From 88f9a623e046703530bc7a9e8fcafbfc9bfe4652 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:56:56 +0000 Subject: [PATCH 1/2] [skip ci] build(deps): Bump the symfony group across 1 directory with 4 updates Bumps the symfony group with 4 updates in the / directory: [symfony/console](https://github.com/symfony/console), [symfony/http-foundation](https://github.com/symfony/http-foundation), [symfony/routing](https://github.com/symfony/routing) and [symfony/translation](https://github.com/symfony/translation). Updates `symfony/console` from 7.4.21 to 7.4.23 - [Release notes](https://github.com/symfony/console/releases) - [Changelog](https://github.com/symfony/console/blob/8.2/CHANGELOG.md) - [Commits](https://github.com/symfony/console/compare/v7.4.21...v7.4.23) Updates `symfony/http-foundation` from 7.4.21 to 7.4.23 - [Release notes](https://github.com/symfony/http-foundation/releases) - [Changelog](https://github.com/symfony/http-foundation/blob/8.2/CHANGELOG.md) - [Commits](https://github.com/symfony/http-foundation/compare/v7.4.21...v7.4.23) Updates `symfony/routing` from 6.4.47 to 6.4.50 - [Release notes](https://github.com/symfony/routing/releases) - [Changelog](https://github.com/symfony/routing/blob/8.2/CHANGELOG.md) - [Commits](https://github.com/symfony/routing/compare/v6.4.47...v6.4.50) Updates `symfony/translation` from 6.4.49 to 6.4.50 - [Release notes](https://github.com/symfony/translation/releases) - [Changelog](https://github.com/symfony/translation/blob/8.2/CHANGELOG.md) - [Commits](https://github.com/symfony/translation/compare/v6.4.49...v6.4.50) --- updated-dependencies: - dependency-name: symfony/console dependency-version: 7.4.23 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: symfony - dependency-name: symfony/http-foundation dependency-version: 7.4.23 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: symfony - dependency-name: symfony/routing dependency-version: 6.4.50 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: symfony - dependency-name: symfony/translation dependency-version: 6.4.50 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: symfony ... Signed-off-by: dependabot[bot] --- composer.json | 8 ++--- composer.lock | 92 +++++++++++++++++++++++++-------------------------- 2 files changed, 50 insertions(+), 50 deletions(-) diff --git a/composer.json b/composer.json index ec68bee53..490ec6b6d 100644 --- a/composer.json +++ b/composer.json @@ -57,9 +57,9 @@ "punic/punic": "^3.8", "sabre/dav": "^4.7.0", "stecman/symfony-console-completion": "^0.15.0", - "symfony/console": "^7.4.21", + "symfony/console": "^7.4.23", "symfony/event-dispatcher": "^7.4.17", - "symfony/http-foundation": "^7.4.21", + "symfony/http-foundation": "^7.4.23", "symfony/mailer": "^7.4.22", "symfony/polyfill-intl-grapheme": "^1.41.0", "symfony/polyfill-intl-normalizer": "^1.38.0", @@ -67,9 +67,9 @@ "symfony/polyfill-php85": "^1.41.0", "symfony/polyfill-php86": "^1.41.0", "symfony/process": "^6.4.49", - "symfony/routing": "^6.4.47", + "symfony/routing": "^6.4.50", "symfony/string": "^7.4.15", - "symfony/translation": "^6.4.49", + "symfony/translation": "^6.4.50", "wapmorgan/mp3info": "^0.1.1", "web-auth/webauthn-lib": "^4.9.1" }, diff --git a/composer.lock b/composer.lock index c1ee0cce2..f43c8f803 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "12889a1121a49aeb07b539b9802bb722", + "content-hash": "6e4a7d687ae4b89fcc75db53d926a0b0", "packages": [ { "name": "aws/aws-crt-php", @@ -4464,16 +4464,16 @@ }, { "name": "symfony/console", - "version": "v7.4.21", + "version": "v7.4.23", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "21f1bc2296f7ff6043241a8dcbc09559b3732820" + "reference": "81957c2440c05c962fe8291f318de6e85f8db330" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/21f1bc2296f7ff6043241a8dcbc09559b3732820", - "reference": "21f1bc2296f7ff6043241a8dcbc09559b3732820", + "url": "https://api.github.com/repos/symfony/console/zipball/81957c2440c05c962fe8291f318de6e85f8db330", + "reference": "81957c2440c05c962fe8291f318de6e85f8db330", "shasum": "" }, "require": { @@ -4538,7 +4538,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v7.4.21" + "source": "https://github.com/symfony/console/tree/v7.4.23" }, "funding": [ { @@ -4558,7 +4558,7 @@ "type": "tidelift" } ], - "time": "2026-10-12T18:45:38+00:00" + "time": "2026-11-03T21:47:07+00:00" }, { "name": "symfony/css-selector", @@ -4631,16 +4631,16 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/feb1edf4e546af3b85c5caebe8359a20db230ca3", + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3", "shasum": "" }, "require": { @@ -4653,7 +4653,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -4678,7 +4678,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.8.1" }, "funding": [ { @@ -4698,7 +4698,7 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-09-16T14:15:10+00:00" }, { "name": "symfony/dom-crawler", @@ -5009,16 +5009,16 @@ }, { "name": "symfony/http-foundation", - "version": "v7.4.21", + "version": "v7.4.23", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "58c89144c7a36dd89c3d01917e9fa3a72d8aaf31" + "reference": "7fb73cffa06e2bcc2cb523fcccb1e8174106b206" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/58c89144c7a36dd89c3d01917e9fa3a72d8aaf31", - "reference": "58c89144c7a36dd89c3d01917e9fa3a72d8aaf31", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/7fb73cffa06e2bcc2cb523fcccb1e8174106b206", + "reference": "7fb73cffa06e2bcc2cb523fcccb1e8174106b206", "shasum": "" }, "require": { @@ -5067,7 +5067,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v7.4.21" + "source": "https://github.com/symfony/http-foundation/tree/v7.4.23" }, "funding": [ { @@ -5087,7 +5087,7 @@ "type": "tidelift" } ], - "time": "2026-10-08T16:56:12+00:00" + "time": "2026-11-04T08:27:22+00:00" }, { "name": "symfony/mailer", @@ -5902,16 +5902,16 @@ }, { "name": "symfony/routing", - "version": "v6.4.47", + "version": "v6.4.50", "source": { "type": "git", "url": "https://github.com/symfony/routing.git", - "reference": "641a94df9ad73671abd86bc4303aa301ca555b2b" + "reference": "80253f3a04ea4e1ba4d78690b8a1727ed9f104e0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/routing/zipball/641a94df9ad73671abd86bc4303aa301ca555b2b", - "reference": "641a94df9ad73671abd86bc4303aa301ca555b2b", + "url": "https://api.github.com/repos/symfony/routing/zipball/80253f3a04ea4e1ba4d78690b8a1727ed9f104e0", + "reference": "80253f3a04ea4e1ba4d78690b8a1727ed9f104e0", "shasum": "" }, "require": { @@ -5965,7 +5965,7 @@ "url" ], "support": { - "source": "https://github.com/symfony/routing/tree/v6.4.47" + "source": "https://github.com/symfony/routing/tree/v6.4.50" }, "funding": [ { @@ -5985,20 +5985,20 @@ "type": "tidelift" } ], - "time": "2026-09-28T18:59:50+00:00" + "time": "2026-11-04T08:16:31+00:00" }, { "name": "symfony/service-contracts", - "version": "v3.7.3", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257" + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/052852a96fd5e5ebdb617dba22031e41a3300fb5", + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5", "shasum": "" }, "require": { @@ -6016,7 +6016,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -6052,7 +6052,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/service-contracts/tree/v3.7.3" + "source": "https://github.com/symfony/service-contracts/tree/v3.8.1" }, "funding": [ { @@ -6072,7 +6072,7 @@ "type": "tidelift" } ], - "time": "2026-07-27T15:39:01+00:00" + "time": "2026-10-20T17:38:25+00:00" }, { "name": "symfony/string", @@ -6167,16 +6167,16 @@ }, { "name": "symfony/translation", - "version": "v6.4.49", + "version": "v6.4.50", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "81998c85f03941f8efeb6f44549259066361780b" + "reference": "6a2ba8838bb815b90fe09f4487da9896d7128862" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/81998c85f03941f8efeb6f44549259066361780b", - "reference": "81998c85f03941f8efeb6f44549259066361780b", + "url": "https://api.github.com/repos/symfony/translation/zipball/6a2ba8838bb815b90fe09f4487da9896d7128862", + "reference": "6a2ba8838bb815b90fe09f4487da9896d7128862", "shasum": "" }, "require": { @@ -6242,7 +6242,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v6.4.49" + "source": "https://github.com/symfony/translation/tree/v6.4.50" }, "funding": [ { @@ -6262,20 +6262,20 @@ "type": "tidelift" } ], - "time": "2026-10-25T08:57:29+00:00" + "time": "2026-11-01T19:42:58+00:00" }, { "name": "symfony/translation-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/translation-contracts.git", - "reference": "ccb206b98faccc511ebae8e5fad50f2dc0b30621" + "reference": "0a3ae917402632fcba2aeddae9c98332f3d7dd05" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/ccb206b98faccc511ebae8e5fad50f2dc0b30621", - "reference": "ccb206b98faccc511ebae8e5fad50f2dc0b30621", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/0a3ae917402632fcba2aeddae9c98332f3d7dd05", + "reference": "0a3ae917402632fcba2aeddae9c98332f3d7dd05", "shasum": "" }, "require": { @@ -6288,7 +6288,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -6324,7 +6324,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/translation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/translation-contracts/tree/v3.8.1" }, "funding": [ { @@ -6344,7 +6344,7 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-10-03T08:17:19+00:00" }, { "name": "symfony/uid", From 9dc99ae7dc9add864ca3bb869d151c7316deb8e4 Mon Sep 17 00:00:00 2001 From: nextcloud-command Date: Wed, 18 Nov 2026 20:59:50 +0000 Subject: [PATCH 2/2] chore(autoloader): Dump autoloader Signed-off-by: nextcloud-command --- composer/autoload_classmap.php | 1 + composer/autoload_static.php | 1 + composer/installed.json | 104 +++--- composer/installed.php | 42 +-- symfony/console/Application.php | 4 +- symfony/console/Command/CompleteCommand.php | 50 +++ symfony/console/Command/InvokableCommand.php | 27 +- symfony/console/Command/LockableTrait.php | 16 +- symfony/console/Formatter/OutputFormatter.php | 271 ++++++++++++++-- .../Formatter/OutputFormatterStyle.php | 17 +- symfony/console/Helper/OutputWrapper.php | 4 +- symfony/console/Helper/ProcessHelper.php | 3 +- symfony/console/Helper/ProgressBar.php | 56 +++- symfony/console/Helper/QuestionHelper.php | 4 +- .../console/Helper/SymfonyQuestionHelper.php | 4 +- symfony/console/Helper/Table.php | 298 +++++++++++++----- .../console/Helper/TerminalInputHelper.php | 3 +- symfony/console/Input/ArgvInput.php | 24 +- symfony/console/Input/StringInput.php | 2 +- symfony/console/Logger/ConsoleLogger.php | 3 +- .../console/Output/ConsoleSectionOutput.php | 91 +++++- symfony/console/Style/SymfonyStyle.php | 2 +- .../http-foundation/BinaryFileResponse.php | 12 +- symfony/http-foundation/Cookie.php | 63 +++- symfony/http-foundation/HeaderUtils.php | 2 +- symfony/http-foundation/InputBag.php | 48 ++- symfony/http-foundation/IpUtils.php | 36 +++ symfony/http-foundation/ParameterBag.php | 48 ++- symfony/http-foundation/Request.php | 42 +-- .../RequestMatcher/MethodRequestMatcher.php | 5 + .../Handler/AbstractSessionHandler.php | 6 +- .../Handler/MarshallingSessionHandler.php | 5 + .../Handler/MemcachedSessionHandler.php | 5 + .../Storage/Handler/MongoDbSessionHandler.php | 5 + .../Storage/Handler/NullSessionHandler.php | 5 - .../Storage/Handler/PdoSessionHandler.php | 5 + .../Storage/Handler/RedisSessionHandler.php | 5 + .../Storage/Handler/SessionHandlerFactory.php | 4 +- .../Session/Storage/NativeSessionStorage.php | 7 +- symfony/http-foundation/UrlHelper.php | 24 +- .../Dumper/CompiledUrlMatcherDumper.php | 17 +- .../Dumper/CompiledUrlMatcherTrait.php | 22 +- .../Matcher/RedirectableUrlMatcher.php | 9 + .../routing/Matcher/TraceableUrlMatcher.php | 5 +- symfony/routing/Matcher/UrlMatcher.php | 17 +- symfony/service-contracts/ResetInterface.php | 1 + .../ServiceSubscriberInterface.php | 2 +- .../service-contracts/ShutdownInterface.php | 24 ++ .../LocaleAwareInterface.php | 3 + .../TranslatorInterface.php | 2 + .../Provider/AbstractProviderFactory.php | 2 +- 51 files changed, 1143 insertions(+), 315 deletions(-) create mode 100644 symfony/service-contracts/ShutdownInterface.php diff --git a/composer/autoload_classmap.php b/composer/autoload_classmap.php index e5588e65f..ba05c52ab 100644 --- a/composer/autoload_classmap.php +++ b/composer/autoload_classmap.php @@ -3770,6 +3770,7 @@ 'Symfony\\Contracts\\Service\\ServiceProviderInterface' => $vendorDir . '/symfony/service-contracts/ServiceProviderInterface.php', 'Symfony\\Contracts\\Service\\ServiceSubscriberInterface' => $vendorDir . '/symfony/service-contracts/ServiceSubscriberInterface.php', 'Symfony\\Contracts\\Service\\ServiceSubscriberTrait' => $vendorDir . '/symfony/service-contracts/ServiceSubscriberTrait.php', + 'Symfony\\Contracts\\Service\\ShutdownInterface' => $vendorDir . '/symfony/service-contracts/ShutdownInterface.php', 'Symfony\\Contracts\\Translation\\LocaleAwareInterface' => $vendorDir . '/symfony/translation-contracts/LocaleAwareInterface.php', 'Symfony\\Contracts\\Translation\\TranslatableInterface' => $vendorDir . '/symfony/translation-contracts/TranslatableInterface.php', 'Symfony\\Contracts\\Translation\\TranslatorInterface' => $vendorDir . '/symfony/translation-contracts/TranslatorInterface.php', diff --git a/composer/autoload_static.php b/composer/autoload_static.php index 88a3ba00a..a116a11af 100644 --- a/composer/autoload_static.php +++ b/composer/autoload_static.php @@ -4326,6 +4326,7 @@ class ComposerStaticInit2f23f73bc0cc116b4b1eee1521aa8652 'Symfony\\Contracts\\Service\\ServiceProviderInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceProviderInterface.php', 'Symfony\\Contracts\\Service\\ServiceSubscriberInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceSubscriberInterface.php', 'Symfony\\Contracts\\Service\\ServiceSubscriberTrait' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceSubscriberTrait.php', + 'Symfony\\Contracts\\Service\\ShutdownInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ShutdownInterface.php', 'Symfony\\Contracts\\Translation\\LocaleAwareInterface' => __DIR__ . '/..' . '/symfony/translation-contracts/LocaleAwareInterface.php', 'Symfony\\Contracts\\Translation\\TranslatableInterface' => __DIR__ . '/..' . '/symfony/translation-contracts/TranslatableInterface.php', 'Symfony\\Contracts\\Translation\\TranslatorInterface' => __DIR__ . '/..' . '/symfony/translation-contracts/TranslatorInterface.php', diff --git a/composer/installed.json b/composer/installed.json index 5572ee651..6738bf296 100644 --- a/composer/installed.json +++ b/composer/installed.json @@ -4659,17 +4659,17 @@ }, { "name": "symfony/console", - "version": "v7.4.21", - "version_normalized": "7.4.21.0", + "version": "v7.4.23", + "version_normalized": "7.4.23.0", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "21f1bc2296f7ff6043241a8dcbc09559b3732820" + "reference": "81957c2440c05c962fe8291f318de6e85f8db330" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/21f1bc2296f7ff6043241a8dcbc09559b3732820", - "reference": "21f1bc2296f7ff6043241a8dcbc09559b3732820", + "url": "https://api.github.com/repos/symfony/console/zipball/81957c2440c05c962fe8291f318de6e85f8db330", + "reference": "81957c2440c05c962fe8291f318de6e85f8db330", "shasum": "" }, "require": { @@ -4702,7 +4702,7 @@ "symfony/stopwatch": "^6.4|^7.0|^8.0", "symfony/var-dumper": "^6.4|^7.0|^8.0" }, - "time": "2026-10-12T18:45:38+00:00", + "time": "2026-11-03T21:47:07+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -4736,7 +4736,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v7.4.21" + "source": "https://github.com/symfony/console/tree/v7.4.23" }, "funding": [ { @@ -4832,23 +4832,23 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.7.1", - "version_normalized": "3.7.1.0", + "version": "v3.8.1", + "version_normalized": "3.8.1.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/feb1edf4e546af3b85c5caebe8359a20db230ca3", + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3", "shasum": "" }, "require": { "php": ">=8.1" }, - "time": "2026-06-05T06:23:12+00:00", + "time": "2026-09-16T14:15:10+00:00", "type": "library", "extra": { "thanks": { @@ -4856,7 +4856,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "installation-source": "dist", @@ -4882,7 +4882,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.8.1" }, "funding": [ { @@ -5225,17 +5225,17 @@ }, { "name": "symfony/http-foundation", - "version": "v7.4.21", - "version_normalized": "7.4.21.0", + "version": "v7.4.23", + "version_normalized": "7.4.23.0", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "58c89144c7a36dd89c3d01917e9fa3a72d8aaf31" + "reference": "7fb73cffa06e2bcc2cb523fcccb1e8174106b206" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/58c89144c7a36dd89c3d01917e9fa3a72d8aaf31", - "reference": "58c89144c7a36dd89c3d01917e9fa3a72d8aaf31", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/7fb73cffa06e2bcc2cb523fcccb1e8174106b206", + "reference": "7fb73cffa06e2bcc2cb523fcccb1e8174106b206", "shasum": "" }, "require": { @@ -5258,7 +5258,7 @@ "symfony/mime": "^6.4|^7.0|^8.0", "symfony/rate-limiter": "^6.4|^7.0|^8.0" }, - "time": "2026-10-08T16:56:12+00:00", + "time": "2026-11-04T08:27:22+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -5286,7 +5286,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v7.4.21" + "source": "https://github.com/symfony/http-foundation/tree/v7.4.23" }, "funding": [ { @@ -6151,17 +6151,17 @@ }, { "name": "symfony/routing", - "version": "v6.4.47", - "version_normalized": "6.4.47.0", + "version": "v6.4.50", + "version_normalized": "6.4.50.0", "source": { "type": "git", "url": "https://github.com/symfony/routing.git", - "reference": "641a94df9ad73671abd86bc4303aa301ca555b2b" + "reference": "80253f3a04ea4e1ba4d78690b8a1727ed9f104e0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/routing/zipball/641a94df9ad73671abd86bc4303aa301ca555b2b", - "reference": "641a94df9ad73671abd86bc4303aa301ca555b2b", + "url": "https://api.github.com/repos/symfony/routing/zipball/80253f3a04ea4e1ba4d78690b8a1727ed9f104e0", + "reference": "80253f3a04ea4e1ba4d78690b8a1727ed9f104e0", "shasum": "" }, "require": { @@ -6183,7 +6183,7 @@ "symfony/http-foundation": "^5.4|^6.0|^7.0", "symfony/yaml": "^5.4|^6.0|^7.0" }, - "time": "2026-09-28T18:59:50+00:00", + "time": "2026-11-04T08:16:31+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -6217,7 +6217,7 @@ "url" ], "support": { - "source": "https://github.com/symfony/routing/tree/v6.4.47" + "source": "https://github.com/symfony/routing/tree/v6.4.50" }, "funding": [ { @@ -6241,17 +6241,17 @@ }, { "name": "symfony/service-contracts", - "version": "v3.7.3", - "version_normalized": "3.7.3.0", + "version": "v3.8.1", + "version_normalized": "3.8.1.0", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257" + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/052852a96fd5e5ebdb617dba22031e41a3300fb5", + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5", "shasum": "" }, "require": { @@ -6262,7 +6262,7 @@ "conflict": { "ext-psr": "<1.1|>=2" }, - "time": "2026-07-27T15:39:01+00:00", + "time": "2026-10-20T17:38:25+00:00", "type": "library", "extra": { "thanks": { @@ -6270,7 +6270,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "installation-source": "dist", @@ -6307,7 +6307,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/service-contracts/tree/v3.7.3" + "source": "https://github.com/symfony/service-contracts/tree/v3.8.1" }, "funding": [ { @@ -6425,17 +6425,17 @@ }, { "name": "symfony/translation", - "version": "v6.4.49", - "version_normalized": "6.4.49.0", + "version": "v6.4.50", + "version_normalized": "6.4.50.0", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "81998c85f03941f8efeb6f44549259066361780b" + "reference": "6a2ba8838bb815b90fe09f4487da9896d7128862" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/81998c85f03941f8efeb6f44549259066361780b", - "reference": "81998c85f03941f8efeb6f44549259066361780b", + "url": "https://api.github.com/repos/symfony/translation/zipball/6a2ba8838bb815b90fe09f4487da9896d7128862", + "reference": "6a2ba8838bb815b90fe09f4487da9896d7128862", "shasum": "" }, "require": { @@ -6472,7 +6472,7 @@ "symfony/service-contracts": "^2.5|^3", "symfony/yaml": "^5.4|^6.0|^7.0" }, - "time": "2026-10-25T08:57:29+00:00", + "time": "2026-11-01T19:42:58+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -6503,7 +6503,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v6.4.49" + "source": "https://github.com/symfony/translation/tree/v6.4.50" }, "funding": [ { @@ -6527,23 +6527,23 @@ }, { "name": "symfony/translation-contracts", - "version": "v3.7.1", - "version_normalized": "3.7.1.0", + "version": "v3.8.1", + "version_normalized": "3.8.1.0", "source": { "type": "git", "url": "https://github.com/symfony/translation-contracts.git", - "reference": "ccb206b98faccc511ebae8e5fad50f2dc0b30621" + "reference": "0a3ae917402632fcba2aeddae9c98332f3d7dd05" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/ccb206b98faccc511ebae8e5fad50f2dc0b30621", - "reference": "ccb206b98faccc511ebae8e5fad50f2dc0b30621", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/0a3ae917402632fcba2aeddae9c98332f3d7dd05", + "reference": "0a3ae917402632fcba2aeddae9c98332f3d7dd05", "shasum": "" }, "require": { "php": ">=8.1" }, - "time": "2026-06-05T06:23:12+00:00", + "time": "2026-10-03T08:17:19+00:00", "type": "library", "extra": { "thanks": { @@ -6551,7 +6551,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "installation-source": "dist", @@ -6588,7 +6588,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/translation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/translation-contracts/tree/v3.8.1" }, "funding": [ { diff --git a/composer/installed.php b/composer/installed.php index 73b5b9409..25038b6be 100644 --- a/composer/installed.php +++ b/composer/installed.php @@ -695,9 +695,9 @@ 'dev_requirement' => false, ), 'symfony/console' => array( - 'pretty_version' => 'v7.4.21', - 'version' => '7.4.21.0', - 'reference' => '21f1bc2296f7ff6043241a8dcbc09559b3732820', + 'pretty_version' => 'v7.4.23', + 'version' => '7.4.23.0', + 'reference' => '81957c2440c05c962fe8291f318de6e85f8db330', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/console', 'aliases' => array(), @@ -713,9 +713,9 @@ 'dev_requirement' => false, ), 'symfony/deprecation-contracts' => array( - 'pretty_version' => 'v3.7.1', - 'version' => '3.7.1.0', - 'reference' => 'f3202fa1b5097b0af062dc978b32ecf63404e31d', + 'pretty_version' => 'v3.8.1', + 'version' => '3.8.1.0', + 'reference' => 'feb1edf4e546af3b85c5caebe8359a20db230ca3', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', 'aliases' => array(), @@ -764,9 +764,9 @@ 'dev_requirement' => false, ), 'symfony/http-foundation' => array( - 'pretty_version' => 'v7.4.21', - 'version' => '7.4.21.0', - 'reference' => '58c89144c7a36dd89c3d01917e9fa3a72d8aaf31', + 'pretty_version' => 'v7.4.23', + 'version' => '7.4.23.0', + 'reference' => '7fb73cffa06e2bcc2cb523fcccb1e8174106b206', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/http-foundation', 'aliases' => array(), @@ -899,18 +899,18 @@ 'dev_requirement' => false, ), 'symfony/routing' => array( - 'pretty_version' => 'v6.4.47', - 'version' => '6.4.47.0', - 'reference' => '641a94df9ad73671abd86bc4303aa301ca555b2b', + 'pretty_version' => 'v6.4.50', + 'version' => '6.4.50.0', + 'reference' => '80253f3a04ea4e1ba4d78690b8a1727ed9f104e0', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/routing', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/service-contracts' => array( - 'pretty_version' => 'v3.7.3', - 'version' => '3.7.3.0', - 'reference' => '15e6a07ec2a2c75ceb1b21dd98105ee8456d2257', + 'pretty_version' => 'v3.8.1', + 'version' => '3.8.1.0', + 'reference' => '052852a96fd5e5ebdb617dba22031e41a3300fb5', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/service-contracts', 'aliases' => array(), @@ -926,18 +926,18 @@ 'dev_requirement' => false, ), 'symfony/translation' => array( - 'pretty_version' => 'v6.4.49', - 'version' => '6.4.49.0', - 'reference' => '81998c85f03941f8efeb6f44549259066361780b', + 'pretty_version' => 'v6.4.50', + 'version' => '6.4.50.0', + 'reference' => '6a2ba8838bb815b90fe09f4487da9896d7128862', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/translation', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/translation-contracts' => array( - 'pretty_version' => 'v3.7.1', - 'version' => '3.7.1.0', - 'reference' => 'ccb206b98faccc511ebae8e5fad50f2dc0b30621', + 'pretty_version' => 'v3.8.1', + 'version' => '3.8.1.0', + 'reference' => '0a3ae917402632fcba2aeddae9c98332f3d7dd05', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/translation-contracts', 'aliases' => array(), diff --git a/symfony/console/Application.php b/symfony/console/Application.php index 68acadf57..41ddc95b7 100644 --- a/symfony/console/Application.php +++ b/symfony/console/Application.php @@ -1045,7 +1045,9 @@ protected function doRunCommand(Command $command, InputInterface $input, OutputI // We register application signals, so that we can dispatch the event foreach ($this->signalsToDispatchEvent as $signal) { - $signalEvent = new ConsoleSignalEvent($command, $input, $output, $signal); + // When this application runs inside another application that handles the signal, the outer application decides if the process exits + $previousHandler = pcntl_signal_get_handler($signal); + $signalEvent = new ConsoleSignalEvent($command, $input, $output, $signal, \is_array($previousHandler) && $previousHandler[0] instanceof SignalRegistry ? false : 0); $alarmEvent = \SIGALRM === $signal ? new ConsoleAlarmEvent($command, $input, $output) : null; $signalRegistry->register($signal, function ($signal) use ($signalEvent, $alarmEvent, $command, $commandSignals, $input, $output) { diff --git a/symfony/console/Command/CompleteCommand.php b/symfony/console/Command/CompleteCommand.php index 44d23cc63..bdc3a8c53 100644 --- a/symfony/console/Command/CompleteCommand.php +++ b/symfony/console/Command/CompleteCommand.php @@ -11,6 +11,7 @@ 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; @@ -20,6 +21,7 @@ use Symfony\Component\Console\Completion\Output\ZshCompletionOutput; use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; @@ -35,6 +37,7 @@ final class CompleteCommand extends Command public const COMPLETION_API_VERSION = '1'; private array $completionOutputs; + private ?InputDefinition $fullDefinition = null; private bool $isDebug = false; /** @@ -52,6 +55,53 @@ public function __construct(array $completionOutputs = []) parent::__construct(); } + public function setApplication(?Application $application): void + { + $this->fullDefinition = null; + + parent::setApplication($application); + } + + public function setDefinition(array|InputDefinition $definition): static + { + $this->fullDefinition = null; + + return parent::setDefinition($definition); + } + + /** + * @internal + */ + public function mergeApplicationDefinition(bool $mergeArgs = true): void + { + if (!$application = $this->getApplication()) { + return; + } + + $definition = $this->getNativeDefinition(); + $this->fullDefinition = new InputDefinition(); + $this->fullDefinition->setOptions($definition->getOptions()); + + foreach ($application->getDefinition()->getOptions() as $option) { + // the completion scripts rely on the options of this command, they win over the conflicting application ones + if ($definition->hasOption($option->getName()) || array_filter(explode('|', $option->getShortcut() ?? ''), $definition->hasShortcut(...))) { + continue; + } + + $this->fullDefinition->addOption($option); + } + + if ($mergeArgs) { + $this->fullDefinition->setArguments($application->getDefinition()->getArguments()); + } + $this->fullDefinition->addArguments($definition->getArguments()); + } + + public function getDefinition(): InputDefinition + { + return $this->fullDefinition ?? parent::getDefinition(); + } + protected function configure(): void { $this diff --git a/symfony/console/Command/InvokableCommand.php b/symfony/console/Command/InvokableCommand.php index 016da5a01..808083578 100644 --- a/symfony/console/Command/InvokableCommand.php +++ b/symfony/console/Command/InvokableCommand.php @@ -35,6 +35,11 @@ */ class InvokableCommand implements SignalableCommandInterface { + /** + * @var list + */ + private static array $running = []; + private readonly ?SignalableCommandInterface $signalableCommand; private readonly \ReflectionFunction $invokable; /** @@ -58,7 +63,13 @@ public function __construct( */ public function __invoke(InputInterface $input, OutputInterface $output): int { - $statusCode = $this->invokable->invoke(...$this->getParameters($this->invokable, $input, $output)); + self::$running[] = [$this->invokable->getClosureThis(), $this->command]; + + try { + $statusCode = $this->invokable->invoke(...$this->getParameters($this->invokable, $input, $output)); + } finally { + array_pop(self::$running); + } if (!\is_int($statusCode)) { if ($this->triggerDeprecations) { @@ -114,6 +125,20 @@ public function getCode(): callable return $this->code; } + /** + * Returns the command that is currently running the given object, if any. + */ + public static function getRunningCommand(object $code): ?Command + { + for ($i = \count(self::$running) - 1; 0 <= $i; --$i) { + if ($code === self::$running[$i][0]) { + return self::$running[$i][1]; + } + } + + return null; + } + private function getClosure(callable $code): \Closure { if (!$code instanceof \Closure) { diff --git a/symfony/console/Command/LockableTrait.php b/symfony/console/Command/LockableTrait.php index b7abd2fdc..25261a755 100644 --- a/symfony/console/Command/LockableTrait.php +++ b/symfony/console/Command/LockableTrait.php @@ -55,20 +55,22 @@ private function lock(?string $name = null, bool $blocking = false): bool if (!$name) { if ($this instanceof Command) { $name = $this->getName(); + } elseif ($command = InvokableCommand::getRunningCommand($this)) { + $name = $command->getName(); } elseif ($attribute = (new \ReflectionClass($this::class))->getAttributes(AsCommand::class)) { - $name = $attribute[0]->newInstance()->name; + $name = explode('|', ltrim($attribute[0]->newInstance()->name, '|'), 2)[0]; } else { throw new LogicException(\sprintf('Lock name missing: provide it via "%s()", #[AsCommand] attribute, or by extending Command class.', __METHOD__)); } } - $this->lock = $this->lockFactory->createLock($name); - if (!$this->lock->acquire($blocking)) { - $this->lock = null; - + $lock = $this->lockFactory->createLock($name); + if (!$lock->acquire($blocking)) { return false; } + $this->lock = $lock; + return true; } @@ -77,9 +79,9 @@ private function lock(?string $name = null, bool $blocking = false): bool */ private function release(): void { - if ($this->lock) { - $this->lock->release(); + if ($lock = $this->lock) { $this->lock = null; + $lock->release(); } } } diff --git a/symfony/console/Formatter/OutputFormatter.php b/symfony/console/Formatter/OutputFormatter.php index 1e757183e..21800ebe6 100644 --- a/symfony/console/Formatter/OutputFormatter.php +++ b/symfony/console/Formatter/OutputFormatter.php @@ -24,8 +24,12 @@ */ class OutputFormatter implements WrappableOutputFormatterInterface { + private const ANSI_PATTERN = '\\x1B(?:\\[[0-9;:]*m|\\]8;[^;]*;[^\\x1B]*\\x1B\\\\)'; + private const ANSI_REGEX = '/'.self::ANSI_PATTERN.'/'; + private array $styles = []; private OutputFormatterStyleStack $styleStack; + private array $charWidths = []; public function __clone() { @@ -128,6 +132,7 @@ public function formatAndWrap(?string $message, int $width): string $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*'; $closeTagRegex = '[a-z][^<>]*+'; $currentLineLength = 0; + $lineBreak = false; preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE); foreach ($matches[0] as $i => $match) { $pos = $match[1]; @@ -139,7 +144,7 @@ public function formatAndWrap(?string $message, int $width): string // tags are delimited by "<" and ">", which are ASCII, so a tag offset can never // fall inside a multibyte sequence: slicing by bytes is safe here - $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength); + $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $width, $currentLineLength, $lineBreak); $offset = $pos + \strlen($text); // opening tag? @@ -153,7 +158,7 @@ public function formatAndWrap(?string $message, int $width): string // $this->styleStack->pop(); } elseif (null === $style = $this->createStyleFromString($tag)) { - $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength); + $output .= $this->applyCurrentStyle($text, $width, $currentLineLength, $lineBreak); } elseif ($open) { $this->styleStack->push($style); } else { @@ -161,9 +166,18 @@ public function formatAndWrap(?string $message, int $width): string } } - $output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength); + $output .= $this->applyCurrentStyle(substr($message, $offset), $width, $currentLineLength, $lineBreak); + + if ($lineBreak) { + $output .= "\n"; + } + + if ($width && str_contains($output, "\r")) { + // keep "\r\n" line breaks together when ANSI codes end the line + $output = preg_replace('/\r((?:'.self::ANSI_PATTERN.')++)(?=\n|$)/', "\$1\r", $output); + } - return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']); + return str_replace("\0", '\\', $output); } public function getStyleStack(): OutputFormatterStyleStack @@ -176,8 +190,8 @@ public function getStyleStack(): OutputFormatterStyleStack */ private function createStyleFromString(string $string): ?OutputFormatterStyleInterface { - if (isset($this->styles[$string])) { - return $this->styles[$string]; + if (isset($this->styles[$lowerString = strtolower($string)])) { + return $this->styles[$lowerString]; } if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) { @@ -213,58 +227,108 @@ private function createStyleFromString(string $string): ?OutputFormatterStyleInt /** * Applies current style from stack to text, if must be applied. */ - private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string + private function applyCurrentStyle(string $text, int $width, int &$currentLineLength, bool &$lineBreak): string { if ('' === $text) { return ''; } - if (!$width) { + if (!$width || str_contains($text, "\e") && '' === preg_replace(self::ANSI_REGEX, '', $text)) { + $text = str_replace(['\\<', '\\>'], ['<', '>'], $text); + return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text; } - if (!$currentLineLength && '' !== $current) { - $text = ltrim($text); + $text = str_replace(['\\<', '\\>'], ['<', '>'], $text); + $prefix = ''; + $visibleText = str_contains($text, "\e") ? preg_replace(self::ANSI_REGEX, '', $text) : $text; + + if ($currentLineLength >= $width) { + // the current line is full: drop the whitespace that follows and break the line before the next character + if (str_contains($text, "\e")) { + $text = preg_replace_callback('/^(?:[\\x00\\x09\\x0B\\x0D\\x20]|'.self::ANSI_PATTERN.')++/', static function ($match) { + preg_match_all(self::ANSI_REGEX, $match[0], $ansi); + + return implode('', $ansi[0]); + }, $text); + $visibleText = ltrim($visibleText, " \t\r\0\x0B"); + } else { + $text = $visibleText = ltrim($text, " \t\r\0\x0B"); + } + + // whitespace at the end of the message still breaks the line + if ($lineBreak = '' === $visibleText) { + return '' === $text || !$this->isDecorated() ? $text : $this->styleStack->getCurrent()->apply($text); + } + + if ("\n" !== $visibleText[0]) { + $prefix = "\n"; + } + + $currentLineLength = 0; } + $trailingNewlines = substr($visibleText, \strlen(rtrim($visibleText, "\r\n"))); + if ($currentLineLength) { $lines = explode("\n", $text, 2); - $prefix = Helper::substr($lines[0], 0, $i = $width - $currentLineLength)."\n"; - $text = Helper::substr($lines[0], $i); + $eol = "\n"; + if (isset($lines[1]) && str_ends_with($lines[0], "\r")) { + $lines[0] = substr($lines[0], 0, -1); + $eol = "\r\n"; + } + $i = $width - $currentLineLength; + if ($widths = $this->getWidths($lines[0])) { + $room = $i; + $i = \count($widths); + foreach ($widths as $j => $charWidth) { + if (0 > $room -= $charWidth) { + $i = $j; + break; + } + } + } + $prefix = ($i ? $this->substr($lines[0], 0, $i) : '')."\n"; + $text = $i ? $this->substr($lines[0], $i) : $lines[0]; if (isset($lines[1])) { // $prefix may contain the full first line in which the \n is already a part of $prefix. if ('' !== $text) { - $text .= "\n"; + $text .= $eol; + } else { + $prefix = substr($prefix, 0, -1).$eol; } $text .= $lines[1]; } - } else { - $prefix = ''; } - preg_match('~(\\n)$~', $text, $matches); $text = $prefix.$this->addLineBreaks($text, $width); - $text = rtrim($text, "\n").($matches[1] ?? ''); - - if (!$currentLineLength && '' !== $current && !str_ends_with($current, "\n")) { - $text = "\n".$text; + if (str_contains($text, "\e")) { + $parts = preg_split('/('.self::ANSI_PATTERN.')/', $text, -1, \PREG_SPLIT_DELIM_CAPTURE); + $sequences = ''; + for ($i = \count($parts) - 1; $i >= 0; --$i) { + if ($i % 2) { + $sequences = $parts[$i].$sequences; + } elseif ('' !== $parts[$i] = rtrim($parts[$i], "\r\n")) { + break; + } + } + $text = implode('', \array_slice($parts, 0, $i + 1)).$sequences; + } else { + $text = rtrim($text, "\r\n"); } + $text .= $trailingNewlines; $lines = explode("\n", $text); foreach ($lines as $i => $line) { - $currentLineLength = 0 === $i ? $currentLineLength + Helper::length($line) : Helper::length($line); - if ($width <= $currentLineLength) { - $currentLineLength = 0; - } + $lineLength = array_sum($this->getWidths($line)) ?: Helper::length(str_contains($line, "\e") ? preg_replace(self::ANSI_REGEX, '', $line) : $line); + $currentLineLength = 0 === $i ? $currentLineLength + $lineLength : $lineLength; } - if ($this->isDecorated()) { - foreach ($lines as $i => $line) { - $lines[$i] = $this->styleStack->getCurrent()->apply($line); - } + foreach ($lines as $i => $line) { + $lines[$i] = $this->isDecorated() ? $this->styleStack->getCurrent()->apply($line) : $line; } return implode("\n", $lines); @@ -273,7 +337,156 @@ private function applyCurrentStyle(string $text, string $current, int $width, in private function addLineBreaks(string $text, int $width): string { $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8'; + $widths = $this->getWidths($text); + + if (!$widths && !str_contains($text, "\e") && !str_contains($text, "\r\n")) { + return b($text)->toUnicodeString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding); + } + + $chars = []; + $mask = $pending = ''; + foreach ($this->getTokens($text) as $token) { + if (preg_match(self::ANSI_REGEX, $token)) { + $pending .= $token; + continue; + } + $chars[] = [$pending, $token]; + $pending = ''; + $mask .= "\n" === $token || "\r\n" === $token ? '#' : (' ' === $token ? ' ' : '?'); + } + + if (!$chars) { + return $pending; + } + + $wrapped = rtrim($mask, '#'); + $mask = ($widths ? $this->wordwrap($wrapped, $width, $widths) : wordwrap($wrapped, $width, '#', true)).substr($mask, \strlen($wrapped)); + $result = ''; + $j = 0; + foreach (str_split($mask) as $char) { + if ('#' === $char) { + $eol = "\n"; + if (isset($chars[$j]) && ("\n" === $chars[$j][1] || "\r\n" === $chars[$j][1] || ' ' === $chars[$j][1])) { + $eol = ' ' === $chars[$j][1] ? "\n" : $chars[$j][1]; + $result .= $chars[$j++][0]; + } + $result .= $eol; + } else { + $result .= implode('', $chars[$j++]); + } + } + + return $result.$pending; + } + + private function substr(string $text, int $from, ?int $length = null): string + { + if (!str_contains($text, "\e")) { + return Helper::substr($text, $from, $length); + } + + $result = ''; + $position = 0; + foreach ($this->getTokens($text) as $token) { + $isAnsi = preg_match(self::ANSI_REGEX, $token); + if ($position >= $from && (null === $length || $position < $from + $length || $isAnsi && $position === $from + $length) + && (!$isAnsi || !$from || $position > $from) + ) { + $result .= $token; + } + if (!$isAnsi) { + ++$position; + } + } + + return $result; + } + + private function getTokens(string $text): iterable + { + $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8'; + foreach (preg_split('/('.self::ANSI_PATTERN.')/', $text, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $part) { + if (preg_match(self::ANSI_REGEX, $part)) { + yield $part; + continue; + } + foreach (b($part)->toUnicodeString($encoding)->chunk() as $char) { + yield (string) $char->toByteString($encoding); + } + } + } + + /** + * Returns the number of columns of each visible character, or an empty array when none uses more than one column. + * + * @return list + */ + private function getWidths(string $text): array + { + if (!preg_match('/[^\x00-\x{10FF}]/u', $text)) { + return []; + } + + $widths = []; + $wide = false; + foreach ($this->getTokens($text) as $token) { + if (!preg_match(self::ANSI_REGEX, $token)) { + $widths[] = $charWidth = 2 < \strlen($token) ? ($this->charWidths[$token] ??= Helper::width($token)) : 1; + $wide = $wide || 1 < $charWidth; + } + } + + return $wide ? $widths : []; + } + + /** + * Wraps a mask like wordwrap() does when cutting long words, but using the number of columns of each character. + * + * @param list $widths + */ + private function wordwrap(string $mask, int $width, array $widths): string + { + $result = ''; + $start = $lastSpace = $lineWidth = 0; + + for ($i = 0, $length = \strlen($mask); $i < $length; ++$i) { + if ('#' === $mask[$i]) { + $result .= substr($mask, $start, $i + 1 - $start); + $start = $lastSpace = $i + 1; + $lineWidth = 0; + + continue; + } + + if (' ' === $mask[$i]) { + if ($lineWidth >= $width) { + $result .= substr($mask, $start, $i - $start).'#'; + $start = $i + 1; + $lineWidth = 0; + } else { + ++$lineWidth; + } + $lastSpace = $i; + + continue; + } + + if ($lineWidth + $widths[$i] > $width && $start < $lastSpace) { + $result .= substr($mask, $start, $lastSpace - $start).'#'; + $start = $lastSpace = $lastSpace + 1; + $lineWidth = array_sum(\array_slice($widths, $start, $i - $start)); + } + + // cut long words, and also before a wide character that still doesn't fit after breaking at the last space + if ($lineWidth && $lineWidth + $widths[$i] > $width) { + $result .= substr($mask, $start, $i - $start).'#'; + $start = $lastSpace = $i; + $lineWidth = 0; + } + + $lineWidth += $widths[$i]; + } - return b($text)->toUnicodeString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding); + return $result.substr($mask, $start); } } diff --git a/symfony/console/Formatter/OutputFormatterStyle.php b/symfony/console/Formatter/OutputFormatterStyle.php index 20a65b517..de800f98b 100644 --- a/symfony/console/Formatter/OutputFormatterStyle.php +++ b/symfony/console/Formatter/OutputFormatterStyle.php @@ -40,12 +40,14 @@ public function __construct(?string $foreground = null, ?string $background = nu public function setForeground(?string $color): void { - $this->color = new Color($this->foreground = $color ?: '', $this->background, $this->options); + $this->color = new Color($foreground = $color ?: '', $this->background, $this->options); + $this->foreground = $foreground; } public function setBackground(?string $color): void { - $this->color = new Color($this->foreground, $this->background = $color ?: '', $this->options); + $this->color = new Color($this->foreground, $background = $color ?: '', $this->options); + $this->background = $background; } public function setHref(string $url): void @@ -55,23 +57,20 @@ public function setHref(string $url): void public function setOption(string $option): void { + $this->color = new Color($this->foreground, $this->background, [...$this->options, $option]); $this->options[] = $option; - $this->color = new Color($this->foreground, $this->background, $this->options); } public function unsetOption(string $option): void { - $pos = array_search($option, $this->options); - if (false !== $pos) { - unset($this->options[$pos]); - } - + $this->options = array_diff($this->options, [$option]); $this->color = new Color($this->foreground, $this->background, $this->options); } public function setOptions(array $options): void { - $this->color = new Color($this->foreground, $this->background, $this->options = $options); + $this->color = new Color($this->foreground, $this->background, $options); + $this->options = $options; } public function apply(string $text): string diff --git a/symfony/console/Helper/OutputWrapper.php b/symfony/console/Helper/OutputWrapper.php index 1e3ac908d..fb977443a 100644 --- a/symfony/console/Helper/OutputWrapper.php +++ b/symfony/console/Helper/OutputWrapper.php @@ -71,7 +71,9 @@ public function wrap(string $text, int $width, string $break = "\n"): string // the u modifier counts characters instead of bytes, but preg_replace() returns null // on malformed UTF-8, which would empty the text $modifiers = preg_match('//u', $text) ? 'imux' : 'imx'; - $pattern = \sprintf('#(?:((?>(%1$s)((?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|(%1$s))(?:\r?\n)?|(?:\r?\n|$))#%2$s', $rowPattern, $modifiers); + // a line cut inside a word never ends between a backslash and the "<" or ">" it escapes, + // or the escaped character would start the next line as a tag delimiter + $pattern = \sprintf('#(?:((?>(%1$s)((?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|(%1$s)(?!(?<=\\\\)[<>]))(?:\r?\n)?|(?:\r?\n|$))#%2$s', $rowPattern, $modifiers); $output = rtrim(preg_replace($pattern, '\\1'.$break, $text), $break); return str_replace(' '.$break, $break, $output); diff --git a/symfony/console/Helper/ProcessHelper.php b/symfony/console/Helper/ProcessHelper.php index 2b12ec5e9..430d01874 100644 --- a/symfony/console/Helper/ProcessHelper.php +++ b/symfony/console/Helper/ProcessHelper.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Console\Helper; +use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\Exception\ProcessFailedException; @@ -127,7 +128,7 @@ public function wrapCallback(OutputInterface $output, Process $process, ?callabl private function escapeString(string $str): string { - return str_replace('<', '\\<', $str); + return OutputFormatter::escapeTrailingBackslash(str_replace('<', '\\<', $str)); } public function getName(): string diff --git a/symfony/console/Helper/ProgressBar.php b/symfony/console/Helper/ProgressBar.php index 0ce498643..b1ade17c0 100644 --- a/symfony/console/Helper/ProgressBar.php +++ b/symfony/console/Helper/ProgressBar.php @@ -58,6 +58,9 @@ final class ProgressBar private bool $overwrite = true; private Terminal $terminal; private ?string $previousMessage = null; + private int $lastDrawnStep = 0; + private ?int $lastDrawnMax = null; + private bool $maxInferred = false; private Cursor $cursor; private array $placeholders = []; @@ -319,17 +322,20 @@ public function iterate(iterable $iterable, ?int $max = null): iterable $max = null; } + $maxInferred = null === $max && is_countable($iterable); $max ??= is_countable($iterable) ? \count($iterable) : null; if (0 === $max) { $this->max = 0; $this->stepWidth = 2; + $this->maxInferred = true; $this->finish(); return; } $this->start($max); + $this->maxInferred = $maxInferred; foreach ($iterable as $key => $value) { yield $key => $value; @@ -348,16 +354,28 @@ public function iterate(iterable $iterable, ?int $max = null): iterable */ public function start(?int $max = null, int $startAt = 0): void { + $startAt = max(0, $startAt); $this->startTime = time(); $this->step = $startAt; $this->startingStep = $startAt; - $startAt > 0 ? $this->setProgress($startAt) : $this->percent = 0.0; - if (null !== $max) { $this->setMaxSteps($max); + } elseif ($this->maxInferred) { + // drop the max that a previous iterate() or finish() inferred + $this->setMaxSteps(null); + } + + if ($this->max && $startAt > $this->max) { + $this->max = $startAt; } + $this->percent = 0 === $startAt ? 0.0 : match ($this->max) { + null => 0, + 0 => 1, + default => (float) $startAt / $this->max, + }; + $this->display(); } @@ -423,6 +441,7 @@ public function setMaxSteps(?int $max): void } $this->format = null; + $this->maxInferred = false; if (null === $max) { $this->max = null; $this->stepWidth = 4; @@ -430,6 +449,12 @@ public function setMaxSteps(?int $max): void $this->max = max(0, $max); $this->stepWidth = Helper::width((string) $this->max); } + + $this->percent = match ($this->max) { + null => 0, + 0 => 1, + default => min(1, (float) $this->step / $this->max), + }; } /** @@ -437,12 +462,24 @@ public function setMaxSteps(?int $max): void */ public function finish(): void { + if ($this->max && $this->step > $this->max) { + // the max was lowered below the step with setMaxSteps(), raise it like setProgress() does + $this->max = $this->step; + } + + $max = $this->max; + if (null === $this->max) { $this->max = $this->step; + $this->percent = 1.0; + $this->maxInferred = true; } - if (($this->step === $this->max || null === $this->max) && !$this->overwrite) { - // prevent double 100% output + if ($this->step === $this->max && !$this->overwrite && $this->lastDrawnStep === $this->step && \in_array($this->lastDrawnMax, [$max, $this->max], true)) { + // prevent double output when the last frame already shows this step, against the max it had before finishing or this one + // remember this max as drawn, so that calling finish() again does not draw the frame either + $this->lastDrawnMax = $this->max; + return; } @@ -463,6 +500,8 @@ public function display(): void } $this->overwrite($this->buildLine()); + $this->lastDrawnStep = $this->step; + $this->lastDrawnMax = $this->max; } /** @@ -521,13 +560,6 @@ private function overwrite(string $message): void --$lineCount; } - 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"); @@ -541,7 +573,7 @@ private function overwrite(string $message): void $this->cursor->clearLine(); } } - } elseif ($this->step > 0) { + } elseif (null !== $this->previousMessage) { $message = \PHP_EOL.$message; } diff --git a/symfony/console/Helper/QuestionHelper.php b/symfony/console/Helper/QuestionHelper.php index ea82acc18..119b5627c 100644 --- a/symfony/console/Helper/QuestionHelper.php +++ b/symfony/console/Helper/QuestionHelper.php @@ -211,7 +211,7 @@ protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string foreach ($choices as $key => $value) { $padding = str_repeat(' ', $maxWidth - self::width($key)); - $messages[] = \sprintf(" [<$tag>%s$padding] %s", $key, $value); + $messages[] = \sprintf(" [<$tag>%s$padding] %s", OutputFormatter::escapeTrailingBackslash($key), $value); } return $messages; @@ -225,7 +225,7 @@ protected function writeError(OutputInterface $output, \Exception $error): void if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) { $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'); } else { - $message = ''.$error->getMessage().''; + $message = ''.OutputFormatter::escapeTrailingBackslash($error->getMessage()).''; } $output->writeln($message); diff --git a/symfony/console/Helper/SymfonyQuestionHelper.php b/symfony/console/Helper/SymfonyQuestionHelper.php index cf6a6ddd6..f48e869e8 100644 --- a/symfony/console/Helper/SymfonyQuestionHelper.php +++ b/symfony/console/Helper/SymfonyQuestionHelper.php @@ -53,13 +53,13 @@ protected function writePrompt(OutputInterface $output, Question $question): voi $default[$key] = $choices[trim($value)]; } - $text = \sprintf(' %s [%s]:', $text, implode(', ', $default)); + $text = \sprintf(' %s [%s]:', $text, OutputFormatter::escapeTrailingBackslash(implode(', ', $default))); break; case $question instanceof ChoiceQuestion: $choices = $question->getChoices(); - $text = \sprintf(' %s [%s]:', $text, $choices[$default] ?? $default); + $text = \sprintf(' %s [%s]:', $text, OutputFormatter::escapeTrailingBackslash($choices[$default] ?? $default)); break; diff --git a/symfony/console/Helper/Table.php b/symfony/console/Helper/Table.php index 80d7ed6ee..bced98a12 100644 --- a/symfony/console/Helper/Table.php +++ b/symfony/console/Helper/Table.php @@ -15,6 +15,7 @@ use Symfony\Component\Console\Exception\RuntimeException; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Formatter\WrappableOutputFormatterInterface; +use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\ConsoleSectionOutput; use Symfony\Component\Console\Output\OutputInterface; @@ -50,7 +51,9 @@ class Table private array $columnWidths = []; private array $configuredColumnWidths = []; private array $columnMaxWidths = []; - private bool $rendered = false; + private array $renderedLines = []; + private array $tagStyles = []; + private ?\WeakMap $rowspanLines = null; private string $displayOrientation = self::DISPLAY_ORIENTATION_DEFAULT; private static array $styles; @@ -235,16 +238,40 @@ public function addRow(TableSeparator|array $row): static */ public function appendRow(TableSeparator|array $row): static { - if (!$this->output instanceof ConsoleSectionOutput) { + $output = $this->output; + if (!$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()); + if (!$output->isDecorated()) { + $this->addRow($row); + $this->render(); + + return $this; + } + + $previous = $this->renderedLines; + if ($previous && !str_ends_with($output->getContent(), implode('', $previous))) { + // the section was cleared or written to since the table was rendered: keep its content and render the whole table again + $previous = []; } $this->addRow($row); - $this->render(); + $lines = $this->renderLines(); + + // Only rewrite the lines after the part both renderings have in common. + // While no column gets wider, that is just the bottom border, so lines that scrolled out of the terminal, which can't be cleared, are not touched. + $common = 0; + $max = min(\count($previous), \count($lines)); + while ($common < $max && $previous[$common] === $lines[$common]) { + ++$common; + } + + if (\count($previous) > $common) { + $output->clear(\count($previous) - $common); + } + $output->write(implode('', \array_slice($lines, $common)), false, OutputInterface::OUTPUT_RAW); + $this->renderedLines = $lines; return $this; } @@ -254,7 +281,7 @@ public function appendRow(TableSeparator|array $row): static */ public function setRow(int|string $column, array $row): static { - $this->rows[$column] = $row; + $this->rows[$column] = array_values($row); return $this; } @@ -314,6 +341,15 @@ public function setVertical(bool $vertical = true): static */ public function render(): void { + if ($this->output instanceof ConsoleSectionOutput && $this->output->isDecorated()) { + // remember the lines on screen, so that appendRow() can rewrite only the ones that change + $lines = $this->renderLines(); + $this->output->write(implode('', $lines), false, OutputInterface::OUTPUT_RAW); + $this->renderedLines = $lines; + + return; + } + $divider = new TableSeparator(); $isCellWithColspan = static fn ($cell) => $cell instanceof TableCell && $cell->getColspan() >= 2; @@ -323,13 +359,13 @@ public function render(): void $rows = []; if ($horizontal) { foreach ($this->headers[0] ?? [] as $i => $header) { - $rows[$i] = [$header]; + $rows[$i] = [$this->closeStyles($header)]; foreach ($this->rows as $row) { if ($row instanceof TableSeparator) { continue; } if (isset($row[$i])) { - $rows[$i][] = $row[$i]; + $rows[$i][] = $this->closeStyles($row[$i]); } elseif ($isCellWithColspan($rows[$i][0])) { // Noop, there is a "title" } else { @@ -339,7 +375,8 @@ public function render(): void } } elseif ($vertical) { $formatter = $this->output->getFormatter(); - $maxHeaderLength = array_reduce($this->headers[0] ?? [], static fn ($max, $header) => max($max, Helper::width(Helper::removeDecoration($formatter, $header))), 0); + $headers = array_map($this->closeStyles(...), $this->headers[0] ?? []); + $maxHeaderLength = array_reduce($headers, static fn ($max, $header) => max($max, Helper::width(Helper::removeDecoration($formatter, $header))), 0); foreach ($this->rows as $row) { if ($row instanceof TableSeparator) { @@ -357,20 +394,19 @@ public function render(): void } } - $headers = $this->headers[0] ?? []; $maxRows = max(\count($headers), \count($row)); for ($i = 0; $i < $maxRows; ++$i) { - $cell = (string) ($row[$i] ?? ''); + $cell = (string) $this->closeStyles($row[$i] ?? ''); $eol = str_contains($cell, "\r\n") ? "\r\n" : "\n"; - $parts = explode($eol, $cell); + $parts = explode($eol, $this->closeStyles($cell, $eol)); foreach ($parts as $idx => $part) { if ($headers && !$containsColspan) { if (0 === $idx) { $rows[] = [\sprintf( '%s%s: %s', str_repeat(' ', $maxHeaderLength - Helper::width(Helper::removeDecoration($formatter, $headers[$i] ?? ''))), - $headers[$i] ?? '', + OutputFormatter::escapeTrailingBackslash($headers[$i] ?? ''), $part )]; } else { @@ -387,7 +423,8 @@ public function render(): void } } } else { - $rows = array_merge($this->headers, [$divider], $this->rows); + $closeStyles = $this->closeStyles(...); + $rows = array_map(static fn ($row) => $row instanceof TableSeparator ? $row : array_map($closeStyles, $row), array_merge($this->headers, [$divider], $this->rows)); } $this->calculateNumberOfColumns($rows); @@ -395,9 +432,13 @@ public function render(): void $rowGroups = $this->buildTableRows($rows); $this->calculateColumnsWidth($rowGroups); + $isMarkdown = self::$styles['markdown'] === $this->style; + // a markdown table must start with a header row, so one is added when the table has none + $needsMarkdownHeader = $isMarkdown && ($horizontal || $vertical || !array_filter($this->headers)); $isHeader = !$horizontal; $isFirstRow = $horizontal; - $hasTitle = (bool) $this->headerTitle; + // a title would break the delimiter row of a markdown table + $hasTitle = (bool) $this->headerTitle && !$isMarkdown; $previousRow = null; $pendingSeparators = 0; @@ -407,7 +448,8 @@ public function render(): void foreach ($rowGroup as $row) { if ($divider === $row) { $isHeader = false; - $isFirstRow = true; + // the delimiter row of a markdown table is written after its first header row + $isFirstRow = !$isMarkdown; continue; } @@ -423,6 +465,13 @@ public function render(): void continue; } + if ($needsMarkdownHeader) { + $this->renderRow(array_fill(0, $this->numberOfColumns, ''), $this->style->getCellHeaderFormat()); + $this->renderRowSeparator(self::SEPARATOR_TOP_BOTTOM); + $needsMarkdownHeader = false; + $isFirstRow = false; + } + for (; $pendingSeparators > 0; --$pendingSeparators) { $this->renderRowSeparator(self::SEPARATOR_MID, null, null, $previousRow, $row); } @@ -462,6 +511,12 @@ public function render(): void $this->renderRow($row, $isHeader ? $this->style->getCellHeaderFormat() : $this->style->getCellRowFormat()); } + if ($isMarkdown && $isHeader) { + // a markdown table has a single header row, so the next header rows are rendered as body rows + $this->renderRowSeparator(self::SEPARATOR_TOP_BOTTOM); + $isHeader = false; + } + $previousRow = $row; } } @@ -475,7 +530,6 @@ public function render(): void } $this->cleanup(); - $this->rendered = true; } /** @@ -604,40 +658,31 @@ private function renderCell(array $row, int $column, string $cellFormat): string } // str_pad won't work properly with multi-byte strings, we need to fix the padding - $width += \strlen($cell) - Helper::width($cell) - substr_count($cell, "\0"); + $width += \strlen($cell) - Helper::width(Helper::removeDecoration($this->output->getFormatter(), $cell)); $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); + // the lines of a cell that spans rows get the style of the cell, even when a tag wraps them + $isNotStyledByTag = isset($this->rowspanLines[$cell]) || !preg_match('/^<(\w+|(\w+=[\w,]+;?)*)>.+<\/(\w+|(\w+=\w+;?)*)?>$/', $cell); if ($isNotStyledByTag) { $cellFormat = $cell->getStyle()->getCellFormat(); if (!\is_string($cellFormat)) { $tag = http_build_query($cell->getStyle()->getTagOptions(), '', ';'); $cellFormat = '<'.$tag.'>%s'; } - - if (str_contains($content, '')) { - $content = str_replace('', '', $content); - $width -= 3; - } - if (str_contains($content, '')) { - $content = str_replace('', '', $content); - $width -= \strlen(''); - } } $padType = $cell->getStyle()->getPadByAlign(); } - return \sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $padType)); + return \sprintf($cellFormat, OutputFormatter::escapeTrailingBackslash(str_pad($content, $width, $style->getPaddingChar(), $padType))); } /** @@ -661,18 +706,21 @@ private function buildTableRows(array $rows): TableRows { /** @var WrappableOutputFormatterInterface $formatter */ $formatter = $this->output->getFormatter(); + $isMarkdown = self::$styles['markdown'] === $this->style; $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 + $firstColumn = $colspan = 0; foreach ($rows[$rowKey] as $column => $cell) { + $firstColumn += $colspan; $colspan = $cell instanceof TableCell ? $cell->getColspan() : 1; $minWrappedWidth = 0; $widthApplied = []; $lengthColumnBorder = $this->getColumnSeparatorWidth() + Helper::width($this->style->getCellRowContentFormat()) - 2; - for ($i = $column; $i < ($column + $colspan); ++$i) { + for ($i = $firstColumn; $i < ($firstColumn + $colspan); ++$i) { if (isset($this->columnMaxWidths[$i])) { $minWrappedWidth += $this->columnMaxWidths[$i]; $widthApplied[] = ['type' => 'max', 'column' => $i]; @@ -690,8 +738,9 @@ private function buildTableRows(array $rows): TableRows } $cellWidth = Helper::width(Helper::removeDecoration($formatter, $cell)); - if ($minWrappedWidth && $cellWidth > $minWrappedWidth) { - $cell = $formatter->formatAndWrap($cell, $minWrappedWidth); + if ($wrapped = $minWrappedWidth && $cellWidth > $minWrappedWidth) { + // the wrapped cell is already formatted and gets formatted again when rendered + $cell = str_replace(['<', '>'], ['\\<', '\\>'], $formatter->formatAndWrap($cell, $minWrappedWidth)); } // update minimal columnWidths for spanned columns if ($colspan > 1 && $minWrappedWidth > 0) { @@ -709,7 +758,7 @@ private function buildTableRows(array $rows): TableRows $cellWidth -= $this->configuredColumnWidths[$item['column']] + $lengthColumnBorder; } } - for ($i = $column; $i < ($column + $colspan); ++$i) { + for ($i = $firstColumn; $i < ($firstColumn + $colspan); ++$i) { if (isset($columnsMinWidthProcessed[$i])) { continue; } @@ -717,13 +766,19 @@ private function buildTableRows(array $rows): TableRows $this->columnWidths[$i] = max($this->configuredColumnWidths[$i] ?? 0, $cellWidth + $lengthColumnBorder); } } - if (!str_contains($cell ?? '', "\n")) { + if ($isMarkdown && !$cell instanceof TableSeparator) { + // double the backslashes before a
so that markdown does not escape it, and add one that the output formatter removes + $escaped = preg_replace(['/\\\\++(?=[\r\n])/', '/\r\n?|\n/'], ['$0$0\\\\', '
'], str_replace('|', '\|', $cell ?? '')); + $rows[$rowKey][$column] = $cell instanceof TableCell || $colspan > 1 ? new TableCell($escaped, ['colspan' => $colspan, 'style' => $cell instanceof TableCell ? $cell->getStyle() : null]) : $escaped; + continue; } - $eol = str_contains($cell ?? '', "\r\n") ? "\r\n" : "\n"; - $escaped = implode($eol, array_map(OutputFormatter::escapeTrailingBackslash(...), explode($eol, $cell))); + if (!$wrapped && !str_contains($cell ?? '', "\n")) { + continue; + } + $escaped = implode("\n", array_map(OutputFormatter::escapeTrailingBackslash(...), preg_split('/\r?\n/', $wrapped ? $cell : $this->closeStyles(str_replace("\r\n", "\n", $cell), "\n")))); $cell = $cell instanceof TableCell ? new TableCell($escaped, ['colspan' => $cell->getColspan()]) : $escaped; - $lines = explode($eol, str_replace($eol, ''.$eol, $cell)); + $lines = explode("\n", str_replace("\n", ''."\n", $cell)); foreach ($lines as $lineKey => $line) { if ($colspan > 1) { $line = new TableCell($line, ['colspan' => $colspan]); @@ -754,21 +809,6 @@ private function buildTableRows(array $rows): TableRows }); } - private function calculateRowCount(): int - { - $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows)))); - - if ($this->headers) { - ++$numberOfRows; // Add row for header separator - } - - if ($this->rows) { - ++$numberOfRows; // Add row for footer separator - } - - return $numberOfRows; - } - /** * fill rows that contains rowspan > 1. * @@ -776,48 +816,46 @@ private function calculateRowCount(): int */ private function fillNextRows(array $rows, int $line): array { + $this->rowspanLines ??= new \WeakMap(); $unmergedRows = []; - foreach ($rows[$line] as $column => $cell) { + $column = 0; + foreach ($rows[$line] as $cellKey => $cell) { if (null !== $cell && !$cell instanceof TableCell && !\is_scalar($cell) && !$cell instanceof \Stringable) { throw new InvalidArgumentException(\sprintf('A cell must be a TableCell, a scalar or an object implementing "__toString()", "%s" given.', get_debug_type($cell))); } if ($cell instanceof TableCell && $cell->getRowspan() > 1) { $nbLines = $cell->getRowspan() - 1; - $lines = [$cell]; + $value = ''; if (str_contains($cell, "\n")) { $eol = str_contains($cell, "\r\n") ? "\r\n" : "\n"; - $lines = explode($eol, str_replace($eol, ''.$eol.'', $cell)); + $lines = explode($eol, $this->closeStyles($cell, $eol)); $nbLines = \count($lines) > $nbLines ? substr_count($cell, $eol) : $nbLines; - $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]); + $rows[$line][$cellKey] = new TableCell($lines[0], ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]); + $this->rowspanLines[$rows[$line][$cellKey]] = true; unset($lines[0]); + $value = implode($eol, $lines); } - // 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; - } - } + // only fill the next row, the rows below are filled from that row after its own cells that span rows + $unmergedRows[$line + 1][$column] = new TableCell($value, ['rowspan' => $nbLines, 'colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]); + $this->rowspanLines[$unmergedRows[$line + 1][$column]] = true; } + + $column += $cell instanceof TableCell ? $cell->getColspan() : 1; } 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($unmergedRow) <= $this->numberOfColumns)) { - foreach ($unmergedRow as $cellKey => $cell) { - // insert cell into row at cellKey position - array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]); + foreach ($unmergedRow as $column => $cell) { + // insert cell into row at column position + array_splice($rows[$unmergedRowKey], $this->getCellPosition($rows[$unmergedRowKey], $column), 0, [$cell]); } } else { $row = $this->copyRow($rows, $unmergedRowKey - 1); foreach ($unmergedRow as $column => $cell) { - if ($cell) { - $row[$column] = $cell; - } + array_splice($row, $this->getCellPosition($row, $column), 1, [$cell]); } array_splice($rows, $unmergedRowKey, 0, [$row]); } @@ -836,6 +874,10 @@ private function fillCells(iterable $row): iterable foreach ($row as $column => $cell) { $newRow[] = $cell; if ($cell instanceof TableCell && $cell->getColspan() > 1) { + if (self::$styles['markdown'] === $this->style) { + // markdown has no colspan and needs one cell per column, so the cell only fills the first column it spans + $newRow[array_key_last($newRow)] = new TableCell((string) $cell, ['style' => $cell->getStyle()]); + } foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) { // insert empty value at column position $newRow[] = ''; @@ -859,6 +901,77 @@ private function copyRow(array $rows, int $line): array return $row; } + /** + * Closes the styles that a cell leaves open at its end. + * + * With $eol, closes the styles that span a line break at the end of each line, and reopens them on the next line. + */ + private function closeStyles(mixed $cell, ?string $eol = null): mixed + { + if (!\is_string($cell) && !$cell instanceof \Stringable || !str_contains($value = (string) $cell, '<') || null !== $eol && !str_contains($value, $eol) || !($formatter = $this->output->getFormatter()) instanceof OutputFormatter) { + return $cell; + } + + $lines = null === $eol ? [$value] : explode($eol, $value); + // the tags that are open at the start of each line, then at the end of the last one, with the codes of their style and their closing tag + $openTags = [[]]; + foreach ($lines as $i => $line) { + $tags = $openTags[$i]; + preg_match_all('#<(?:[a-z](?:[^\\\\<>]*+|\\\\.)*|/(?:[a-z][^<>]*+)?)>#i', $line, $matches, \PREG_OFFSET_CAPTURE); + + foreach ($matches[0] as [$tag, $offset]) { + if ($offset && '\\' === $line[$offset - 1]) { + continue; + } + + if ('' !== $tag) { + // the formatter pushes the style of a style tag, and prints any other tag as is + $name = ltrim(substr($tag, 1), '/'); + $this->tagStyles[$name] ??= '' === $formatter->format('<'.$name) ? $formatter->getStyleStack()->pop()->apply('') : false; + if (false === $style = $this->tagStyles[$name]) { + continue; + } + + if ('/' !== $tag[1]) { + // a closing tag cannot contain an escaped "<" or ">" + $tags[] = [$tag, $style, strpbrk(substr($tag, 1, -1), '<>') ? '' : '' === $tag) { + array_pop($tags); + } else { + // like the formatter, close the last tag that has the same style, and the ones opened after it + for ($j = \count($tags) - 1; $j >= 0; --$j) { + if ($style === $tags[$j][1]) { + array_splice($tags, $j); + break; + } + } + } + } + + $openTags[] = $tags; + } + + if (!array_filter(\array_slice($openTags, 1, null === $eol ? null : -1))) { + return $cell; + } + + foreach ($lines as $i => $line) { + // closing tags go before the trailing backslashes of the line, which would escape them otherwise + $text = rtrim($line, '\\'); + $line = $text.implode('', array_reverse(array_column($openTags[$i + 1], 2))).substr($line, \strlen($text)); + $lines[$i] = implode('', array_column($openTags[$i], 0)).$line; + } + $value = implode($eol ?? '', $lines); + + return $cell instanceof TableCell ? new TableCell($value, ['rowspan' => $cell->getRowspan(), 'colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]) : $value; + } + /** * Gets number of columns by row. */ @@ -872,6 +985,23 @@ private function getNumberOfColumns(array $row): int return $columns; } + /** + * Gets the position in the given row of the cell that starts at the given column. + */ + private function getCellPosition(array $row, int $column): int + { + $position = 0; + foreach ($row as $cell) { + if ($column <= 0) { + break; + } + $column -= $cell instanceof TableCell ? $cell->getColspan() : 1; + ++$position; + } + + return $position; + } + /** * Gets list of columns for the given row. */ @@ -908,7 +1038,7 @@ private function calculateColumnsWidth(iterable $groups): void if ($textLength > 0) { $contentColumns = mb_str_split($textContent, ceil($textLength / $cell->getColspan())); foreach ($contentColumns as $position => $content) { - $row[$i + $position] = $content; + $row[$i + $position] = OutputFormatter::escape($content); } } } @@ -939,7 +1069,7 @@ private function getCellWidth(array $row, int $column): int $columnWidth = $this->columnWidths[$column] ?? 0; $cellWidth = max($cellWidth, $columnWidth); - return isset($this->columnMaxWidths[$column]) ? min($this->columnMaxWidths[$column], $cellWidth) : $cellWidth; + return isset($this->columnMaxWidths[$column]) && self::$styles['markdown'] !== $this->style ? min($this->columnMaxWidths[$column], $cellWidth) : $cellWidth; } /** @@ -948,6 +1078,8 @@ private function getCellWidth(array $row, int $column): int private function cleanup(): void { $this->effectiveColumnWidths = []; + $this->tagStyles = []; + $this->rowspanLines = null; unset($this->numberOfColumns); } @@ -1016,4 +1148,22 @@ private function resolveStyle(TableStyle|string $name): TableStyle return self::$styles[$name] ?? throw new InvalidArgumentException(\sprintf('Style "%s" is not defined.', $name)); } + + /** + * @return string[] + */ + private function renderLines(): array + { + $output = $this->output; + $buffer = new BufferedOutput($output->getVerbosity(), true, $output->getFormatter()); + $this->output = $buffer; + + try { + $this->render(); + } finally { + $this->output = $output; + } + + return preg_split('/(?<=\n)/', $buffer->fetch(), -1, \PREG_SPLIT_NO_EMPTY) ?: []; + } } diff --git a/symfony/console/Helper/TerminalInputHelper.php b/symfony/console/Helper/TerminalInputHelper.php index d0bc120ae..fe6d695ee 100644 --- a/symfony/console/Helper/TerminalInputHelper.php +++ b/symfony/console/Helper/TerminalInputHelper.php @@ -102,7 +102,8 @@ public function finish(): void // and shell_exec() gives no way to detect that failure. Try the exact restore first so // any custom terminal settings survive, but always fall back to "stty sane" so the // terminal is left in a usable state even when the exact restore silently fails. - shell_exec('stty '.$this->initialState.' 2>/dev/null || stty sane'); + $nullDevice = '\\' === \DIRECTORY_SEPARATOR ? 'NUL' : '/dev/null'; + shell_exec('stty '.$this->initialState.' 2>'.$nullDevice.' || stty sane'); $this->signalToKill = 0; foreach ($this->signalHandlers as $signal => $originalHandler) { diff --git a/symfony/console/Input/ArgvInput.php b/symfony/console/Input/ArgvInput.php index 74f3fca21..b919667b0 100644 --- a/symfony/console/Input/ArgvInput.php +++ b/symfony/console/Input/ArgvInput.php @@ -270,6 +270,13 @@ private function addLongOption(string $name, mixed $value): void } public function getFirstArgument(): ?string + { + $position = $this->getFirstArgumentPosition(); + + return null === $position ? null : $this->tokens[$position]; + } + + private function getFirstArgumentPosition(): ?int { $isOption = false; foreach ($this->tokens as $i => $token) { @@ -295,7 +302,7 @@ public function getFirstArgument(): ?string continue; } - return $token; + return $i; } return null; @@ -364,20 +371,9 @@ public function getRawTokens(bool $strip = false): array return $this->tokens; } - $parameters = []; - $keep = false; - foreach ($this->tokens as $value) { - if (!$keep && $value === $this->getFirstArgument()) { - $keep = true; - - continue; - } - if ($keep) { - $parameters[] = $value; - } - } + $position = $this->getFirstArgumentPosition(); - return $parameters; + return null === $position ? [] : \array_slice($this->tokens, $position + 1); } /** diff --git a/symfony/console/Input/StringInput.php b/symfony/console/Input/StringInput.php index a70f048f9..1392bef2d 100644 --- a/symfony/console/Input/StringInput.php +++ b/symfony/console/Input/StringInput.php @@ -63,7 +63,7 @@ private function tokenize(string $input): array $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))); + $token .= $match[1].$match[2].stripcslashes(preg_replace('/'.self::REGEX_QUOTED_STRING.'/', '$1$2', $match[3])); } 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)) { diff --git a/symfony/console/Logger/ConsoleLogger.php b/symfony/console/Logger/ConsoleLogger.php index a6ef49ea9..d5f6881f2 100644 --- a/symfony/console/Logger/ConsoleLogger.php +++ b/symfony/console/Logger/ConsoleLogger.php @@ -14,6 +14,7 @@ use Psr\Log\AbstractLogger; use Psr\Log\InvalidArgumentException; use Psr\Log\LogLevel; +use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -79,7 +80,7 @@ public function log($level, $message, array $context = []): void // the if condition check isn't necessary -- it's the same one that $output will do internally anyway. // We only do it for efficiency here as the message formatting is relatively expensive. if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) { - $output->writeln(\sprintf('<%1$s>[%2$s] %3$s', $this->formatLevelMap[$level], $level, $this->interpolate($message, $context)), $this->verbosityLevelMap[$level]); + $output->writeln(\sprintf('<%1$s>[%2$s] %3$s', $this->formatLevelMap[$level], $level, OutputFormatter::escapeTrailingBackslash($this->interpolate($message, $context))), $this->verbosityLevelMap[$level]); } } diff --git a/symfony/console/Output/ConsoleSectionOutput.php b/symfony/console/Output/ConsoleSectionOutput.php index a45d177a1..b86ca7f42 100644 --- a/symfony/console/Output/ConsoleSectionOutput.php +++ b/symfony/console/Output/ConsoleSectionOutput.php @@ -52,7 +52,8 @@ public function setMaxHeight(int $maxHeight): void $this->maxHeight = $maxHeight; $existingContent = $this->popStreamContentUntilCurrentSection($previousMaxHeight ? min($previousMaxHeight, $this->lines) : $this->lines); - parent::doWrite($this->getVisibleContent(), false); + $visibleContent = $this->getVisibleContent(); + parent::doWrite($visibleContent, '' !== $visibleContent && !str_ends_with($visibleContent, \PHP_EOL)); parent::doWrite($existingContent, false); } @@ -68,17 +69,31 @@ public function clear(?int $lines = null): void } if ($lines) { - array_splice($this->content, -$lines); + $width = $this->terminal->getWidth(); + foreach (array_splice($this->content, -$lines) as $line) { + $lines += $this->getDisplayHeight($line, $width) - 1; + } } else { $lines = $this->lines; $this->content = []; } + $previousLines = $this->lines; + // callers may ask to clear more lines than this section tracks (e.g. ProgressBar // counts "\n"-separated lines while addContent() splits on PHP_EOL), so keep the // counter from going negative, which would break the max-height bookkeeping $this->lines = max(0, $this->lines - $lines); + if ($this->maxHeight && $previousLines > $this->maxHeight) { + // the section was scrolled: redraw it to show the lines that are visible again + $erasedContent = $this->popStreamContentUntilCurrentSection($this->maxHeight); + parent::doWrite($this->getVisibleContent(), false); + parent::doWrite($erasedContent, false); + + return; + } + parent::doWrite($this->popStreamContentUntilCurrentSection($this->maxHeight ? min($this->maxHeight, $lines) : $lines), false); } @@ -157,7 +172,7 @@ public function addContent(string $input, bool $newline = true): int && !str_ends_with($lastLine, \PHP_EOL) ) { // deduct the line count of the previous line - $this->lines -= (int) ceil($this->getDisplayLength($lastLine) / $width) ?: 1; + $this->lines -= $this->getDisplayHeight($lastLine, $width); // concatenate previous and new line $lineContent = $lastLine.$lineContent; // replace last entry of `$this->content` with the new expanded line @@ -167,7 +182,7 @@ public function addContent(string $input, bool $newline = true): int $this->content[] = $lineContent; } - $linesAdded += (int) ceil($this->getDisplayLength($lineContent) / $width) ?: 1; + $linesAdded += $this->getDisplayHeight($lineContent, $width); } $this->lines += $linesAdded; @@ -198,25 +213,30 @@ protected function doWrite(string $message, bool $newline): void return; } + if ('' === $message && !$newline) { + return; + } + // Check if the previous line (last entry of `$this->content`) needs to be continued // (i.e. does not end with a line break). In which case, it needs to be erased first. - $linesToClear = $deleteLastLine = ($lastLine = end($this->content) ?: '') && !str_ends_with($lastLine, \PHP_EOL) ? 1 : 0; + $deleteLastLine = ($lastLine = end($this->content) ?: '') && !str_ends_with($lastLine, \PHP_EOL); + $linesToClear = $deleteLastLine ? $this->getDisplayHeight($lastLine, $this->terminal->getWidth()) : 0; + $previousLines = $this->lines; + + $this->addContent($message, $newline); - $linesAdded = $this->addContent($message, $newline); + if ($this->maxHeight > 0 && $this->lines > $this->maxHeight) { + // on overflow, clear the lines displayed so far and redraw the section (to remove the first lines) + $erasedContent = $this->popStreamContentUntilCurrentSection(min($this->maxHeight, $previousLines)); + $visibleContent = $this->getVisibleContent(); + parent::doWrite($visibleContent, !str_ends_with($visibleContent, \PHP_EOL)); + parent::doWrite($erasedContent, false); - if ($lineOverflow = $this->maxHeight > 0 && $this->lines > $this->maxHeight) { - // on overflow, clear the whole section and redraw again (to remove the first lines) - $linesToClear = $this->maxHeight; + return; } $erasedContent = $this->popStreamContentUntilCurrentSection($linesToClear); - if ($lineOverflow) { - // redraw existing lines of the section - $previousLinesOfSection = \array_slice($this->content, $this->lines - $this->maxHeight, $this->maxHeight - $linesAdded); - parent::doWrite(implode('', $previousLinesOfSection), false); - } - // if the last line was removed, re-print its content together with the new content. // otherwise, just print the new content. parent::doWrite($deleteLastLine ? $lastLine.$message : $message, true); @@ -256,8 +276,45 @@ private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFr return implode('', array_reverse($erasedContent)); } - private function getDisplayLength(string $text): int + private function getDisplayHeight(string $line, int $width): int { - return Helper::width(Helper::removeDecoration($this->getFormatter(), str_replace("\t", ' ', $text))); + if ($width <= 0) { + return 1; + } + + // the line break must not count as a column, or a line as wide as the terminal would count as two + if (str_ends_with($line, \PHP_EOL)) { + $line = substr($line, 0, -\strlen(\PHP_EOL)); + } + + // formatting the line again would remove literal tags, so only the ANSI sequences are removed + $line = preg_replace(['/\e\[[^m]*m/', '/\e]8;[^;]*;[^\e]*\e\\\\/'], '', $line); + $lineWidth = Helper::width(str_replace("\t", ' ', $line)); + + if ($lineWidth <= $width || !preg_match('/[\t\x80-\xFF]/', $line) || !preg_match('//u', $line)) { + return (int) ceil($lineWidth / $width) ?: 1; + } + + // a wide character that does not fit at the end of a row is moved to the next one + $rows = 1; + $column = 0; + $offset = 0; + $widths = []; + while (false !== $char = grapheme_extract($line, 1, \GRAPHEME_EXTR_COUNT, $offset, $offset)) { + if ("\t" === $char) { + // a tab moves the cursor to the next multiple of 8 columns, but never past the last column + $column = min($column - $column % 8 + 8, $width - 1); + continue; + } + + $charWidth = $widths[$char] ??= Helper::width($char); + if ($column + $charWidth > $width) { + ++$rows; + $column = 0; + } + $column += $charWidth; + } + + return $rows; } } diff --git a/symfony/console/Style/SymfonyStyle.php b/symfony/console/Style/SymfonyStyle.php index a6b67242d..efde0685f 100644 --- a/symfony/console/Style/SymfonyStyle.php +++ b/symfony/console/Style/SymfonyStyle.php @@ -474,7 +474,7 @@ private function createBlock(iterable $messages, ?string $type = null, ?string $ $line .= str_repeat(' ', max($this->lineLength - Helper::width(Helper::removeDecoration($this->getFormatter(), $line)), 0)); if ($style) { - $line = \sprintf('<%s>%s', $style, $line); + $line = \sprintf('<%s>%s', $style, OutputFormatter::escapeTrailingBackslash($line)); } } diff --git a/symfony/http-foundation/BinaryFileResponse.php b/symfony/http-foundation/BinaryFileResponse.php index 6f2b88452..e51cd3d5b 100644 --- a/symfony/http-foundation/BinaryFileResponse.php +++ b/symfony/http-foundation/BinaryFileResponse.php @@ -165,7 +165,7 @@ public function setContentDisposition(string $disposition, string $filename = '' $filename = $this->file->getFilename(); } - if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) { + if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/D', $filename) || str_contains($filename, '%'))) { $encoding = mb_detect_encoding($filename, null, true) ?: '8bit'; for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) { @@ -187,7 +187,7 @@ public function setContentDisposition(string $disposition, string $filename = '' public function prepare(Request $request): static { - if ($this->isInformational() || $this->isEmpty()) { + if (!$this->isSuccessful() || $this->isEmpty()) { parent::prepare($request); $this->maxlen = 0; @@ -260,13 +260,15 @@ public function prepare(Request $request): static 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]; + if (preg_match('/^bytes=(\d*)-(\d*)$/i', $range, $matches) && ('' !== $matches[1] || '' !== $matches[2])) { + $start = $matches[1]; + $end = $matches[2]; $end = ('' === $end) ? $fileSize - 1 : (int) $end; if ('' === $start) { - $start = $fileSize - $end; + // a suffix longer than the file selects the whole file, see RFC 9110 section 14.1.2 + $start = max(0, $fileSize - $end); $end = $fileSize - 1; } else { $start = (int) $start; diff --git a/symfony/http-foundation/Cookie.php b/symfony/http-foundation/Cookie.php index 10127176b..bf847d2c9 100644 --- a/symfony/http-foundation/Cookie.php +++ b/symfony/http-foundation/Cookie.php @@ -51,17 +51,62 @@ public static function fromString(string $cookie, bool $decode = false): static 'partitioned' => false, ]; - $parts = HeaderUtils::split($cookie, ';='); - $part = array_shift($parts); + [$pair, $attributes] = explode(';', $cookie, 2) + ['', '']; + $part = explode('=', $pair, 2); - $name = $decode ? urldecode($part[0]) : $part[0]; - $value = isset($part[1]) ? ($decode ? urldecode($part[1]) : $part[1]) : null; + $name = trim($part[0]); + $value = isset($part[1]) ? trim($part[1]) : null; + $name = $decode ? urldecode($name) : $name; + $value = $decode && null !== $value ? urldecode($value) : $value; - $data = HeaderUtils::combine($parts) + $data; - $data['expires'] = self::expiresTimestamp($data['expires']); + foreach (explode(';', $attributes) as $attribute) { + $attribute = explode('=', $attribute, 2); + $attributeName = strtolower(trim($attribute[0])); + $attributeValue = trim($attribute[1] ?? ''); - if (isset($data['max-age']) && ($data['max-age'] > 0 || $data['expires'] > time())) { - $data['expires'] = time() + (int) $data['max-age']; + if ('raw' === $attributeName || !\array_key_exists($attributeName, $data) && 'max-age' !== $attributeName) { + continue; + } + + if (\in_array($attributeName, ['secure', 'httponly', 'partitioned'], true)) { + $attributeValue = true; + } elseif ('expires' === $attributeName) { + // double quotes are delimiters in cookie dates, see RFC 6265, section 5.1.1 + $attributeValue = str_replace('"', '', $attributeValue); + + if (is_numeric($attributeValue)) { + $attributeValue = self::expiresTimestamp($attributeValue); + } elseif (false === $attributeValue = strtotime($attributeValue)) { + continue; + } else { + $attributeValue = max(1, $attributeValue); + } + } elseif ('max-age' === $attributeName) { + if (!preg_match('/^-?\d+$/D', $attributeValue)) { + continue; + } + } elseif ('samesite' === $attributeName) { + $attributeValue = strtolower($attributeValue); + + if (!\in_array($attributeValue, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE], true)) { + continue; + } + } + + $data[$attributeName] = $attributeValue; + } + + if (isset($data['max-age'])) { + $maxAge = (int) $data['max-age']; + $now = time(); + + if ($maxAge > 0) { + $data['expires'] = $now + min($maxAge, \PHP_INT_MAX - $now); + } elseif ($data['expires'] > $now) { + $data['expires'] = $now; + } elseif (0 === $data['expires']) { + $data['expires'] = 1; + } } return new static($name, $value, $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite'], $data['partitioned']); @@ -107,7 +152,7 @@ public function __construct( throw new \InvalidArgumentException(\sprintf('The cookie name "%s" contains invalid characters.', $name)); } - if (!$name) { + if ('' === $name) { throw new \InvalidArgumentException('The cookie name cannot be empty.'); } diff --git a/symfony/http-foundation/HeaderUtils.php b/symfony/http-foundation/HeaderUtils.php index 290102e6d..b039ac10d 100644 --- a/symfony/http-foundation/HeaderUtils.php +++ b/symfony/http-foundation/HeaderUtils.php @@ -176,7 +176,7 @@ public static function makeDisposition(string $disposition, string $filename, st } // filenameFallback is not ASCII. - if (!preg_match('/^[\x20-\x7e]*$/', $filenameFallback)) { + if (!preg_match('/^[\x20-\x7e]*$/D', $filenameFallback)) { throw new \InvalidArgumentException('The filename fallback must only contain ASCII characters.'); } diff --git a/symfony/http-foundation/InputBag.php b/symfony/http-foundation/InputBag.php index 8c153dc30..2dae23251 100644 --- a/symfony/http-foundation/InputBag.php +++ b/symfony/http-foundation/InputBag.php @@ -141,12 +141,56 @@ public function filter(string $key, mixed $default = null, int $filter = \FILTER $nullOnFailure = $options['flags'] & \FILTER_NULL_ON_FAILURE; $options['flags'] |= \FILTER_NULL_ON_FAILURE; - $value = filter_var($value, $filter, $options); + $invalid = false; + $forceArray = !\is_array($value) && ($options['flags'] & \FILTER_FORCE_ARRAY) && !($options['flags'] & \FILTER_REQUIRE_ARRAY); + + if (!$nullOnFailure && \is_array($value) && $value && !($options['flags'] & \FILTER_REQUIRE_SCALAR) && ($options['flags'] & (\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY))) { + $options['flags'] &= ~(\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY); + $value = self::filterArray($value, $filter, $options, $invalid); + } else { + if ($forceArray) { + $options['flags'] &= ~\FILTER_FORCE_ARRAY; + } + + $value = filter_var($value, $filter, $options); + $invalid = null === $value; + + if ($forceArray) { + $value = [$value]; + } + } - if (null !== $value || $nullOnFailure) { + if (!$invalid || $nullOnFailure) { return $value; } throw new BadRequestException(\sprintf('Input value "%s" is invalid and flag "FILTER_NULL_ON_FAILURE" was not set.', $key)); } + + private static function filterArray(array $value, int $filter, array $options, bool &$invalid, array &$references = []): array + { + foreach ($value as $key => $item) { + if (!\is_array($item)) { + $value[$key] = filter_var($item, $filter, $options); + $invalid = $invalid || null === $value[$key]; + continue; + } + + $id = \ReflectionReference::fromArrayElement($value, $key)?->getId(); + if (null !== $id && isset($references[$id])) { + continue; + } + if (null !== $id) { + $references[$id] = true; + } + + $value[$key] = self::filterArray($item, $filter, $options, $invalid, $references); + + if (null !== $id) { + unset($references[$id]); + } + } + + return $value; + } } diff --git a/symfony/http-foundation/IpUtils.php b/symfony/http-foundation/IpUtils.php index 00d5233fb..ff56dfd7c 100644 --- a/symfony/http-foundation/IpUtils.php +++ b/symfony/http-foundation/IpUtils.php @@ -18,6 +18,13 @@ */ class IpUtils { + /** + * Ranges that a server must not connect to: the private networks, plus the documentation, benchmarking + * and other special-purpose ranges listed below. This is a deny list for outgoing requests, so it also + * covers the IPv6 prefixes that embed an IPv4 address (IPv4-mapped, IPv4-compatible, 6to4, Teredo, + * NAT64). A remote client can present such an address as its own, so this list must not serve as an + * allow list of trusted proxies: use PRIVATE_RANGES for that. + */ public const PRIVATE_SUBNETS = [ '127.0.0.0/8', // RFC1700 (Loopback) '10.0.0.0/8', // RFC1918 @@ -45,6 +52,25 @@ class IpUtils '64:ff9b:1::/48', // NAT64 local-use prefix (RFC 8215) ]; + /** + * Ranges reserved for private networks, which a reverse proxy in front of the application can live in. + * + * Unlike PRIVATE_SUBNETS, this list holds no prefix that a remote client can present as its own address, + * so it can serve as an allow list, as Request::setTrustedProxies() does for "private_ranges". + * An IPv4-mapped IPv6 address is matched as the IPv4 host it embeds. + */ + public const PRIVATE_RANGES = [ + '127.0.0.0/8', // RFC1700 (Loopback) + '10.0.0.0/8', // RFC1918 + '172.16.0.0/12', // RFC1918 + '192.168.0.0/16', // RFC1918 + '169.254.0.0/16', // RFC3927 + '100.64.0.0/10', // RFC6598 + '::1/128', // Loopback + 'fc00::/7', // Unique Local Address + 'fe80::/10', // Link Local Address + ]; + private static array $checkedIps = []; /** @@ -66,11 +92,21 @@ public static function checkIp(string $requestIp, string|array $ips): bool } $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4'; + $embeddedIp4 = null; + + // An IPv4-mapped IPv6 address is the address of an IPv4 host, so it is also checked against IPv4 subnets as that host + if ('checkIp6' === $method && filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) && false !== ($packed = @inet_pton($requestIp)) && 16 === \strlen($packed) && "\0\0\0\0\0\0\0\0\0\0\xFF\xFF" === substr($packed, 0, 12)) { + $embeddedIp4 = inet_ntop(substr($packed, 12)); + } foreach ($ips as $ip) { if (self::$method($requestIp, $ip)) { return true; } + + if (null !== $embeddedIp4 && !str_contains($ip, ':') && self::checkIp4($embeddedIp4, $ip)) { + return true; + } } return false; diff --git a/symfony/http-foundation/ParameterBag.php b/symfony/http-foundation/ParameterBag.php index 5e36cf2f9..1998806fb 100644 --- a/symfony/http-foundation/ParameterBag.php +++ b/symfony/http-foundation/ParameterBag.php @@ -242,9 +242,26 @@ public function filter(string $key, mixed $default = null, int $filter = \FILTER $nullOnFailure = $options['flags'] & \FILTER_NULL_ON_FAILURE; $options['flags'] |= \FILTER_NULL_ON_FAILURE; - $value = filter_var($value, $filter, $options); + $invalid = false; + $forceArray = !\is_array($value) && ($options['flags'] & \FILTER_FORCE_ARRAY) && !($options['flags'] & \FILTER_REQUIRE_ARRAY); + + if (!$nullOnFailure && \is_array($value) && $value && !($options['flags'] & \FILTER_REQUIRE_SCALAR) && ($options['flags'] & (\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY))) { + $options['flags'] &= ~(\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY); + $value = self::filterArray($value, $filter, $options, $invalid); + } else { + if ($forceArray) { + $options['flags'] &= ~\FILTER_FORCE_ARRAY; + } + + $value = filter_var($value, $filter, $options); + $invalid = null === $value; + + if ($forceArray) { + $value = [$value]; + } + } - if (null !== $value || $nullOnFailure) { + if (!$invalid || $nullOnFailure) { return $value; } @@ -268,4 +285,31 @@ public function count(): int { return \count($this->parameters); } + + private static function filterArray(array $value, int $filter, array $options, bool &$invalid, array &$references = []): array + { + foreach ($value as $key => $item) { + if (!\is_array($item)) { + $value[$key] = filter_var($item, $filter, $options); + $invalid = $invalid || null === $value[$key]; + continue; + } + + $id = \ReflectionReference::fromArrayElement($value, $key)?->getId(); + if (null !== $id && isset($references[$id])) { + continue; + } + if (null !== $id) { + $references[$id] = true; + } + + $value[$key] = self::filterArray($item, $filter, $options, $invalid, $references); + + if (null !== $id) { + unset($references[$id]); + } + } + + return $value; + } } diff --git a/symfony/http-foundation/Request.php b/symfony/http-foundation/Request.php index fba1cf33e..e501d8791 100644 --- a/symfony/http-foundation/Request.php +++ b/symfony/http-foundation/Request.php @@ -611,7 +611,7 @@ public function overrideGlobals(): void * * 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'] and 'PRIVATE_SUBNETS' by IpUtils::PRIVATE_SUBNETS + * @param array $proxies A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR'], and 'private_ranges' or 'PRIVATE_SUBNETS' by IpUtils::PRIVATE_RANGES * @param int-mask-of $trustedHeaderSet A bit field to set which headers to trust from your proxies */ public static function setTrustedProxies(array $proxies, int $trustedHeaderSet): void @@ -627,7 +627,7 @@ public static function setTrustedProxies(array $proxies, int $trustedHeaderSet): if (false !== ($i = array_search('PRIVATE_SUBNETS', $proxies, true)) || false !== ($i = array_search('private_ranges', $proxies, true))) { unset($proxies[$i]); - $proxies = array_merge($proxies, IpUtils::PRIVATE_SUBNETS); + $proxies = array_merge($proxies, IpUtils::PRIVATE_RANGES); } self::$trustedProxies = $proxies; @@ -1714,7 +1714,7 @@ public function getPreferredLanguage(?array $locales = null): ?string $combinations = array_merge(...array_map($this->getLanguageCombinations(...), $preferredLanguages)); foreach ($combinations as $combination) { foreach ($locales as $locale) { - if (str_starts_with($locale, $combination)) { + if ($locale === $combination || str_starts_with($locale, $combination.'_')) { return $locale; } } @@ -1973,8 +1973,13 @@ protected function prepareBaseUrl(): string $requestUri = '/'.$requestUri; } - if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { - // full $baseUrl matches + if (str_starts_with($requestUri, '//') || str_starts_with($requestUri, '/\\')) { + // the URI starts with a host that the client chose: URLs built on it would point there + return ''; + } + + if ($baseUrl && (null !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) && \in_array($requestUri[\strlen($prefix)] ?? '', ['', '/', '?'], true)) { + // full $baseUrl matches, and is not only the start of a longer path segment return $prefix; } @@ -1988,17 +1993,19 @@ protected function prepareBaseUrl(): string $truncatedRequestUri = substr($requestUri, 0, $pos); } - $basename = basename($baseUrl ?? ''); - if (!$basename || !strpos(rawurldecode($truncatedRequestUri), $basename)) { - // no match whatsoever; set it blank + // With mod_rewrite or ISAPI_Rewrite, the script filename can come after + // a prefix in the path: the base URL then ends with the script filename + $decodedRequestUri = rawurldecode($truncatedRequestUri); + if (!$baseUrl || !$pos = ($this->isIisRewrite() ? stripos($decodedRequestUri, $baseUrl) : strpos($decodedRequestUri, $baseUrl))) { + // the script filename isn't in the path, or only at its start, which is handled above 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)); + $baseUrl = $this->getUrlencodedPrefix($truncatedRequestUri, substr($decodedRequestUri, 0, $pos + \strlen($baseUrl))) ?? ''; + + if (!\in_array($requestUri[\strlen($baseUrl)] ?? '', ['', '/', '?'], true)) { + // the script filename is only the start of a longer path segment + return ''; } return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR); @@ -2114,13 +2121,12 @@ private function getUrlencodedPrefix(string $string, string $prefix): ?string return null; } + // Each byte of the prefix takes 1 or 3 characters in the string. + // A {n} quantifier would make PCRE fail to compile for a long prefix. $len = \strlen($prefix); + preg_match_all('#%[[:xdigit:]]{2}|.#s', substr($string, 0, 3 * $len), $match); - if (preg_match(\sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) { - return $match[0]; - } - - return null; + return implode('', \array_slice($match[0], 0, $len)); } private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): static diff --git a/symfony/http-foundation/RequestMatcher/MethodRequestMatcher.php b/symfony/http-foundation/RequestMatcher/MethodRequestMatcher.php index b37f6e3c8..2c09c3abc 100644 --- a/symfony/http-foundation/RequestMatcher/MethodRequestMatcher.php +++ b/symfony/http-foundation/RequestMatcher/MethodRequestMatcher.php @@ -33,6 +33,11 @@ class MethodRequestMatcher implements RequestMatcherInterface public function __construct(array|string $methods) { $this->methods = array_reduce(array_map('strtoupper', (array) $methods), static fn (array $methods, string $method) => array_merge($methods, preg_split('/\s*,\s*/', $method)), []); + + // HEAD requests are served by the GET handler, as the router does + if (\in_array('GET', $this->methods, true) && !\in_array('HEAD', $this->methods, true)) { + $this->methods[] = 'HEAD'; + } } public function matches(Request $request): bool diff --git a/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php b/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php index bfdc55ba6..a14086406 100644 --- a/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php +++ b/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php @@ -27,6 +27,7 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess private string|false $prefetchData; private ?\Throwable $prefetchError = null; private ?string $newSessionId = null; + private ?string $readSessionId = null; private string $igbinaryEmptyData; public function __serialize(): array @@ -80,6 +81,8 @@ public function validateId(#[\SensitiveParameter] string $sessionId): bool public function read(#[\SensitiveParameter] string $sessionId): string|false { + $this->readSessionId = $sessionId; + if (isset($this->prefetchId)) { $prefetchId = $this->prefetchId; $prefetchData = $this->prefetchData; @@ -127,7 +130,8 @@ public function write(#[\SensitiveParameter] string $sessionId, string $data): b public function destroy(#[\SensitiveParameter] string $sessionId): bool { - if (!headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL)) { + // only the handler that read the session manages its cookie, e.g. not the write-only handler of MigratingSessionHandler + if ($this->readSessionId === $sessionId && !headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL)) { if (!isset($this->sessionName)) { throw new \LogicException(\sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', static::class)); } diff --git a/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php b/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php index 848225001..1d4ae1ed4 100644 --- a/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php +++ b/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php @@ -78,6 +78,11 @@ public function read(#[\SensitiveParameter] string $sessionId): string|false public function write(#[\SensitiveParameter] string $sessionId, string $data): bool { + // empty data must reach the inner handler unchanged so that it destroys the session + if ('' === $data || (\function_exists('igbinary_serialize') && igbinary_serialize([]) === $data)) { + return $this->handler->write($sessionId, $data); + } + $failed = []; $marshalledData = $this->marshaller->marshall(['data' => $data], $failed); diff --git a/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php b/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php index 4f1254f1b..597b0c99a 100644 --- a/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php @@ -70,6 +70,11 @@ protected function doRead(#[\SensitiveParameter] string $sessionId): string|fals public function updateTimestamp(#[\SensitiveParameter] string $sessionId, string $data): bool { + // PHP 8.6 calls updateTimestamp() instead of write() for a session that is still empty + if ('' === $data || (\function_exists('igbinary_serialize') && igbinary_serialize([]) === $data)) { + return $this->destroy($sessionId); + } + $this->memcached->touch($this->prefix.$sessionId, $this->getCompatibleTtl()); return true; diff --git a/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php b/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php index d5586030f..df1620dd1 100644 --- a/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php @@ -140,6 +140,11 @@ protected function doWrite(#[\SensitiveParameter] string $sessionId, string $dat public function updateTimestamp(#[\SensitiveParameter] string $sessionId, string $data): bool { + // PHP 8.6 calls updateTimestamp() instead of write() for a session that is still empty + if ('' === $data || (\function_exists('igbinary_serialize') && igbinary_serialize([]) === $data)) { + return $this->destroy($sessionId); + } + $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'); $expiry = $this->getUTCDateTime($ttl); diff --git a/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php b/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php index a77185e2e..cde3b9c7c 100644 --- a/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php +++ b/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php @@ -33,11 +33,6 @@ protected function doRead(#[\SensitiveParameter] string $sessionId): string return ''; } - public function updateTimestamp(#[\SensitiveParameter] string $sessionId, string $data): bool - { - return true; - } - protected function doWrite(#[\SensitiveParameter] string $sessionId, string $data): bool { return true; diff --git a/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php b/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php index 281925eaa..5e5a6946d 100644 --- a/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php +++ b/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php @@ -449,6 +449,11 @@ protected function doWrite(#[\SensitiveParameter] string $sessionId, string $dat public function updateTimestamp(#[\SensitiveParameter] string $sessionId, string $data): bool { + // PHP 8.6 calls updateTimestamp() instead of write() for a session that is still empty + if ('' === $data || (\function_exists('igbinary_serialize') && igbinary_serialize([]) === $data)) { + return $this->destroy($sessionId); + } + $expiry = time() + (int) (($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime')); try { diff --git a/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php b/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php index 5bbd236df..665b51071 100644 --- a/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php +++ b/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php @@ -98,6 +98,11 @@ public function gc(int $maxlifetime): int|false public function updateTimestamp(#[\SensitiveParameter] string $sessionId, string $data): bool { + // PHP 8.6 calls updateTimestamp() instead of write() for a session that is still empty + if ('' === $data || (\function_exists('igbinary_serialize') && igbinary_serialize([]) === $data)) { + return $this->destroy($sessionId); + } + $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'); return $this->redis->expire($this->prefix.$sessionId, (int) $ttl); diff --git a/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php b/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php index 25b1eb5ea..8f41abcfb 100644 --- a/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php +++ b/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php @@ -23,7 +23,7 @@ */ class SessionHandlerFactory { - public static function createHandler(object|string $connection, array $options = []): AbstractSessionHandler + public static function createHandler(#[\SensitiveParameter] object|string $connection, #[\SensitiveParameter] array $options = []): AbstractSessionHandler { if ($query = \is_string($connection) ? parse_url($connection) : false) { parse_str($query['query'] ?? '', $query); @@ -93,6 +93,6 @@ public static function createHandler(object|string $connection, array $options = return new PdoSessionHandler($connection, $options); } - throw new \InvalidArgumentException(\sprintf('Unsupported Connection: "%s".', $connection)); + throw new \InvalidArgumentException('No session handler supports the given DSN.'); } } diff --git a/symfony/http-foundation/Session/Storage/NativeSessionStorage.php b/symfony/http-foundation/Session/Storage/NativeSessionStorage.php index 5c0851347..ffb90a97d 100644 --- a/symfony/http-foundation/Session/Storage/NativeSessionStorage.php +++ b/symfony/http-foundation/Session/Storage/NativeSessionStorage.php @@ -37,6 +37,8 @@ class NativeSessionStorage implements SessionStorageInterface protected AbstractProxy|\SessionHandlerInterface $saveHandler; protected MetadataBag $metadataBag; + private static bool $shutdownRegistered = false; + /** * Depending on how you want the storage driver to behave you probably * want to override this constructor entirely. @@ -87,7 +89,10 @@ public function __construct(array $options = [], AbstractProxy|\SessionHandlerIn 'use_strict_mode' => 1, ]; - session_register_shutdown(); + if (!self::$shutdownRegistered) { + session_register_shutdown(); + self::$shutdownRegistered = true; + } $this->setMetadataBag($metaBag); $this->setOptions($options); diff --git a/symfony/http-foundation/UrlHelper.php b/symfony/http-foundation/UrlHelper.php index 22fb9a1a1..c442fad2b 100644 --- a/symfony/http-foundation/UrlHelper.php +++ b/symfony/http-foundation/UrlHelper.php @@ -37,10 +37,20 @@ public function getAbsoluteUrl(string $path): string return $this->getAbsoluteUrlFromContext($path); } - if ('#' === $path[0]) { - $path = $request->getRequestUri().$path; - } elseif ('?' === $path[0]) { - $path = $request->getPathInfo().$path; + if ('' === $path || '#' === $path[0] || '?' === $path[0]) { + [$requestPath, $queryString] = explode('?', $request->getRequestUri(), 2) + [1 => null]; + $pathInfo = $request->getPathInfo(); + + // the path info of "/index.php" is "/", but the URL has no slash after the base URL + if (!str_ends_with($requestPath, $pathInfo)) { + $pathInfo = substr($pathInfo, 1); + } + + if (null !== $queryString && !str_starts_with($path, '?')) { + $path = '?'.$queryString.$path; + } + + $path = $request->getBaseUrl().$pathInfo.$path; } if (!$path || '/' !== $path[0]) { @@ -92,7 +102,9 @@ private function getAbsoluteUrlFromContext(string $path): string $port = ':'.$context->getHttpsPort(); } - if ('#' === $path[0]) { + $isCurrentPathReference = '' === $path || str_starts_with($path, '#') || str_starts_with($path, '?'); + + if ('' === $path || '#' === $path[0]) { $queryString = $context->getQueryString(); $path = $context->getPathInfo().($queryString ? '?'.$queryString : '').$path; } elseif ('?' === $path[0]) { @@ -101,6 +113,8 @@ private function getAbsoluteUrlFromContext(string $path): string if ('/' !== $path[0]) { $path = rtrim($context->getBaseUrl(), '/').'/'.$path; + } elseif ($isCurrentPathReference) { + $path = $context->getBaseUrl().$path; } return $scheme.'://'.$host.$port.$path; diff --git a/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php b/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php index fcdc1d160..a66eb0692 100644 --- a/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php +++ b/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php @@ -85,7 +85,7 @@ public function getCompiledRoutes(bool $forDump = false): array [$staticRoutes, $dynamicRoutes] = $this->groupStaticRoutes($routes); - $conditions = [null]; + $conditions = ['' => null]; $compiledRoutes[] = $this->compileStaticRoutes($staticRoutes, $conditions); $chunkLimit = \count($dynamicRoutes); @@ -107,7 +107,7 @@ public function getCompiledRoutes(bool $forDump = false): array if ($forDump) { $compiledRoutes[2] = $compiledRoutes[4]; } - unset($conditions[0]); + unset($conditions['']); if ($conditions) { foreach ($conditions as $expression => $condition) { @@ -318,6 +318,17 @@ private function compileDynamicRoutes(RouteCollection $collection, bool $matchHo $state->vars = []; $hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.'; $state->hostVars = $state->vars; + + if ($state->hostVars) { + // Group 1 captures the path so that host variables cannot match any part of it. + // Group 1 is mapped to the first host variable, then the group of that variable overwrites it. + // The first lookahead skips the capture when the host cannot match. + // It is left out when requirements contain named groups, because a regexp can't define the same name twice. + $hostCheck = preg_replace('#\?P<[^>]++>#', '?:', $rx[1]); + $hostCheck = preg_match('#\(\?(?:<[^=!]|\')#', $hostCheck) ? '' : '(?=(?i:'.$hostCheck.')\.)'; + $hostRegex = $hostCheck.'(?=[^/]*+(.*+))'.$hostRegex.'(?=\1)'; + array_unshift($state->hostVars, $state->hostVars[0]); + } } else { $hostRegex = '(?:(?:[^./]*+\.)++)'; $state->hostVars = []; @@ -430,7 +441,7 @@ private function compileRoute(Route $route, string $name, string|array|null $var unset($defaults['_canonical_route']); } - if ($condition = $route->getCondition()) { + if ('' !== $condition = $route->getCondition()) { $condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request', 'params']); $condition = $conditions[$condition] ??= (str_contains($condition, '$request') ? 1 : -1) * \count($conditions); } else { diff --git a/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php b/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php index 5177c269a..2105473b7 100644 --- a/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php +++ b/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php @@ -34,8 +34,8 @@ trait CompiledUrlMatcherTrait public function match(string $pathinfo): array { - $allow = $allowSchemes = []; - if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) { + $allow = $allowSchemes = $trailingSlashSchemes = []; + if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes, $trailingSlashSchemes)) { return $ret; } if ($allow) { @@ -58,11 +58,17 @@ public function match(string $pathinfo): array $this->context->setScheme($scheme); } } elseif ('' !== $trimmedPathinfo = rtrim($pathinfo, '/')) { + $fallbackSchemes = $trailingSlashSchemes; + $fallbackPathinfo = $pathinfo; $pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo; - if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) { + if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes, $trailingSlashSchemes)) { return $this->redirect($pathinfo, $ret['_route']) + $ret; } - if ($allowSchemes) { + if ($allowSchemes = $allowSchemes ?: $trailingSlashSchemes) { + goto redirect_scheme; + } + if ($allowSchemes = $fallbackSchemes) { + $pathinfo = $fallbackPathinfo; goto redirect_scheme; } } @@ -70,9 +76,9 @@ public function match(string $pathinfo): array throw new ResourceNotFoundException(\sprintf('No routes found for "%s".', $pathinfo)); } - private function doMatch(string $pathinfo, array &$allow = [], array &$allowSchemes = []): array + private function doMatch(string $pathinfo, array &$allow = [], array &$allowSchemes = [], array &$trailingSlashSchemes = []): array { - $allow = $allowSchemes = []; + $allow = $allowSchemes = $trailingSlashSchemes = []; $pathinfo = '' === ($pathinfo = rawurldecode($pathinfo)) ? '/' : $pathinfo; $trimmedPathinfo = '' === ($trimmedPathinfo = rtrim($pathinfo, '/')) ? '/' : $trimmedPathinfo; $context = $this->context; @@ -104,6 +110,8 @@ private function doMatch(string $pathinfo, array &$allow = [], array &$allowSche if ('/' !== $pathinfo && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) { + $trailingSlashSchemes = $allowSchemes; + return $allow = $allowSchemes = []; } continue; @@ -154,6 +162,8 @@ private function doMatch(string $pathinfo, array &$allow = [], array &$allowSche if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) { + $trailingSlashSchemes = $allowSchemes; + return $allow = $allowSchemes = []; } continue; diff --git a/symfony/routing/Matcher/RedirectableUrlMatcher.php b/symfony/routing/Matcher/RedirectableUrlMatcher.php index 3e7b78b5e..47478d68f 100644 --- a/symfony/routing/Matcher/RedirectableUrlMatcher.php +++ b/symfony/routing/Matcher/RedirectableUrlMatcher.php @@ -44,6 +44,8 @@ public function match(string $pathinfo): array } elseif ('' === $trimmedPathinfo = rtrim($pathinfo, '/')) { throw $e; } else { + $fallbackSchemes = $this->trailingSlashSchemes; + $fallbackPathinfo = $pathinfo; try { $pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo; $ret = parent::match($pathinfo); @@ -53,6 +55,13 @@ public function match(string $pathinfo): array if ($this->allowSchemes) { goto redirect_scheme; } + if ($this->allowSchemes = $this->trailingSlashSchemes) { + goto redirect_scheme; + } + if ($this->allowSchemes = $fallbackSchemes) { + $pathinfo = $fallbackPathinfo; + goto redirect_scheme; + } throw $e; } } diff --git a/symfony/routing/Matcher/TraceableUrlMatcher.php b/symfony/routing/Matcher/TraceableUrlMatcher.php index 8ff018309..c104e6456 100644 --- a/symfony/routing/Matcher/TraceableUrlMatcher.php +++ b/symfony/routing/Matcher/TraceableUrlMatcher.php @@ -59,7 +59,7 @@ public function getTracesForRequest(Request $request) protected function matchCollection(string $pathinfo, RouteCollection $routes): array { // HEAD and GET are equivalent as per RFC - if ('HEAD' === $method = $this->context->getMethod()) { + if ('HEAD' === $method = $requestMethod = $this->context->getMethod()) { $method = 'GET'; } $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface; @@ -133,6 +133,7 @@ protected function matchCollection(string $pathinfo, RouteCollection $routes): a if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) { $this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route); + $this->trailingSlashSchemes = $this->allowSchemes; return $this->allow = $this->allowSchemes = []; } @@ -146,7 +147,7 @@ protected function matchCollection(string $pathinfo, RouteCollection $routes): a continue; } - if ($requiredMethods && !\in_array($method, $requiredMethods)) { + if ($requiredMethods && !\in_array($method, $requiredMethods) && !\in_array($requestMethod, $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; diff --git a/symfony/routing/Matcher/UrlMatcher.php b/symfony/routing/Matcher/UrlMatcher.php index 374eb3a0f..47f68ca78 100644 --- a/symfony/routing/Matcher/UrlMatcher.php +++ b/symfony/routing/Matcher/UrlMatcher.php @@ -47,6 +47,13 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface */ protected array $allowSchemes = []; + /** + * Collects URI schemes that would be allowed for the request before a trailing slash redirection took precedence. + * + * @internal + */ + protected array $trailingSlashSchemes = []; + protected $routes; protected $request; protected $expressionLanguage; @@ -77,7 +84,7 @@ public function getContext(): RequestContext public function match(string $pathinfo): array { - $this->allow = $this->allowSchemes = []; + $this->allow = $this->allowSchemes = $this->trailingSlashSchemes = []; $pathinfo = '' === ($pathinfo = rawurldecode($pathinfo)) ? '/' : $pathinfo; if ($ret = $this->matchCollection($pathinfo, $this->routes)) { @@ -125,7 +132,7 @@ public function addExpressionLanguageProvider(ExpressionFunctionProviderInterfac protected function matchCollection(string $pathinfo, RouteCollection $routes): array { // HEAD and GET are equivalent as per RFC - if ('HEAD' === $method = $this->context->getMethod()) { + if ('HEAD' === $method = $requestMethod = $this->context->getMethod()) { $method = 'GET'; } $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface; @@ -175,6 +182,8 @@ protected function matchCollection(string $pathinfo, RouteCollection $routes): a if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) { + $this->trailingSlashSchemes = $this->allowSchemes; + return $this->allow = $this->allowSchemes = []; } continue; @@ -185,7 +194,7 @@ protected function matchCollection(string $pathinfo, RouteCollection $routes): a continue; } - if ($requiredMethods && !\in_array($method, $requiredMethods)) { + if ($requiredMethods && !\in_array($method, $requiredMethods) && !\in_array($requestMethod, $requiredMethods)) { $this->allow = array_merge($this->allow, $requiredMethods); continue; } @@ -234,7 +243,7 @@ protected function handleRouteRequirements(string $pathinfo, string $name, Route } // expression condition - if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), [ + if ('' !== $route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), [ 'context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo), 'params' => $routeParameters, diff --git a/symfony/service-contracts/ResetInterface.php b/symfony/service-contracts/ResetInterface.php index a4f389b01..b29dbfd24 100644 --- a/symfony/service-contracts/ResetInterface.php +++ b/symfony/service-contracts/ResetInterface.php @@ -18,6 +18,7 @@ * 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. + * The object must remain usable after the call. * * 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 diff --git a/symfony/service-contracts/ServiceSubscriberInterface.php b/symfony/service-contracts/ServiceSubscriberInterface.php index 3da19169b..cd1ef7c6b 100644 --- a/symfony/service-contracts/ServiceSubscriberInterface.php +++ b/symfony/service-contracts/ServiceSubscriberInterface.php @@ -14,7 +14,7 @@ use Symfony\Contracts\Service\Attribute\SubscribedService; /** - * A ServiceSubscriber exposes its dependencies via the static {@link getSubscribedServices} method. + * Lists the services that the class needs, so that a service locator creates each service only when it is requested. * * 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 diff --git a/symfony/service-contracts/ShutdownInterface.php b/symfony/service-contracts/ShutdownInterface.php new file mode 100644 index 000000000..3c38e2ebf --- /dev/null +++ b/symfony/service-contracts/ShutdownInterface.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\Contracts\Service; + +/** + * Resets an object and optionally releases its resources. + * + * When $shutdown is false, the object must remain usable, as required by ResetInterface. + * When $shutdown is true, the object won't be used again. + * Implementations can then close resources and break circular references. + */ +interface ShutdownInterface extends ResetInterface +{ + public function reset(bool $shutdown = false): void; +} diff --git a/symfony/translation-contracts/LocaleAwareInterface.php b/symfony/translation-contracts/LocaleAwareInterface.php index db40ba13e..d34097755 100644 --- a/symfony/translation-contracts/LocaleAwareInterface.php +++ b/symfony/translation-contracts/LocaleAwareInterface.php @@ -11,6 +11,9 @@ namespace Symfony\Contracts\Translation; +/** + * Gets and sets the current locale. + */ interface LocaleAwareInterface { /** diff --git a/symfony/translation-contracts/TranslatorInterface.php b/symfony/translation-contracts/TranslatorInterface.php index 7fa69878f..67f0b2800 100644 --- a/symfony/translation-contracts/TranslatorInterface.php +++ b/symfony/translation-contracts/TranslatorInterface.php @@ -12,6 +12,8 @@ namespace Symfony\Contracts\Translation; /** + * Translates messages into the current or a given locale. + * * @author Fabien Potencier */ interface TranslatorInterface diff --git a/symfony/translation/Provider/AbstractProviderFactory.php b/symfony/translation/Provider/AbstractProviderFactory.php index f0c11d85d..c6bcac3b8 100644 --- a/symfony/translation/Provider/AbstractProviderFactory.php +++ b/symfony/translation/Provider/AbstractProviderFactory.php @@ -32,6 +32,6 @@ protected function getUser(Dsn $dsn): string protected function getPassword(Dsn $dsn): string { - return $dsn->getPassword() ?? throw new IncompleteDsnException('Password is not set.', $dsn->getOriginalDsn()); + return $dsn->getPassword() ?? throw new IncompleteDsnException('Password is not set.', $dsn->getScheme().'://'.$dsn->getHost()); } }