From 96bb798bc1dce7780827dd51cecaafde94b9ae6c Mon Sep 17 00:00:00 2001 From: Javier Eguiluz Date: Tue, 4 Mar 2025 09:40:01 +0100 Subject: [PATCH] [Reference] Sort all framework options alphabetically --- reference/configuration/framework.rst | 4643 +++++++++++++------------ 1 file changed, 2322 insertions(+), 2321 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index e58a7ebc80f..0334b918c66 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -19,236 +19,355 @@ configured under the ``framework`` key in your application configuration. namespace and the related XSD schema is available at: ``https://symfony.com/schema/dic/symfony/symfony-1.0.xsd`` -.. _configuration-framework-secret: +annotations +~~~~~~~~~~~ -secret -~~~~~~ +.. _reference-annotations-cache: -**type**: ``string`` **required** +cache +..... -This is a string that should be unique to your application and it's commonly -used to add more entropy to security related operations. Its value should -be a series of characters, numbers and symbols chosen randomly and the -recommended length is around 32 characters. +**type**: ``string`` **default**: ``php_array`` -In practice, Symfony uses this value for encrypting the cookies used -in the :doc:`remember me functionality ` and for -creating signed URIs when using :ref:`ESI (Edge Side Includes) `. -That's why you should treat this value as if it were a sensitive credential and -**never make it public**. +This option can be one of the following values: -This option becomes the service container parameter named ``kernel.secret``, -which you can use whenever the application needs an immutable random string -to add more entropy. +php_array + Use a PHP array to cache annotations in memory +file + Use the filesystem to cache annotations +none + Disable the caching of annotations -As with any other security-related parameter, it is a good practice to change -this value from time to time. However, keep in mind that changing this value -will invalidate all signed URIs and Remember Me cookies. That's why, after -changing this value, you should regenerate the application cache and log -out all the application users. +debug +..... -handle_all_throwables -~~~~~~~~~~~~~~~~~~~~~ +**type**: ``boolean`` **default**: ``%kernel.debug%`` -**type**: ``boolean`` **default**: ``true`` +Whether to enable debug mode for caching. If enabled, the cache will +automatically update when the original file is changed (both with code and +annotation changes). For performance reasons, it is recommended to disable +debug mode in production, which will happen automatically if you use the +default value. -When set to ``true``, the Symfony kernel will catch all ``\Throwable`` exceptions -thrown by the application and will turn them into HTTP responses. +file_cache_dir +.............. -.. _configuration-framework-http_cache: +**type**: ``string`` **default**: ``%kernel.cache_dir%/annotations`` -http_cache -~~~~~~~~~~ +The directory to store cache files for annotations, in case +``annotations.cache`` is set to ``'file'``. -enabled -....... +assets +~~~~~~ -**type**: ``boolean`` **default**: ``false`` +.. _reference-assets-base-path: -debug -..... +base_path +......... -**type**: ``boolean`` **default**: ``%kernel.debug%`` +**type**: ``string`` -If true, exceptions are thrown when things go wrong. Otherwise, the cache will -try to carry on and deliver a meaningful response. +This option allows you to define a base path to be used for assets: -trace_level -........... +.. configuration-block:: -**type**: ``string`` **possible values**: ``'none'``, ``'short'`` or ``'full'`` + .. code-block:: yaml -For 'short', a concise trace of the main request will be added as an HTTP header. -'full' will add traces for all requests (including ESI subrequests). -(default: 'full' if in debug; 'none' otherwise) + # config/packages/framework.yaml + framework: + # ... + assets: + base_path: '/images' -trace_header -............ + .. code-block:: xml -**type**: ``string`` + + + -Header name to use for traces. (default: X-Symfony-Cache) + + + + -default_ttl -........... + .. code-block:: php -**type**: ``integer`` + // config/packages/framework.php + use Symfony\Config\FrameworkConfig; -The number of seconds that a cache entry should be considered fresh when no -explicit freshness information is provided in a response. Explicit -Cache-Control or Expires headers override this value. (default: 0) + return static function (FrameworkConfig $framework): void { + // ... + $framework->assets() + ->basePath('/images'); + }; -private_headers -............... +.. _reference-templating-base-urls: +.. _reference-assets-base-urls: + +base_urls +......... **type**: ``array`` -Set of request headers that trigger "private" cache-control behavior on responses -that don't explicitly state whether the response is public or private via a -Cache-Control directive. (default: Authorization and Cookie) +This option allows you to define base URLs to be used for assets. +If multiple base URLs are provided, Symfony will select one from the +collection each time it generates an asset's path: -skip_response_headers -..................... +.. configuration-block:: -**type**: ``array`` **default**: ``Set-Cookie`` + .. code-block:: yaml -Set of response headers that will never be cached even when the response is cacheable -and public. + # config/packages/framework.yaml + framework: + # ... + assets: + base_urls: + - 'http://cdn.example.com/' -allow_reload -............ + .. code-block:: xml -**type**: ``string`` + + + -Specifies whether the client can force a cache reload by including a -Cache-Control "no-cache" directive in the request. Set it to ``true`` -for compliance with RFC 2616. (default: false) + + + + -allow_revalidate -................ + .. code-block:: php -**type**: ``string`` + // config/packages/framework.php + use Symfony\Config\FrameworkConfig; -Specifies whether the client can force a cache revalidate by including a -Cache-Control "max-age=0" directive in the request. Set it to ``true`` -for compliance with RFC 2616. (default: false) + return static function (FrameworkConfig $framework): void { + // ... + $framework->assets() + ->baseUrls(['http://cdn.example.com/']); + }; -stale_while_revalidate -...................... +.. _reference-assets-json-manifest-path: +.. _reference-templating-json-manifest-path: -**type**: ``integer`` +json_manifest_path +.................. -Specifies the default number of seconds (the granularity is the second as the -Response TTL precision is a second) during which the cache can immediately return -a stale response while it revalidates it in the background (default: 2). -This setting is overridden by the stale-while-revalidate HTTP Cache-Control -extension (see RFC 5861). +**type**: ``string`` **default**: ``null`` -stale_if_error -.............. +The file path or absolute URL to a ``manifest.json`` file containing an +associative array of asset names and their respective compiled names. A common +cache-busting technique using a "manifest" file works by writing out assets with +a "hash" appended to their file names (e.g. ``main.ae433f1cb.css``) during a +front-end compilation routine. -**type**: ``integer`` +.. tip:: -Specifies the default number of seconds (the granularity is the second) during -which the cache can serve a stale response when an error is encountered -(default: 60). This setting is overridden by the stale-if-error HTTP -Cache-Control extension (see RFC 5861). + Symfony's :ref:`Webpack Encore ` supports + :ref:`outputting hashed assets `. Moreover, this + can be incorporated into many other workflows, including Webpack and + Gulp using `webpack-manifest-plugin`_ and `gulp-rev`_, respectively. + +This option can be set globally for all assets and individually for each asset +package: + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/framework.yaml + framework: + assets: + # this manifest is applied to every asset (including packages) + json_manifest_path: "%kernel.project_dir%/public/build/manifest.json" + # you can use absolute URLs too and Symfony will download them automatically + # json_manifest_path: 'https://cdn.example.com/manifest.json' + packages: + foo_package: + # this package uses its own manifest (the default file is ignored) + json_manifest_path: "%kernel.project_dir%/public/build/a_different_manifest.json" + # Throws an exception when an asset is not found in the manifest + strict_mode: %kernel.debug% + bar_package: + # this package uses the global manifest (the default file is used) + base_path: '/images' + + .. code-block:: xml + + + + + + + + + + + + + + + + + + + + .. code-block:: php + + // config/packages/framework.php + use Symfony\Config\FrameworkConfig; + + return static function (FrameworkConfig $framework): void { + // ... + $framework->assets() + // this manifest is applied to every asset (including packages) + ->jsonManifestPath('%kernel.project_dir%/public/build/manifest.json'); + + // you can use absolute URLs too and Symfony will download them automatically + // 'json_manifest_path' => 'https://cdn.example.com/manifest.json', + $framework->assets()->package('foo_package') + // this package uses its own manifest (the default file is ignored) + ->jsonManifestPath('%kernel.project_dir%/public/build/a_different_manifest.json') + // Throws an exception when an asset is not found in the manifest + ->setStrictMode('%kernel.debug%'); + + $framework->assets()->package('bar_package') + // this package uses the global manifest (the default file is used) + ->basePath('/images'); + }; + +.. note:: + + This parameter cannot be set at the same time as ``version`` or ``version_strategy``. + Additionally, this option cannot be nullified at the package scope if a global manifest + file is specified. + +.. tip:: + + If you request an asset that is *not found* in the ``manifest.json`` file, the original - + *unmodified* - asset path will be returned. + You can set ``strict_mode`` to ``true`` to get an exception when an asset is *not found*. - .. _configuration-framework-http_method_override: +.. note:: -http_method_override -~~~~~~~~~~~~~~~~~~~~ + If a URL is set, the JSON manifest is downloaded on each request using the `http_client`_. -**type**: ``boolean`` **default**: ``false`` +.. _reference-framework-assets-packages: -This determines whether the ``_method`` request parameter is used as the -intended HTTP method on POST requests. If enabled, the -:method:`Request::enableHttpMethodParameterOverride ` -method gets called automatically. It becomes the service container parameter -named ``kernel.http_method_override``. +packages +........ -.. seealso:: +You can group assets into packages, to specify different base URLs for them: - :ref:`Changing the Action and HTTP Method ` of - Symfony forms. +.. configuration-block:: -.. warning:: + .. code-block:: yaml - If you're using the :ref:`HttpCache Reverse Proxy ` - with this option, the kernel will ignore the ``_method`` parameter, - which could lead to errors. + # config/packages/framework.yaml + framework: + # ... + assets: + packages: + avatars: + base_urls: 'http://static_cdn.example.com/avatars' - To fix this, invoke the ``enableHttpMethodParameterOverride()`` method - before creating the ``Request`` object:: + .. code-block:: xml - // public/index.php + + + - // ... - $kernel = new CacheKernel($kernel); + + + + + + - Request::enableHttpMethodParameterOverride(); // <-- add this line - $request = Request::createFromGlobals(); - // ... + .. code-block:: php -trust_x_sendfile_type_header -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // config/packages/framework.php + use Symfony\Config\FrameworkConfig; -**type**: ``boolean`` **default**: ``%env(bool:default::SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER)%`` + return static function (FrameworkConfig $framework): void { + // ... + $framework->assets() + ->package('avatars') + ->baseUrls(['http://static_cdn.example.com/avatars']); + }; -.. versionadded:: 7.2 +Now you can use the ``avatars`` package in your templates: - In Symfony 7.2, the default value of this option was changed from ``false`` to the - value stored in the ``SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER`` environment variable. +.. code-block:: html+twig -``X-Sendfile`` is a special HTTP header that tells web servers to replace the -response contents by the file that is defined in that header. This improves -performance because files are no longer served by your application but directly -by the web server. + -This configuration option determines whether to trust ``x-sendfile`` header for -BinaryFileResponse. If enabled, Symfony calls the -:method:`BinaryFileResponse::trustXSendfileTypeHeader ` -method automatically. It becomes the service container parameter named -``kernel.trust_x_sendfile_type_header``. +Each package can configure the following options: -.. _reference-framework-trusted-headers: +* :ref:`base_path ` +* :ref:`base_urls ` +* :ref:`version_strategy ` +* :ref:`version ` +* :ref:`version_format ` +* :ref:`json_manifest_path ` +* :ref:`strict_mode ` -trusted_headers -~~~~~~~~~~~~~~~ +.. _reference-assets-strict-mode: -The ``trusted_headers`` option is needed to configure which client information -should be trusted (e.g. their host) when running Symfony behind a load balancer -or a reverse proxy. See :doc:`/deployment/proxies`. +strict_mode +........... -.. _reference-framework-trusted-proxies: +**type**: ``boolean`` **default**: ``false`` -trusted_proxies -~~~~~~~~~~~~~~~ +When enabled, the strict mode asserts that all requested assets are in the +manifest file. This option is useful to detect typos or missing assets, the +recommended value is ``%kernel.debug%``. -The ``trusted_proxies`` option is needed to get precise information about the -client (e.g. their IP address) when running Symfony behind a load balancer or a -reverse proxy. See :doc:`/deployment/proxies`. +.. _reference-framework-assets-version: +.. _ref-framework-assets-version: -ide -~~~ +version +....... -**type**: ``string`` **default**: ``%env(default::SYMFONY_IDE)%`` +**type**: ``string`` -Symfony turns file paths seen in variable dumps and exception messages into -links that open those files right inside your browser. If you prefer to open -those files in your favorite IDE or text editor, set this option to any of the -following values: ``phpstorm``, ``sublime``, ``textmate``, ``macvim``, ``emacs``, -``atom`` and ``vscode``. +This option is used to *bust* the cache on assets by globally adding a query +parameter to all rendered asset paths (e.g. ``/images/logo.png?v2``). This +applies only to assets rendered via the Twig ``asset()`` function (or PHP +equivalent). -.. note:: +For example, suppose you have the following: - The ``phpstorm`` option is supported natively by PhpStorm on macOS and - Windows; Linux requires installing `phpstorm-url-handler`_. +.. code-block:: html+twig -If you use another editor, the expected configuration value is a URL template -that contains an ``%f`` placeholder where the file path is expected and ``%l`` -placeholder for the line number (percentage signs (``%``) must be escaped by -doubling them to prevent Symfony from interpreting them as container parameters). + Symfony! + +By default, this will render a path to your image such as ``/images/logo.png``. +Now, activate the ``version`` option: .. configuration-block:: @@ -256,7 +375,9 @@ doubling them to prevent Symfony from interpreting them as container parameters) # config/packages/framework.yaml framework: - ide: 'myide://open?url=file://%%f&line=%%l' + # ... + assets: + version: 'v2' .. code-block:: xml @@ -269,7 +390,9 @@ doubling them to prevent Symfony from interpreting them as container parameters) 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"> - + + + .. code-block:: php @@ -278,203 +401,245 @@ doubling them to prevent Symfony from interpreting them as container parameters) use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->ide('myide://open?url=file://%%f&line=%%l'); + // ... + $framework->assets() + ->version('v2'); }; -Since every developer uses a different IDE, the recommended way to enable this -feature is to configure it on a system level. First, you can define this option -in the ``SYMFONY_IDE`` environment variable, which Symfony reads automatically -when ``framework.ide`` config is not set. - -Another alternative is to set the ``xdebug.file_link_format`` option in your -``php.ini`` configuration file. The format to use is the same as for the -``framework.ide`` option, but without the need to escape the percent signs -(``%``) by doubling them: - -.. code-block:: ini - - // example for PhpStorm - xdebug.file_link_format="phpstorm://open?file=%f&line=%l" - - // example for PhpStorm with Jetbrains Toolbox - xdebug.file_link_format="jetbrains://phpstorm/navigate/reference?project=example&path=%f:%l" +Now, the same asset will be rendered as ``/images/logo.png?v2`` If you use +this feature, you **must** manually increment the ``version`` value +before each deployment so that the query parameters change. - // example for Sublime Text - xdebug.file_link_format="subl://open?url=file://%f&line=%l" +You can also control how the query string works via the `version_format`_ +option. .. note:: - If both ``framework.ide`` and ``xdebug.file_link_format`` are defined, - Symfony uses the value of the ``xdebug.file_link_format`` option. - -.. tip:: - - Setting the ``xdebug.file_link_format`` ini option works even if the Xdebug - extension is not enabled. + This parameter cannot be set at the same time as ``version_strategy`` or ``json_manifest_path``. .. tip:: - When running your app in a container or in a virtual machine, you can tell - Symfony to map files from the guest to the host by changing their prefix. - This map should be specified at the end of the URL template, using ``&`` and - ``>`` as guest-to-host separators: - - .. code-block:: text - - // /path/to/guest/.../file will be opened - // as /path/to/host/.../file on the host - // and /var/www/app/ as /projects/my_project/ also - 'myide://%%f:%%l&/path/to/guest/>/path/to/host/&/var/www/app/>/projects/my_project/&...' - - // example for PhpStorm - 'phpstorm://open?file=%%f&line=%%l&/var/www/app/>/projects/my_project/' - -.. _reference-framework-test: - -test -~~~~ + As with all settings, you can use a parameter as value for the + ``version``. This makes it easier to increment the cache on each + deployment. -**type**: ``boolean`` +.. _reference-templating-version-format: +.. _reference-assets-version-format: -If this configuration setting is present (and not ``false``), then the services -related to testing your application (e.g. ``test.client``) are loaded. This -setting should be present in your ``test`` environment (usually via -``config/packages/test/framework.yaml``). +version_format +.............. -.. seealso:: +**type**: ``string`` **default**: ``%%s?%%s`` - For more information, see :doc:`/testing`. +This specifies a :phpfunction:`sprintf` pattern that will be used with the +`version`_ option to construct an asset's path. By default, the pattern +adds the asset's version as a query string. For example, if +``version_format`` is set to ``%%s?version=%%s`` and ``version`` +is set to ``5``, the asset's path would be ``/images/logo.png?version=5``. -.. _config-framework-default_locale: +.. note:: -default_locale -~~~~~~~~~~~~~~ + All percentage signs (``%``) in the format string must be doubled to + escape the character. Without escaping, values might inadvertently be + interpreted as :ref:`service-container-parameters`. -**type**: ``string`` **default**: ``en`` +.. tip:: -The default locale is used if no ``_locale`` routing parameter has been -set. It is available with the -:method:`Request::getDefaultLocale ` -method. + Some CDN's do not support cache-busting via query strings, so injecting + the version into the actual file path is necessary. Thankfully, + ``version_format`` is not limited to producing versioned query + strings. -.. seealso:: + The pattern receives the asset's original path and version as its first + and second parameters, respectively. Since the asset's path is one + parameter, you cannot modify it in-place (e.g. ``/images/logo-v5.png``); + however, you can prefix the asset's path using a pattern of + ``version-%%2$s/%%1$s``, which would result in the path + ``version-5/images/logo.png``. - You can read more information about the default locale in - :ref:`translation-default-locale`. + URL rewrite rules could then be used to disregard the version prefix + before serving the asset. Alternatively, you could copy assets to the + appropriate version path as part of your deployment process and forgot + any URL rewriting. The latter option is useful if you would like older + asset versions to remain accessible at their original URL. -.. _reference-translator-enabled-locales: -.. _reference-enabled-locales: +.. _reference-assets-version-strategy: +.. _reference-templating-version-strategy: -enabled_locales -............... +version_strategy +................ -**type**: ``array`` **default**: ``[]`` (empty array = enable all locales) +**type**: ``string`` **default**: ``null`` -Symfony applications generate by default the translation files for validation -and security messages in all locales. If your application only uses some -locales, use this option to restrict the files generated by Symfony and improve -performance a bit: +The service id of the :doc:`asset version strategy ` +applied to the assets. This option can be set globally for all assets and +individually for each asset package: .. configuration-block:: .. code-block:: yaml - # config/packages/translation.yaml + # config/packages/framework.yaml framework: - enabled_locales: ['en', 'es'] + assets: + # this strategy is applied to every asset (including packages) + version_strategy: 'app.asset.my_versioning_strategy' + packages: + foo_package: + # this package removes any versioning (its assets won't be versioned) + version: ~ + bar_package: + # this package uses its own strategy (the default strategy is ignored) + version_strategy: 'app.asset.another_version_strategy' + baz_package: + # this package inherits the default strategy + base_path: '/images' .. code-block:: xml - + - en - es + + + + + + + + .. code-block:: php - // config/packages/translation.php + // config/packages/framework.php use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->enabledLocales(['en', 'es']); + // ... + $framework->assets() + ->versionStrategy('app.asset.my_versioning_strategy'); + + $framework->assets()->package('foo_package') + // this package removes any versioning (its assets won't be versioned) + ->version(null); + + $framework->assets()->package('bar_package') + // this package uses its own strategy (the default strategy is ignored) + ->versionStrategy('app.asset.another_version_strategy'); + + $framework->assets()->package('baz_package') + // this package inherits the default strategy + ->basePath('/images'); }; -An added bonus of defining the enabled locales is that they are automatically -added as a requirement of the :ref:`special _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 a 404 error. +.. note:: -set_content_language_from_locale -................................ + This parameter cannot be set at the same time as ``version`` or ``json_manifest_path``. -**type**: ``boolean`` **default**: ``false`` +.. _reference-cache: -If this option is set to ``true``, the response will have a ``Content-Language`` -HTTP header set with the ``Request`` locale. +cache +~~~~~ -set_locale_from_accept_language -............................... +.. _reference-cache-app: -**type**: ``boolean`` **default**: ``false`` +app +... -If this option is set to ``true``, the ``Request`` locale will automatically be -set to the value of the ``Accept-Language`` HTTP header. +**type**: ``string`` **default**: ``cache.adapter.filesystem`` -When the ``_locale`` request attribute is passed, the ``Accept-Language`` header -is ignored. +The cache adapter used by the ``cache.app`` service. The FrameworkBundle +ships with multiple adapters: ``cache.adapter.apcu``, ``cache.adapter.system``, +``cache.adapter.filesystem``, ``cache.adapter.psr6``, ``cache.adapter.redis``, +``cache.adapter.memcached``, ``cache.adapter.pdo`` and +``cache.adapter.doctrine_dbal``. -disallow_search_engine_index -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +There's also a special adapter called ``cache.adapter.array`` which stores +contents in memory using a PHP array and it's used to disable caching (mostly on +the ``dev`` environment). -**type**: ``boolean`` **default**: ``true`` when the debug mode is enabled, ``false`` otherwise. +.. tip:: -If ``true``, Symfony adds a ``X-Robots-Tag: noindex`` HTTP tag to all responses -(unless your own app adds that header, in which case it's not modified). This -`X-Robots-Tag HTTP header`_ tells search engines to not index your web site. -This option is a protection measure in case you accidentally publish your site -in debug mode. + It might be tough to understand at the beginning, so to avoid confusion + remember that all pools perform the same actions but on different medium + given the adapter they are based on. Internally, a pool wraps the definition + of an adapter. -.. _configuration-framework-trusted-hosts: +default_doctrine_provider +......................... -trusted_hosts -~~~~~~~~~~~~~ +**type**: ``string`` -**type**: ``array`` | ``string`` **default**: ``['%env(default::SYMFONY_TRUSTED_HOSTS)%']`` +The service name to use as your default Doctrine provider. The provider is +available as the ``cache.default_doctrine_provider`` service. -.. versionadded:: 7.2 +default_memcached_provider +.......................... - In Symfony 7.2, the default value of this option was changed from ``[]`` to the - value stored in the ``SYMFONY_TRUSTED_HOSTS`` environment variable. +**type**: ``string`` **default**: ``memcached://localhost`` -A lot of different attacks have been discovered relying on inconsistencies -in handling the ``Host`` header by various software (web servers, reverse -proxies, web frameworks, etc.). Basically, every time the framework is -generating an absolute URL (when sending an email to reset a password for -instance), the host might have been manipulated by an attacker. +The DSN to use by the Memcached provider. The provider is available as the ``cache.default_memcached_provider`` +service. + +default_pdo_provider +.................... + +**type**: ``string`` **default**: ``doctrine.dbal.default_connection`` + +The service id of the database connection, which should be either a PDO or a +Doctrine DBAL instance. The provider is available as the ``cache.default_pdo_provider`` +service. + +default_psr6_provider +..................... + +**type**: ``string`` + +The service name to use as your default PSR-6 provider. It is available as +the ``cache.default_psr6_provider`` service. + +default_redis_provider +...................... + +**type**: ``string`` **default**: ``redis://localhost`` + +The DSN to use by the Redis provider. The provider is available as the ``cache.default_redis_provider`` +service. + +directory +......... + +**type**: ``string`` **default**: ``%kernel.cache_dir%/pools`` + +The path to the cache directory used by services inheriting from the +``cache.adapter.filesystem`` adapter (including ``cache.app``). + +pools +..... + +**type**: ``array`` + +A list of cache pools to be created by the framework extension. .. seealso:: - You can read `HTTP Host header attacks`_ for more information about - these kinds of attacks. + For more information about how pools work, see :ref:`cache pools `. -The Symfony :method:`Request::getHost() ` -method might be vulnerable to some of these attacks because it depends on -the configuration of your web server. One simple solution to avoid these -attacks is to configure a list of hosts that your Symfony application can respond -to. That's the purpose of this ``trusted_hosts`` option. If the incoming -request's hostname doesn't match one of the regular expressions in this list, -the application won't respond and the user will receive a 400 response. +To configure a Redis cache pool with a default lifetime of 1 hour, do the following: .. configuration-block:: @@ -482,7 +647,11 @@ the application won't respond and the user will receive a 400 response. # config/packages/framework.yaml framework: - trusted_hosts: ['^example\.com$', '^example\.org$'] + cache: + pools: + cache.mycache: + adapter: cache.adapter.redis + default_lifetime: 3600 .. code-block:: xml @@ -496,8 +665,13 @@ the application won't respond and the user will receive a 400 response. http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> - ^example\.com$ - ^example\.org$ + + + @@ -508,60 +682,119 @@ the application won't respond and the user will receive a 400 response. use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->trustedHosts(['^example\.com$', '^example\.org$']); + $framework->cache() + ->pool('cache.mycache') + ->adapters(['cache.adapter.redis']) + ->defaultLifetime(3600); }; -Hosts can also be configured to respond to any subdomain, via -``^(.+\.)?example\.com$`` for instance. +adapter +""""""" + +**type**: ``string`` **default**: ``cache.app`` + +The service name of the adapter to use. You can specify one of the default +services that follow the pattern ``cache.adapter.[type]``. Alternatively you +can specify another cache pool as base, which will make this pool inherit the +settings from the base pool as defaults. + +.. note:: + + Your service needs to implement the ``Psr\Cache\CacheItemPoolInterface`` interface. + +clearer +""""""" + +**type**: ``string`` + +The cache clearer used to clear your PSR-6 cache. + +.. seealso:: + + For more information, see :class:`Symfony\\Component\\HttpKernel\\CacheClearer\\Psr6CacheClearer`. + +default_lifetime +"""""""""""""""" + +**type**: ``integer`` | ``string`` + +Default lifetime of your cache items. Give an integer value to set the default +lifetime in seconds. A string value could be ISO 8601 time interval, like ``"PT5M"`` +or a PHP date expression that is accepted by ``strtotime()``, like ``"5 minutes"``. + +If no value is provided, the cache adapter will fallback to the default value on +the actual cache storage. + +.. _reference-cache-pools-name: + +name +"""" + +**type**: ``prototype`` + +Name of the pool you want to create. + +.. note:: -In addition, you can also set the trusted hosts in the front controller -using the ``Request::setTrustedHosts()`` method:: + Your pool name must differ from ``cache.app`` or ``cache.system``. - // public/index.php - Request::setTrustedHosts(['^(.+\.)?example\.com$', '^(.+\.)?example\.org$']); +provider +"""""""" -The default value for this option is an empty array, meaning that the application -can respond to any given host. +**type**: ``string`` -.. seealso:: +Overwrite the default service name or DSN respectively, if you do not want to +use what is configured as ``default_X_provider`` under ``cache``. See the +description of the default provider setting above for information on how to +specify your specific provider. - Read more about this in the `Security Advisory Blog post`_. +public +"""""" -.. _reference-framework-form: +**type**: ``boolean`` **default**: ``false`` -form -~~~~ +Whether your service should be public or not. -.. _reference-form-enabled: +tags +"""" -enabled -....... +**type**: ``boolean`` | ``string`` **default**: ``null`` -**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation +Whether your service should be able to handle tags or not. +Can also be the service id of another cache pool where tags will be stored. -Whether to enable the form services or not in the service container. If -you don't use forms, setting this to ``false`` may increase your application's -performance because less services will be loaded into the container. +.. _reference-cache-prefix-seed: -This option will automatically be set to ``true`` when one of the child -settings is configured. +prefix_seed +........... -.. note:: +**type**: ``string`` **default**: ``_%kernel.project_dir%.%kernel.container_class%`` - This will automatically enable the `validation`_. +This value is used as part of the "namespace" generated for the +cache item keys. A common practice is to use the unique name of the application +(e.g. ``symfony.com``) because that prevents naming collisions when deploying +multiple applications into the same path (on different servers) that share the +same cache backend. -.. seealso:: +It's also useful when using `blue/green deployment`_ strategies and more +generally, when you need to abstract out the actual deployment directory (for +example, when warming caches offline). - For more details, see :doc:`/forms`. +.. note:: -.. _reference-form-field-name: + The ``prefix_seed`` option is used at compile time. This means + that any change made to this value after container's compilation + will have no effect. -field_name -.......... +.. _reference-cache-system: -**type**: ``string`` **default**: ``_token`` +system +...... -This is the field name that you should give to the CSRF token field of your forms. +**type**: ``string`` **default**: ``cache.adapter.system`` + +The cache adapter used by the ``cache.system`` service. It supports the same +adapters available for the ``cache.app`` service. .. _reference-framework-csrf-protection: @@ -621,48 +854,47 @@ If you're using forms, but want to avoid starting your session (e.g. using forms in an API-only website), ``csrf_protection`` will need to be set to ``false``. -.. _config-framework-error_controller: - -error_controller -~~~~~~~~~~~~~~~~ +.. _config-framework-default_locale: -**type**: ``string`` **default**: ``error_controller`` +default_locale +~~~~~~~~~~~~~~ -This is the controller that is called when an exception is thrown anywhere in -your application. The default controller -(:class:`Symfony\\Component\\HttpKernel\\Controller\\ErrorController`) -renders specific templates under different error conditions (see -:doc:`/controller/error_pages`). +**type**: ``string`` **default**: ``en`` -esi -~~~ +The default locale is used if no ``_locale`` routing parameter has been +set. It is available with the +:method:`Request::getDefaultLocale ` +method. .. seealso:: - You can read more about Edge Side Includes (ESI) in :ref:`edge-side-includes`. - -.. _reference-esi-enabled: + You can read more information about the default locale in + :ref:`translation-default-locale`. -enabled -....... +.. _reference-translator-enabled-locales: +.. _reference-enabled-locales: -**type**: ``boolean`` **default**: ``false`` +enabled_locales +............... -Whether to enable the edge side includes support in the framework. +**type**: ``array`` **default**: ``[]`` (empty array = enable all locales) -You can also set ``esi`` to ``true`` to enable it: +Symfony applications generate by default the translation files for validation +and security messages in all locales. If your application only uses some +locales, use this option to restrict the files generated by Symfony and improve +performance a bit: .. configuration-block:: .. code-block:: yaml - # config/packages/framework.yaml + # config/packages/translation.yaml framework: - esi: true + enabled_locales: ['en', 'es'] .. code-block:: xml - + - + en + es .. code-block:: php - // config/packages/framework.php + // config/packages/translation.php use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->esi()->enabled(true); + $framework->enabledLocales(['en', 'es']); }; -fragments -~~~~~~~~~ +An added bonus of defining the enabled locales is that they are automatically +added as a requirement of the :ref:`special _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 a 404 error. -.. seealso:: +set_content_language_from_locale +................................ - Learn more about fragments in the - :ref:`HTTP Cache article `. +**type**: ``boolean`` **default**: ``false`` -.. _reference-fragments-enabled: +If this option is set to ``true``, the response will have a ``Content-Language`` +HTTP header set with the ``Request`` locale. -enabled -....... +set_locale_from_accept_language +............................... **type**: ``boolean`` **default**: ``false`` -Whether to enable the fragment listener or not. The fragment listener is -used to render ESI fragments independently of the rest of the page. +If this option is set to ``true``, the ``Request`` locale will automatically be +set to the value of the ``Accept-Language`` HTTP header. -This setting is automatically set to ``true`` when one of the child settings -is configured. +When the ``_locale`` request attribute is passed, the ``Accept-Language`` header +is ignored. -hinclude_default_template -......................... +disallow_search_engine_index +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -**type**: ``string`` **default**: ``null`` +**type**: ``boolean`` **default**: ``true`` when the debug mode is enabled, ``false`` otherwise. -Sets the content shown during the loading of the fragment or when JavaScript -is disabled. This can be either a template name or the content itself. +If ``true``, Symfony adds a ``X-Robots-Tag: noindex`` HTTP tag to all responses +(unless your own app adds that header, in which case it's not modified). This +`X-Robots-Tag HTTP header`_ tells search engines to not index your web site. +This option is a protection measure in case you accidentally publish your site +in debug mode. -.. seealso:: +.. _config-framework-error_controller: - See :ref:`templates-hinclude` for more information about hinclude. +error_controller +~~~~~~~~~~~~~~~~ -.. _reference-fragments-path: +**type**: ``string`` **default**: ``error_controller`` -path -.... +This is the controller that is called when an exception is thrown anywhere in +your application. The default controller +(:class:`Symfony\\Component\\HttpKernel\\Controller\\ErrorController`) +renders specific templates under different error conditions (see +:doc:`/controller/error_pages`). -**type**: ``string`` **default**: ``/_fragment`` +esi +~~~ -The path prefix for fragments. The fragment listener will only be executed -when the request starts with this path. +.. seealso:: -.. _reference-http-client: + You can read more about Edge Side Includes (ESI) in :ref:`edge-side-includes`. -http_client -~~~~~~~~~~~ +.. _reference-esi-enabled: -When the HttpClient component is installed, an HTTP client is available -as a service named ``http_client`` or using the autowiring alias -:class:`Symfony\\Contracts\\HttpClient\\HttpClientInterface`. +enabled +....... -.. _reference-http-client-default-options: +**type**: ``boolean`` **default**: ``false`` -This service can be configured using ``framework.http_client.default_options``: +Whether to enable the edge side includes support in the framework. + +You can also set ``esi`` to ``true`` to enable it: .. configuration-block:: @@ -747,12 +991,7 @@ This service can be configured using ``framework.http_client.default_options``: # config/packages/framework.yaml framework: - # ... - http_client: - max_host_connections: 10 - default_options: - headers: { 'X-Powered-By': 'ACME App' } - max_redirects: 7 + esi: true .. code-block:: xml @@ -766,61 +1005,43 @@ This service can be configured using ``framework.http_client.default_options``: http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> - - - ACME App - - + .. code-block:: php // config/packages/framework.php - $container->loadFromExtension('framework', [ - 'http_client' => [ - 'max_host_connections' => 10, - 'default_options' => [ - 'headers' => [ - 'X-Powered-By' => 'ACME App', - ], - 'max_redirects' => 7, - ], - ], - ]); + use Symfony\Config\FrameworkConfig; - .. code-block:: php-standalone + return static function (FrameworkConfig $framework): void { + $framework->esi()->enabled(true); + }; - $client = HttpClient::create([ - 'headers' => [ - 'X-Powered-By' => 'ACME App', - ], - 'max_redirects' => 7, - ], 10); +.. _framework_exceptions: -.. _reference-http-client-scoped-clients: +exceptions +~~~~~~~~~~ -Multiple pre-configured HTTP client services can be defined, each with its -service name defined as a key under ``scoped_clients``. Scoped clients inherit -the default options defined for the ``http_client`` service. You can override -these options and can define a few others: +**type**: ``array`` + +Defines the :ref:`log level ` and HTTP status code applied to the +exceptions that match the given exception class: .. configuration-block:: .. code-block:: yaml - # config/packages/framework.yaml - framework: - # ... - http_client: - scoped_clients: - my_api.client: - auth_bearer: secret_bearer_token - # ... + # config/packages/exceptions.yaml + framework: + exceptions: + Symfony\Component\HttpKernel\Exception\BadRequestHttpException: + log_level: 'debug' + status_code: 422 .. code-block:: xml - + - - - + + .. code-block:: php - // config/packages/framework.php - $container->loadFromExtension('framework', [ - 'http_client' => [ - 'scoped_clients' => [ - 'my_api.client' => [ - 'auth_bearer' => 'secret_bearer_token', - // ... - ], - ], - ], - ]); + // config/packages/exceptions.php + use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; + use Symfony\Config\FrameworkConfig; - .. code-block:: php-standalone + return static function (FrameworkConfig $framework): void { + $framework->exception(BadRequestHttpException::class) + ->logLevel('debug') + ->statusCode(422) + ; + }; - $client = HttpClient::createForBaseUri('https://...', [ - 'auth_bearer' => 'secret_bearer_token', - // ... - ]); +The order in which you configure exceptions is important because Symfony will +use the configuration of the first exception that matches ``instanceof``: -Options defined for scoped clients apply only to URLs that match either their -`base_uri`_ or the `scope`_ option when it is defined. Non-matching URLs always -use default options. +.. code-block:: yaml -Each scoped client also defines a corresponding named autowiring alias. -If you use for example -``Symfony\Contracts\HttpClient\HttpClientInterface $myApiClient`` -as the type and name of an argument, autowiring will inject the ``my_api.client`` -service into your autowired classes. + # config/packages/exceptions.yaml + framework: + exceptions: + Exception: + log_level: 'debug' + status_code: 404 + # The following configuration will never be used because \RuntimeException extends \Exception + RuntimeException: + log_level: 'debug' + status_code: 422 -auth_basic -.......... +You can map a status code and a set of headers to an exception thanks +to the ``#[WithHttpStatus]`` attribute on the exception class:: -**type**: ``string`` + namespace App\Exception; -The username and password used to create the ``Authorization`` HTTP header -used in HTTP Basic authentication. The value of this option must follow the -format ``username:password``. + use Symfony\Component\HttpKernel\Attribute\WithHttpStatus; -auth_bearer -........... + #[WithHttpStatus(422, [ + 'Retry-After' => 10, + 'X-Custom-Header' => 'header-value', + ])] + class CustomException extends \Exception + { + } -**type**: ``string`` +It is also possible to map a log level on a custom exception class using +the ``#[WithLogLevel]`` attribute:: -The token used to create the ``Authorization`` HTTP header used in HTTP Bearer -authentication (also called token authentication). + namespace App\Exception; -auth_ntlm -......... + use Psr\Log\LogLevel; + use Symfony\Component\HttpKernel\Attribute\WithLogLevel; -**type**: ``string`` + #[WithLogLevel(LogLevel::WARNING)] + class CustomException extends \Exception + { + } -The username and password used to create the ``Authorization`` HTTP header used -in the `Microsoft NTLM authentication protocol`_. The value of this option must -follow the format ``username:password``. This authentication mechanism requires -using the cURL-based transport. +The attributes can also be added to interfaces directly:: -.. _reference-http-client-base-uri: + namespace App\Exception; -base_uri -........ + use Symfony\Component\HttpKernel\Attribute\WithHttpStatus; -**type**: ``string`` + #[WithHttpStatus(422)] + interface CustomExceptionInterface + { + } -URI that is merged into relative URIs, following the rules explained in the -`RFC 3986`_ standard. This is useful when all the requests you make share a -common prefix (e.g. ``https://api.github.com/``) so you can avoid adding it to -every request. + class CustomException extends \Exception implements CustomExceptionInterface + { + } -Here are some common examples of how ``base_uri`` merging works in practice: +.. versionadded:: 7.1 -========================== ================== ============================= -``base_uri`` Relative URI Actual Requested URI -========================== ================== ============================= -http://example.org /bar http://example.org/bar -http://example.org/foo /bar http://example.org/bar -http://example.org/foo bar http://example.org/bar -http://example.org/foo/ /bar http://example.org/bar -http://example.org/foo/ bar http://example.org/foo/bar -http://example.org http://symfony.com http://symfony.com -http://example.org/?bar bar http://example.org/bar -http://example.org/api/v4 /bar http://example.org/bar -http://example.org/api/v4/ /bar http://example.org/bar -http://example.org/api/v4 bar http://example.org/api/bar -http://example.org/api/v4/ bar http://example.org/api/v4/bar -========================== ================== ============================= + Support to use ``#[WithHttpStatus]`` and ``#[WithLogLevel]`` attributes + on interfaces was introduced in Symfony 7.1. -bindto -...... +.. _reference-framework-form: -**type**: ``string`` +form +~~~~ -A network interface name, IP address, a host name or a UNIX socket to use as the -outgoing network interface. +.. _reference-form-enabled: -buffer -...... +enabled +....... -**type**: ``boolean`` | ``Closure`` +**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation -Buffering the response means that you can access its content multiple times -without performing the request again. Buffering is enabled by default when the -content type of the response is ``text/*``, ``application/json`` or ``application/xml``. +Whether to enable the form services or not in the service container. If +you don't use forms, setting this to ``false`` may increase your application's +performance because less services will be loaded into the container. -If this option is a boolean value, the response is buffered when the value is -``true``. If this option is a closure, the response is buffered when the -returned value is ``true`` (the closure receives as argument an array with the -response headers). +This option will automatically be set to ``true`` when one of the child +settings is configured. -cafile -...... +.. note:: -**type**: ``string`` + This will automatically enable the `validation`_. -The path of the certificate authority file that contains one or more -certificates used to verify the other servers' certificates. +.. seealso:: -capath -...... + For more details, see :doc:`/forms`. -**type**: ``string`` +.. _reference-form-field-name: -The path to a directory that contains one or more certificate authority files. +field_name +.......... -ciphers +**type**: ``string`` **default**: ``_token`` + +This is the field name that you should give to the CSRF token field of your forms. + +fragments +~~~~~~~~~ + +.. seealso:: + + Learn more about fragments in the + :ref:`HTTP Cache article `. + +.. _reference-fragments-enabled: + +enabled ....... -**type**: ``string`` +**type**: ``boolean`` **default**: ``false`` -A list of the names of the ciphers allowed for the TLS connections. They -can be separated by colons, commas or spaces (e.g. ``'RC4-SHA:TLS13-AES-128-GCM-SHA256'``). +Whether to enable the fragment listener or not. The fragment listener is +used to render ESI fragments independently of the rest of the page. -crypto_method -............. +This setting is automatically set to ``true`` when one of the child settings +is configured. -**type**: ``integer`` +hinclude_default_template +......................... -The minimum version of TLS to accept. The value must be one of the -``STREAM_CRYPTO_METHOD_TLSv*_CLIENT`` constants defined by PHP. +**type**: ``string`` **default**: ``null`` -.. _reference-http-client-retry-delay: +Sets the content shown during the loading of the fragment or when JavaScript +is disabled. This can be either a template name or the content itself. -delay -..... +.. seealso:: -**type**: ``integer`` **default**: ``1000`` + See :ref:`templates-hinclude` for more information about hinclude. -The initial delay in milliseconds used to compute the waiting time between retries. +.. _reference-fragments-path: + +path +.... + +**type**: ``string`` **default**: ``/_fragment`` + +The path prefix for fragments. The fragment listener will only be executed +when the request starts with this path. + +handle_all_throwables +~~~~~~~~~~~~~~~~~~~~~ + +**type**: ``boolean`` **default**: ``true`` + +When set to ``true``, the Symfony kernel will catch all ``\Throwable`` exceptions +thrown by the application and will turn them into HTTP responses. + +html_sanitizer +~~~~~~~~~~~~~~ + +The ``html_sanitizer`` option (and its children) are used to configure +custom HTML sanitizers. Read more about the options in the +:ref:`HTML sanitizer documentation `. + +.. _configuration-framework-http_cache: + +http_cache +~~~~~~~~~~ + +allow_reload +............ + +**type**: ``string`` -.. _reference-http-client-retry-enabled: +Specifies whether the client can force a cache reload by including a +Cache-Control "no-cache" directive in the request. Set it to ``true`` +for compliance with RFC 2616. (default: false) -enabled -....... +allow_revalidate +................ -**type**: ``boolean`` **default**: ``false`` +**type**: ``string`` -Whether to enable the support for retry failed HTTP request or not. -This setting is automatically set to true when one of the child settings is configured. +Specifies whether the client can force a cache revalidate by including a +Cache-Control "max-age=0" directive in the request. Set it to ``true`` +for compliance with RFC 2616. (default: false) -extra +debug ..... -**type**: ``array`` - -Arbitrary additional data to pass to the HTTP client for further use. -This can be particularly useful when :ref:`decorating an existing client `. +**type**: ``boolean`` **default**: ``%kernel.debug%`` -.. _http-headers: +If true, exceptions are thrown when things go wrong. Otherwise, the cache will +try to carry on and deliver a meaningful response. -headers -....... +default_ttl +........... -**type**: ``array`` +**type**: ``integer`` -An associative array of the HTTP headers added before making the request. This -value must use the format ``['header-name' => 'value0, value1, ...']``. +The number of seconds that a cache entry should be considered fresh when no +explicit freshness information is provided in a response. Explicit +Cache-Control or Expires headers override this value. (default: 0) -.. _reference-http-client-retry-http-codes: +enabled +....... -http_codes -.......... +**type**: ``boolean`` **default**: ``false`` -**type**: ``array`` **default**: :method:`Symfony\\Component\\HttpClient\\Retry\\GenericRetryStrategy::DEFAULT_RETRY_STATUS_CODES` +private_headers +............... -The list of HTTP status codes that triggers a retry of the request. +**type**: ``array`` -http_version -............ +Set of request headers that trigger "private" cache-control behavior on responses +that don't explicitly state whether the response is public or private via a +Cache-Control directive. (default: Authorization and Cookie) -**type**: ``string`` | ``null`` **default**: ``null`` +skip_response_headers +..................... -The HTTP version to use, typically ``'1.1'`` or ``'2.0'``. Leave it to ``null`` -to let Symfony select the best version automatically. +**type**: ``array`` **default**: ``Set-Cookie`` -.. _reference-http-client-retry-jitter: +Set of response headers that will never be cached even when the response is cacheable +and public. -jitter -...... +stale_if_error +.............. -**type**: ``float`` **default**: ``0.1`` (must be between 0.0 and 1.0) +**type**: ``integer`` -This option adds some randomness to the delay. It's useful to avoid sending -multiple requests to the server at the exact same time. The randomness is -calculated as ``delay * jitter``. For example: if delay is ``1000ms`` and jitter -is ``0.2``, the actual delay will be a number between ``800`` and ``1200`` (1000 +/- 20%). +Specifies the default number of seconds (the granularity is the second) during +which the cache can serve a stale response when an error is encountered +(default: 60). This setting is overridden by the stale-if-error HTTP +Cache-Control extension (see RFC 5861). -local_cert -.......... +stale_while_revalidate +...................... -**type**: ``string`` +**type**: ``integer`` -The path to a file that contains the `PEM formatted`_ certificate used by the -HTTP client. This is often combined with the ``local_pk`` and ``passphrase`` -options. +Specifies the default number of seconds (the granularity is the second as the +Response TTL precision is a second) during which the cache can immediately return +a stale response while it revalidates it in the background (default: 2). +This setting is overridden by the stale-while-revalidate HTTP Cache-Control +extension (see RFC 5861). -local_pk -........ +trace_header +............ **type**: ``string`` -The path of a file that contains the `PEM formatted`_ private key of the -certificate defined in the ``local_cert`` option. +Header name to use for traces. (default: X-Symfony-Cache) -.. _reference-http-client-retry-max-delay: +trace_level +........... -max_delay -......... +**type**: ``string`` **possible values**: ``'none'``, ``'short'`` or ``'full'`` -**type**: ``integer`` **default**: ``0`` +For 'short', a concise trace of the main request will be added as an HTTP header. +'full' will add traces for all requests (including ESI subrequests). +(default: 'full' if in debug; 'none' otherwise) -The maximum amount of milliseconds initial to wait between retries. -Use ``0`` to not limit the duration. +.. _reference-http-client: -max_duration -............ +http_client +~~~~~~~~~~~ -**type**: ``float`` **default**: ``0`` +When the HttpClient component is installed, an HTTP client is available +as a service named ``http_client`` or using the autowiring alias +:class:`Symfony\\Contracts\\HttpClient\\HttpClientInterface`. -The maximum execution time, in seconds, that the request and the response are -allowed to take. A value lower than or equal to 0 means it is unlimited. +.. _reference-http-client-default-options: -max_host_connections -.................... +This service can be configured using ``framework.http_client.default_options``: -**type**: ``integer`` **default**: ``6`` +.. configuration-block:: -Defines the maximum amount of simultaneously open connections to a single host -(considering a "host" the same as a "host name + port number" pair). This limit -also applies for proxy connections, where the proxy is considered to be the host -for which this limit is applied. + .. code-block:: yaml -max_redirects -............. + # config/packages/framework.yaml + framework: + # ... + http_client: + max_host_connections: 10 + default_options: + headers: { 'X-Powered-By': 'ACME App' } + max_redirects: 7 -**type**: ``integer`` **default**: ``20`` + .. code-block:: xml -The maximum number of redirects to follow. Use ``0`` to not follow any -redirection. + + + -.. _reference-http-client-retry-max-retries: + + + + ACME App + + + + -max_retries -........... + .. code-block:: php -**type**: ``integer`` **default**: ``3`` + // config/packages/framework.php + $container->loadFromExtension('framework', [ + 'http_client' => [ + 'max_host_connections' => 10, + 'default_options' => [ + 'headers' => [ + 'X-Powered-By' => 'ACME App', + ], + 'max_redirects' => 7, + ], + ], + ]); -The maximum number of retries for failing requests. When the maximum is reached, -the client returns the last received response. + .. code-block:: php-standalone -.. _reference-http-client-retry-multiplier: + $client = HttpClient::create([ + 'headers' => [ + 'X-Powered-By' => 'ACME App', + ], + 'max_redirects' => 7, + ], 10); -multiplier -.......... +.. _reference-http-client-scoped-clients: -**type**: ``float`` **default**: ``2`` +Multiple pre-configured HTTP client services can be defined, each with its +service name defined as a key under ``scoped_clients``. Scoped clients inherit +the default options defined for the ``http_client`` service. You can override +these options and can define a few others: -This value is multiplied to the delay each time a retry occurs, to distribute -retries in time instead of making all of them sequentially. +.. configuration-block:: -no_proxy -........ + .. code-block:: yaml -**type**: ``string`` | ``null`` **default**: ``null`` + # config/packages/framework.yaml + framework: + # ... + http_client: + scoped_clients: + my_api.client: + auth_bearer: secret_bearer_token + # ... -A comma separated list of hosts that do not require a proxy to be reached, even -if one is configured. Use the ``'*'`` wildcard to match all hosts and an empty -string to match none (disables the proxy). + .. code-block:: xml -passphrase -.......... + + + -**type**: ``string`` + + + + + + -The passphrase used to encrypt the certificate stored in the file defined in the -``local_cert`` option. + .. code-block:: php -peer_fingerprint -................ + // config/packages/framework.php + $container->loadFromExtension('framework', [ + 'http_client' => [ + 'scoped_clients' => [ + 'my_api.client' => [ + 'auth_bearer' => 'secret_bearer_token', + // ... + ], + ], + ], + ]); -**type**: ``array`` + .. code-block:: php-standalone -When negotiating a TLS connection, the server sends a certificate -indicating its identity. A public key is extracted from this certificate and if -it does not exactly match any of the public keys provided in this option, the -connection is aborted before sending or receiving any data. + $client = HttpClient::createForBaseUri('https://...', [ + 'auth_bearer' => 'secret_bearer_token', + // ... + ]); -The value of this option is an associative array of ``algorithm => hash`` -(e.g ``['pin-sha256' => '...']``). +Options defined for scoped clients apply only to URLs that match either their +`base_uri`_ or the `scope`_ option when it is defined. Non-matching URLs always +use default options. -proxy -..... +Each scoped client also defines a corresponding named autowiring alias. +If you use for example +``Symfony\Contracts\HttpClient\HttpClientInterface $myApiClient`` +as the type and name of an argument, autowiring will inject the ``my_api.client`` +service into your autowired classes. -**type**: ``string`` | ``null`` +auth_basic +.......... -The HTTP proxy to use to make the requests. Leave it to ``null`` to detect the -proxy automatically based on your system configuration. +**type**: ``string`` -query -..... +The username and password used to create the ``Authorization`` HTTP header +used in HTTP Basic authentication. The value of this option must follow the +format ``username:password``. -**type**: ``array`` +auth_bearer +........... -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, ...]``. +**type**: ``string`` -rate_limiter -............ +The token used to create the ``Authorization`` HTTP header used in HTTP Bearer +authentication (also called token authentication). -**type**: ``string`` +auth_ntlm +......... -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`. +**type**: ``string`` -.. versionadded:: 7.1 +The username and password used to create the ``Authorization`` HTTP header used +in the `Microsoft NTLM authentication protocol`_. The value of this option must +follow the format ``username:password``. This authentication mechanism requires +using the cURL-based transport. - The ``rate_limiter`` option was introduced in Symfony 7.1. +.. _reference-http-client-base-uri: -resolve -....... +base_uri +........ -**type**: ``array`` +**type**: ``string`` -A list of hostnames and their IP addresses to pre-populate the DNS cache used by -the HTTP client in order to avoid a DNS lookup for those hosts. This option is -useful to improve security when IPs are checked before the URL is passed to the -client and to make your tests easier. +URI that is merged into relative URIs, following the rules explained in the +`RFC 3986`_ standard. This is useful when all the requests you make share a +common prefix (e.g. ``https://api.github.com/``) so you can avoid adding it to +every request. -The value of this option is an associative array of ``domain => IP address`` -(e.g ``['symfony.com' => '46.137.106.254', ...]``). +Here are some common examples of how ``base_uri`` merging works in practice: -.. _reference-http-client-retry-failed: +========================== ================== ============================= +``base_uri`` Relative URI Actual Requested URI +========================== ================== ============================= +http://example.org /bar http://example.org/bar +http://example.org/foo /bar http://example.org/bar +http://example.org/foo bar http://example.org/bar +http://example.org/foo/ /bar http://example.org/bar +http://example.org/foo/ bar http://example.org/foo/bar +http://example.org http://symfony.com http://symfony.com +http://example.org/?bar bar http://example.org/bar +http://example.org/api/v4 /bar http://example.org/bar +http://example.org/api/v4/ /bar http://example.org/bar +http://example.org/api/v4 bar http://example.org/api/bar +http://example.org/api/v4/ bar http://example.org/api/v4/bar +========================== ================== ============================= -retry_failed -............ +bindto +...... -**type**: ``array`` +**type**: ``string`` -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: +A network interface name, IP address, a host name or a UNIX socket to use as the +outgoing network interface. -* :ref:`delay ` -* :ref:`http_codes ` -* :ref:`jitter ` -* :ref:`max_delay ` -* :ref:`max_retries ` -* :ref:`multiplier ` +buffer +...... -.. code-block:: yaml +**type**: ``boolean`` | ``Closure`` - # 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 +Buffering the response means that you can access its content multiple times +without performing the request again. Buffering is enabled by default when the +content type of the response is ``text/*``, ``application/json`` or ``application/xml``. - scoped_clients: - my_api.client: - # ... - retry_failed: - max_retries: 4 +If this option is a boolean value, the response is buffered when the value is +``true``. If this option is a closure, the response is buffered when the +returned value is ``true`` (the closure receives as argument an array with the +response headers). -retry_strategy -.............. +cafile +...... **type**: ``string`` -The service is used to decide if a request should be retried and to compute the -time to wait between retries. By default, it uses an instance of -:class:`Symfony\\Component\\HttpClient\\Retry\\GenericRetryStrategy` configured -with ``http_codes``, ``delay``, ``max_delay``, ``multiplier`` and ``jitter`` -options. This class has to implement -:class:`Symfony\\Component\\HttpClient\\Retry\\RetryStrategyInterface`. +The path of the certificate authority file that contains one or more +certificates used to verify the other servers' certificates. -scope -..... +capath +...... **type**: ``string`` -For scoped clients only: the regular expression that the URL must match before -applying all other non-default options. By default, the scope is derived from -`base_uri`_. +The path to a directory that contains one or more certificate authority files. -timeout +ciphers ....... -**type**: ``float`` **default**: depends on your PHP config - -Time, in seconds, to wait for network activity. If the connection is idle for longer, a -:class:`Symfony\\Component\\HttpClient\\Exception\\TransportException` is thrown. -Its default value is the same as the value of PHP's `default_socket_timeout`_ -config option. - -verify_host -........... +**type**: ``string`` -**type**: ``boolean`` **default**: ``true`` +A list of the names of the ciphers allowed for the TLS connections. They +can be separated by colons, commas or spaces (e.g. ``'RC4-SHA:TLS13-AES-128-GCM-SHA256'``). -If ``true``, the certificate sent by other servers is verified to ensure that -their common name matches the host included in the URL. This is usually -combined with ``verify_peer`` to also verify the certificate authenticity. +crypto_method +............. -verify_peer -........... +**type**: ``integer`` -**type**: ``boolean`` **default**: ``true`` +The minimum version of TLS to accept. The value must be one of the +``STREAM_CRYPTO_METHOD_TLSv*_CLIENT`` constants defined by PHP. -If ``true``, the certificate sent by other servers when negotiating a TLS -connection is verified for authenticity. Authenticating the certificate is not -enough to be sure about the server, so you should combine this with the -``verify_host`` option. +.. _reference-http-client-retry-delay: -html_sanitizer -~~~~~~~~~~~~~~ +delay +..... -The ``html_sanitizer`` option (and its children) are used to configure -custom HTML sanitizers. Read more about the options in the -:ref:`HTML sanitizer documentation `. +**type**: ``integer`` **default**: ``1000`` -profiler -~~~~~~~~ +The initial delay in milliseconds used to compute the waiting time between retries. -.. _reference-profiler-enabled: +.. _reference-http-client-retry-enabled: enabled ....... **type**: ``boolean`` **default**: ``false`` -The profiler can be enabled by setting this option to ``true``. When you -install it using Symfony Flex, the profiler is enabled in the ``dev`` -and ``test`` environments. +Whether to enable the support for retry failed HTTP request or not. +This setting is automatically set to true when one of the child settings is configured. -.. note:: +extra +..... - The profiler works independently from the Web Developer Toolbar, see - the :doc:`WebProfilerBundle configuration ` - on how to disable/enable the toolbar. +**type**: ``array`` -collect -....... +Arbitrary additional data to pass to the HTTP client for further use. +This can be particularly useful when :ref:`decorating an existing client `. -**type**: ``boolean`` **default**: ``true`` +.. _http-headers: -This option configures the way the profiler behaves when it is enabled. If set -to ``true``, the profiler collects data for all requests. If you want to only -collect information on-demand, you can set the ``collect`` flag to ``false`` and -activate the data collectors manually:: +headers +....... - $profiler->enable(); +**type**: ``array`` -collect_parameter -................. +An associative array of the HTTP headers added before making the request. This +value must use the format ``['header-name' => 'value0, value1, ...']``. -**type**: ``string`` **default**: ``null`` +.. _reference-http-client-retry-http-codes: -This specifies name of a query parameter, a body parameter or a request attribute -used to enable or disable collection of data by the profiler for each request. -Combine it with the ``collect`` option to enable/disable the profiler on demand: +http_codes +.......... -* If the ``collect`` option is set to ``true`` but this parameter exists in a - request and has any value other than ``true``, ``yes``, ``on`` or ``1``, the - request data will not be collected; -* If the ``collect`` option is set to ``false``, but this parameter exists in a - request and has value of ``true``, ``yes``, ``on`` or ``1``, the request data - will be collected. +**type**: ``array`` **default**: :method:`Symfony\\Component\\HttpClient\\Retry\\GenericRetryStrategy::DEFAULT_RETRY_STATUS_CODES` -only_exceptions -............... +The list of HTTP status codes that triggers a retry of the request. -**type**: ``boolean`` **default**: ``false`` +http_version +............ -When this is set to ``true``, the profiler will only be enabled when an -exception is thrown during the handling of the request. +**type**: ``string`` | ``null`` **default**: ``null`` -.. _only_master_requests: +The HTTP version to use, typically ``'1.1'`` or ``'2.0'``. Leave it to ``null`` +to let Symfony select the best version automatically. -only_main_requests -.................. +.. _reference-http-client-retry-jitter: + +jitter +...... -**type**: ``boolean`` **default**: ``false`` +**type**: ``float`` **default**: ``0.1`` (must be between 0.0 and 1.0) -When this is set to ``true``, the profiler will only be enabled on the main -requests (and not on the subrequests). +This option adds some randomness to the delay. It's useful to avoid sending +multiple requests to the server at the exact same time. The randomness is +calculated as ``delay * jitter``. For example: if delay is ``1000ms`` and jitter +is ``0.2``, the actual delay will be a number between ``800`` and ``1200`` (1000 +/- 20%). -.. _profiler-dsn: +local_cert +.......... -dsn -... +**type**: ``string`` -**type**: ``string`` **default**: ``file:%kernel.cache_dir%/profiler`` +The path to a file that contains the `PEM formatted`_ certificate used by the +HTTP client. This is often combined with the ``local_pk`` and ``passphrase`` +options. -The DSN where to store the profiling information. +local_pk +........ -.. _collect_serializer_data: +**type**: ``string`` -collect_serializer_data -....................... +The path of a file that contains the `PEM formatted`_ private key of the +certificate defined in the ``local_cert`` option. -**type**: ``boolean`` **default**: ``false`` +.. _reference-http-client-retry-max-delay: -Set this option to ``true`` to enable the serializer data collector and its -profiler panel. When this option is ``true``, all normalizers and encoders are -decorated by traceable implementations that collect profiling information about them. +max_delay +......... -rate_limiter -~~~~~~~~~~~~ +**type**: ``integer`` **default**: ``0`` -.. _reference-rate-limiter-name: +The maximum amount of milliseconds initial to wait between retries. +Use ``0`` to not limit the duration. -name -.... +max_duration +............ -**type**: ``prototype`` +**type**: ``float`` **default**: ``0`` -Name of the rate limiter you want to create. +The maximum execution time, in seconds, that the request and the response are +allowed to take. A value lower than or equal to 0 means it is unlimited. -lock_factory -"""""""""""" +max_host_connections +.................... -**type**: ``string`` **default:** ``lock.factory`` +**type**: ``integer`` **default**: ``6`` -The service that is used to create a lock. The service has to be an instance of -the :class:`Symfony\\Component\\Lock\\LockFactory` class. +Defines the maximum amount of simultaneously open connections to a single host +(considering a "host" the same as a "host name + port number" pair). This limit +also applies for proxy connections, where the proxy is considered to be the host +for which this limit is applied. -policy -"""""" +max_redirects +............. -**type**: ``string`` **required** +**type**: ``integer`` **default**: ``20`` -The name of the rate limiting algorithm to use. Example names are ``fixed_window``, -``sliding_window`` and ``no_limit``. See :ref:`Rate Limiter Policies `) -for more information. +The maximum number of redirects to follow. Use ``0`` to not follow any +redirection. -request -~~~~~~~ +.. _reference-http-client-retry-max-retries: -formats -....... +max_retries +........... -**type**: ``array`` **default**: ``[]`` +**type**: ``integer`` **default**: ``3`` -This setting is used to associate additional request formats (e.g. ``html``) -to one or more mime types (e.g. ``text/html``), which will allow you to use the -format & mime types to call -:method:`Request::getFormat($mimeType) ` or -:method:`Request::getMimeType($format) `. +The maximum number of retries for failing requests. When the maximum is reached, +the client returns the last received response. -In practice, this is important because Symfony uses it to automatically set the -``Content-Type`` header on the ``Response`` (if you don't explicitly set one). -If you pass an array of mime types, the first will be used for the header. +.. _reference-http-client-retry-multiplier: -To configure a ``jsonp`` format: +multiplier +.......... -.. configuration-block:: +**type**: ``float`` **default**: ``2`` - .. code-block:: yaml +This value is multiplied to the delay each time a retry occurs, to distribute +retries in time instead of making all of them sequentially. - # config/packages/framework.yaml - framework: - request: - formats: - jsonp: 'application/javascript' +no_proxy +........ - .. code-block:: xml +**type**: ``string`` | ``null`` **default**: ``null`` - - +A comma separated list of hosts that do not require a proxy to be reached, even +if one is configured. Use the ``'*'`` wildcard to match all hosts and an empty +string to match none (disables the proxy). - +passphrase +.......... - - - - application/javascript - - - - +**type**: ``string`` - .. code-block:: php +The passphrase used to encrypt the certificate stored in the file defined in the +``local_cert`` option. - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +peer_fingerprint +................ - return static function (FrameworkConfig $framework): void { - $framework->request() - ->format('jsonp', 'application/javascript'); - }; +**type**: ``array`` -router -~~~~~~ +When negotiating a TLS connection, the server sends a certificate +indicating its identity. A public key is extracted from this certificate and if +it does not exactly match any of the public keys provided in this option, the +connection is aborted before sending or receiving any data. -resource -........ +The value of this option is an associative array of ``algorithm => hash`` +(e.g ``['pin-sha256' => '...']``). -**type**: ``string`` **required** +proxy +..... -The path the main routing resource (e.g. a YAML file) that contains the -routes and imports the router should load. +**type**: ``string`` | ``null`` -.. _reference-router-type: +The HTTP proxy to use to make the requests. Leave it to ``null`` to detect the +proxy automatically based on your system configuration. -type -.... +query +..... -**type**: ``string`` +**type**: ``array`` -The type of the resource to hint the loaders about the format. This isn't -needed when you use the default routers with the expected file extensions -(``.xml``, ``.yaml``, ``.php``). +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, ...]``. -default_uri -........... +rate_limiter +............ **type**: ``string`` -The default URI used to generate URLs in a non-HTTP context (see -:ref:`Generating URLs in Commands `). +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`. -http_port -......... +.. versionadded:: 7.1 -**type**: ``integer`` **default**: ``80`` + The ``rate_limiter`` option was introduced in Symfony 7.1. -The port for normal http requests (this is used when matching the scheme). +resolve +....... -https_port -.......... +**type**: ``array`` -**type**: ``integer`` **default**: ``443`` +A list of hostnames and their IP addresses to pre-populate the DNS cache used by +the HTTP client in order to avoid a DNS lookup for those hosts. This option is +useful to improve security when IPs are checked before the URL is passed to the +client and to make your tests easier. -The port for https requests (this is used when matching the scheme). +The value of this option is an associative array of ``domain => IP address`` +(e.g ``['symfony.com' => '46.137.106.254', ...]``). -strict_requirements -................... +.. _reference-http-client-retry-failed: -**type**: ``mixed`` **default**: ``true`` +retry_failed +............ -Determines the routing generator behavior. When generating a route that -has specific :ref:`parameter requirements `, the generator -can behave differently in case the used parameters do not meet these requirements. +**type**: ``array`` -The value can be one of: +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: -``true`` - Throw an exception when the requirements are not met; -``false`` - Disable exceptions when the requirements are not met and return ``''`` - instead; -``null`` - Disable checking the requirements (thus, match the route even when the - requirements don't match). +* :ref:`delay ` +* :ref:`http_codes ` +* :ref:`jitter ` +* :ref:`max_delay ` +* :ref:`max_retries ` +* :ref:`multiplier ` -``true`` is recommended in the development environment, while ``false`` -or ``null`` might be preferred in production. +.. code-block:: yaml -utf8 -.... + # 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 -**type**: ``boolean`` **default**: ``true`` +retry_strategy +.............. -When this option is set to ``true``, the regular expressions used in the -:ref:`requirements of route parameters ` will be run -using the `utf-8 modifier`_. This will for example match any UTF-8 character -when using ``.``, instead of matching only a single byte. +**type**: ``string`` -If the charset of your application is UTF-8 (as defined in the -:ref:`getCharset() method ` of your kernel) it's -recommended setting it to ``true``. This will make non-UTF8 URLs to generate 404 -errors. +The service is used to decide if a request should be retried and to compute the +time to wait between retries. By default, it uses an instance of +:class:`Symfony\\Component\\HttpClient\\Retry\\GenericRetryStrategy` configured +with ``http_codes``, ``delay``, ``max_delay``, ``multiplier`` and ``jitter`` +options. This class has to implement +:class:`Symfony\\Component\\HttpClient\\Retry\\RetryStrategyInterface`. -cache_dir -......... +scope +..... -**type**: ``string`` **default**: ``%kernel.cache_dir%`` +**type**: ``string`` -The directory where routing information will be cached. Can be set to -``~`` (``null``) to disable route caching. +For scoped clients only: the regular expression that the URL must match before +applying all other non-default options. By default, the scope is derived from +`base_uri`_. -.. deprecated:: 7.1 +timeout +....... - Setting the ``cache_dir`` option is deprecated since Symfony 7.1. The routes - are now always cached in the ``%kernel.build_dir%`` directory. +**type**: ``float`` **default**: depends on your PHP config -secrets -~~~~~~~ +Time, in seconds, to wait for network activity. If the connection is idle for longer, a +:class:`Symfony\\Component\\HttpClient\\Exception\\TransportException` is thrown. +Its default value is the same as the value of PHP's `default_socket_timeout`_ +config option. -enabled -....... +verify_host +........... **type**: ``boolean`` **default**: ``true`` -Whether to enable or not secrets managements. - -decryption_env_var -.................. +If ``true``, the certificate sent by other servers is verified to ensure that +their common name matches the host included in the URL. This is usually +combined with ``verify_peer`` to also verify the certificate authenticity. -**type**: ``string`` **default**: ``base64:default::SYMFONY_DECRYPTION_SECRET`` +verify_peer +........... -The env var name that contains the vault decryption secret. By default, this -value will be decoded from base64. +**type**: ``boolean`` **default**: ``true`` -local_dotenv_file -................. +If ``true``, the certificate sent by other servers when negotiating a TLS +connection is verified for authenticity. Authenticating the certificate is not +enough to be sure about the server, so you should combine this with the +``verify_host`` option. -**type**: ``string`` **default**: ``%kernel.project_dir%/.env.%kernel.environment%.local`` + .. _configuration-framework-http_method_override: -The path to the local ``.env`` file. This file must contain the vault -decryption key, given by the ``decryption_env_var`` option. +http_method_override +~~~~~~~~~~~~~~~~~~~~ -vault_directory -............... +**type**: ``boolean`` **default**: ``false`` -**type**: ``string`` **default**: ``%kernel.project_dir%/config/secrets/%kernel.runtime_environment%`` +This determines whether the ``_method`` request parameter is used as the +intended HTTP method on POST requests. If enabled, the +:method:`Request::enableHttpMethodParameterOverride ` +method gets called automatically. It becomes the service container parameter +named ``kernel.http_method_override``. -The directory to store the secret vault. By default, the path includes the value -of the :ref:`kernel.runtime_environment ` -parameter. +.. seealso:: -.. _config-framework-session: + :ref:`Changing the Action and HTTP Method ` of + Symfony forms. -session -~~~~~~~ +.. warning:: -.. _storage_id: + If you're using the :ref:`HttpCache Reverse Proxy ` + with this option, the kernel will ignore the ``_method`` parameter, + which could lead to errors. -storage_factory_id -.................. + To fix this, invoke the ``enableHttpMethodParameterOverride()`` method + before creating the ``Request`` object:: -**type**: ``string`` **default**: ``session.storage.factory.native`` + // public/index.php -The service ID used for creating the ``SessionStorageInterface`` that stores -the session. This service is available in the Symfony application via the -``session.storage.factory`` service alias. The class has to implement -:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\SessionStorageFactoryInterface`. -To see a list of all available storages, run: + // ... + $kernel = new CacheKernel($kernel); -.. code-block:: terminal + Request::enableHttpMethodParameterOverride(); // <-- add this line + $request = Request::createFromGlobals(); + // ... - $ php bin/console debug:container session.storage.factory. +ide +~~~ -.. _config-framework-session-handler-id: +**type**: ``string`` **default**: ``%env(default::SYMFONY_IDE)%`` -handler_id -.......... +Symfony turns file paths seen in variable dumps and exception messages into +links that open those files right inside your browser. If you prefer to open +those files in your favorite IDE or text editor, set this option to any of the +following values: ``phpstorm``, ``sublime``, ``textmate``, ``macvim``, ``emacs``, +``atom`` and ``vscode``. -**type**: ``string`` | ``null`` **default**: ``null`` +.. note:: -If ``framework.session.save_path`` is not set, the default value of this option -is ``null``, which means to use the session handler configured in php.ini. If the -``framework.session.save_path`` option is set, then Symfony stores sessions using -the native file session handler. + The ``phpstorm`` option is supported natively by PhpStorm on macOS and + Windows; Linux requires installing `phpstorm-url-handler`_. -It is possible to :ref:`store sessions in a database `, -and also to configure the session handler with a DSN: +If you use another editor, the expected configuration value is a URL template +that contains an ``%f`` placeholder where the file path is expected and ``%l`` +placeholder for the line number (percentage signs (``%``) must be escaped by +doubling them to prevent Symfony from interpreting them as container parameters). .. configuration-block:: @@ -1639,12 +1947,7 @@ and also to configure the session handler with a DSN: # config/packages/framework.yaml framework: - session: - # a few possible examples - handler_id: 'redis://localhost' - handler_id: '%env(REDIS_URL)%' - handler_id: '%env(DATABASE_URL)%' - handler_id: 'file://%kernel.project_dir%/var/sessions' + ide: 'myide://open?url=file://%%f&line=%%l' .. code-block:: xml @@ -1656,268 +1959,290 @@ and also to configure the session handler with a DSN: 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"> - - - - + + .. code-block:: php // config/packages/framework.php - use function Symfony\Component\DependencyInjection\Loader\Configurator\env; use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - // ... - - $framework->session() - // a few possible examples - ->handlerId('redis://localhost') - ->handlerId(env('REDIS_URL')) - ->handlerId(env('DATABASE_URL')) - ->handlerId('file://%kernel.project_dir%/var/sessions'); + $framework->ide('myide://open?url=file://%%f&line=%%l'); }; +Since every developer uses a different IDE, the recommended way to enable this +feature is to configure it on a system level. First, you can define this option +in the ``SYMFONY_IDE`` environment variable, which Symfony reads automatically +when ``framework.ide`` config is not set. + +Another alternative is to set the ``xdebug.file_link_format`` option in your +``php.ini`` configuration file. The format to use is the same as for the +``framework.ide`` option, but without the need to escape the percent signs +(``%``) by doubling them: + +.. code-block:: ini + + // example for PhpStorm + xdebug.file_link_format="phpstorm://open?file=%f&line=%l" + + // example for PhpStorm with Jetbrains Toolbox + xdebug.file_link_format="jetbrains://phpstorm/navigate/reference?project=example&path=%f:%l" + + // example for Sublime Text + xdebug.file_link_format="subl://open?url=file://%f&line=%l" + .. note:: - Supported DSN protocols are the following: + If both ``framework.ide`` and ``xdebug.file_link_format`` are defined, + Symfony uses the value of the ``xdebug.file_link_format`` option. - * ``file`` - * ``redis`` - * ``rediss`` (Redis over TLS) - * ``memcached`` (requires :doc:`symfony/cache `) - * ``pdo_oci`` (requires :doc:`doctrine/dbal `) - * ``mssql`` - * ``mysql`` - * ``mysql2`` - * ``pgsql`` - * ``postgres`` - * ``postgresql`` - * ``sqlsrv`` - * ``sqlite`` - * ``sqlite3`` +.. tip:: -.. _name: + Setting the ``xdebug.file_link_format`` ini option works even if the Xdebug + extension is not enabled. -name -.... +.. tip:: -**type**: ``string`` + When running your app in a container or in a virtual machine, you can tell + Symfony to map files from the guest to the host by changing their prefix. + This map should be specified at the end of the URL template, using ``&`` and + ``>`` as guest-to-host separators: -This specifies the name of the session cookie. + .. code-block:: text -If not set, ``php.ini``'s `session.name`_ directive will be relied on. + // /path/to/guest/.../file will be opened + // as /path/to/host/.../file on the host + // and /var/www/app/ as /projects/my_project/ also + 'myide://%%f:%%l&/path/to/guest/>/path/to/host/&/var/www/app/>/projects/my_project/&...' -cookie_lifetime -............... + // example for PhpStorm + 'phpstorm://open?file=%%f&line=%%l&/var/www/app/>/projects/my_project/' -**type**: ``integer`` +.. _reference-lock: -This determines the lifetime of the session - in seconds. -Setting this value to ``0`` means the cookie is valid for -the length of the browser session. +lock +~~~~ -If not set, ``php.ini``'s `session.cookie_lifetime`_ directive will be relied on. +**type**: ``string`` | ``array`` -cookie_path -........... +The default lock adapter. If not defined, the value is set to ``semaphore`` when +available, or to ``flock`` otherwise. Store's DSN are also allowed. -**type**: ``string`` +.. _reference-lock-enabled: -This determines the path to set in the session cookie. +enabled +....... -If not set, ``php.ini``'s `session.cookie_path`_ directive will be relied on. +**type**: ``boolean`` **default**: ``true`` -cache_limiter -............. +Whether to enable the support for lock or not. This setting is +automatically set to ``true`` when one of the child settings is configured. -**type**: ``string`` **default**: ``0`` +.. _reference-lock-resources: + +resources +......... -If set to ``0``, Symfony won't set any particular header related to the cache -and it will rely on ``php.ini``'s `session.cache_limiter`_ directive. +**type**: ``array`` -Unlike the other session options, ``cache_limiter`` is set as a regular -:ref:`container parameter `: +A map of lock stores to be created by the framework extension, with +the name as key and DSN as value: .. configuration-block:: .. code-block:: yaml - # config/services.yaml - parameters: - session.storage.options: - cache_limiter: 0 + # config/packages/lock.yaml + framework: + lock: '%env(LOCK_DSN)%' .. code-block:: xml - + + 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"> - - - 0 - - + + + %env(LOCK_DSN)% + + .. code-block:: php - // config/services.php - $container->setParameter('session.storage.options', [ - 'cache_limiter' => 0, - ]); + // config/packages/lock.php + use Symfony\Config\FrameworkConfig; -Be aware that if you configure it, you'll have to set other session-related options -as parameters as well. + return static function (FrameworkConfig $framework): void { + $framework->lock() + ->resource('default', [env('LOCK_DSN')]); + }; -cookie_domain -............. +.. seealso:: -**type**: ``string`` + For more details, see :doc:`/lock`. -This determines the domain to set in the session cookie. +.. _reference-lock-resources-name: -If not set, ``php.ini``'s `session.cookie_domain`_ directive will be relied on. +name +"""" -cookie_samesite -............... +**type**: ``prototype`` -**type**: ``string`` or ``null`` **default**: ``null`` +Name of the lock you want to create. -It controls the way cookies are sent when the HTTP request did not originate -from the same domain that is associated with the cookies. Setting this option is -recommended to mitigate `CSRF security attacks`_. +mailer +~~~~~~ -By default, browsers send all cookies related to the domain of the HTTP request. -This may be a problem for example when you visit a forum and some malicious -comment includes a link like ``https://some-bank.com/?send_money_to=attacker&amount=1000``. -If you were previously logged into your bank website, the browser will send all -those cookies when making that HTTP request. +.. _mailer-dsn: -The possible values for this option are: +dsn +... -* ``null``, use ``php.ini``'s `session.cookie_samesite`_ directive. -* ``'none'`` (or the ``Symfony\Component\HttpFoundation\Cookie::SAMESITE_NONE`` constant), use it to allow - sending of cookies when the HTTP request originated from a different domain - (previously this was the default behavior of null, but in newer browsers ``'lax'`` - would be applied when the header has not been set) -* ``'strict'`` (or the ``Cookie::SAMESITE_STRICT`` constant), use it to never - send any cookie when the HTTP request did not originate from the same domain. -* ``'lax'`` (or the ``Cookie::SAMESITE_LAX`` constant), use it to allow sending - cookies when the request originated from a different domain, but only when the - user consciously made the request (by clicking a link or submitting a form - with the ``GET`` method). +**type**: ``string`` **default**: ``null`` -cookie_secure -............. +The DSN used by the mailer. When several DSN may be used, use +``transports`` option (see below) instead. -**type**: ``boolean`` or ``'auto'`` +envelope +........ -This determines whether cookies should only be sent over secure connections. In -addition to ``true`` and ``false``, there's a special ``'auto'`` value that -means ``true`` for HTTPS requests and ``false`` for HTTP requests. +recipients +"""""""""" -If not set, ``php.ini``'s `session.cookie_secure`_ directive will be relied on. +**type**: ``array`` -cookie_httponly -............... +The "envelope recipient" which is used as the value of ``RCPT TO`` during the +the `SMTP session`_. This value overrides any other recipient set in the code. -**type**: ``boolean`` **default**: ``true`` +.. configuration-block:: -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 :ref:`XSS attacks `. + .. code-block:: yaml -gc_divisor -.......... + # config/packages/mailer.yaml + framework: + mailer: + dsn: 'smtp://localhost:25' + envelope: + recipients: ['admin@symfony.com', 'lead@symfony.com'] -**type**: ``integer`` + .. code-block:: xml -See `gc_probability`_. + + + + + + + admin@symfony.com + lead@symfony.com + + + + -If not set, ``php.ini``'s `session.gc_divisor`_ directive will be relied on. + .. code-block:: php -gc_probability -.............. + // config/packages/mailer.php + namespace Symfony\Component\DependencyInjection\Loader\Configurator; -**type**: ``integer`` + return static function (ContainerConfigurator $container): void { + $container->extension('framework', [ + 'mailer' => [ + 'dsn' => 'smtp://localhost:25', + 'envelope' => [ + 'recipients' => [ + 'admin@symfony.com', + 'lead@symfony.com', + ], + ], + ], + ]); + }; -This defines the probability that the garbage collector (GC) process is -started on every session initialization. The probability is calculated by -using ``gc_probability`` / ``gc_divisor``, e.g. 1/100 means there is a 1% -chance that the GC process will start on each request. +sender +"""""" -If not set, Symfony will use the value of the `session.gc_probability`_ directive -in the ``php.ini`` configuration file. +**type**: ``string`` -.. versionadded:: 7.2 +The "envelope sender" which is used as the value of ``MAIL FROM`` during the +`SMTP session`_. This value overrides any other sender set in the code. - Relying on ``php.ini``'s directive as default for ``gc_probability`` was - introduced in Symfony 7.2. +.. _mailer-headers: -gc_maxlifetime -.............. +headers +....... -**type**: ``integer`` +**type**: ``array`` -This determines the number of seconds after which data will be seen as "garbage" -and potentially cleaned up. Garbage collection may occur during session -start and depends on `gc_divisor`_ and `gc_probability`_. +Headers to add to emails. The key (``name`` attribute in xml format) is the +header name and value the header value. -If not set, ``php.ini``'s `session.gc_maxlifetime`_ directive will be relied on. +.. seealso:: -sid_length -.......... + For more information, see :ref:`Configuring Emails Globally ` -**type**: ``integer`` +message_bus +........... -This determines the length of session ID string, which can be an integer between -``22`` and ``256`` (both inclusive), ``32`` being the recommended value. Longer -session IDs are harder to guess. +**type**: ``string`` **default**: ``null`` or default bus if Messenger component is installed -If not set, ``php.ini``'s `session.sid_length`_ directive will be relied on. +Service identifier of the message bus to use when using the +:doc:`Messenger component ` (e.g. ``messenger.default_bus``). -.. deprecated:: 7.2 +transports +.......... - The ``sid_length`` option was deprecated in Symfony 7.2. No alternative is - provided as PHP 8.4 has deprecated the related option. +**type**: ``array`` -sid_bits_per_character -...................... +A :ref:`list of DSN ` that can be used by the +mailer. A transport name is the key and the dsn is the value. -**type**: ``integer`` +messenger +~~~~~~~~~ -This determines the number of bits in the encoded session ID character. The possible -values are ``4`` (0-9, a-f), ``5`` (0-9, a-v), and ``6`` (0-9, a-z, A-Z, "-", ","). -The more bits results in stronger session ID. ``5`` is recommended value for -most environments. +enabled +....... -If not set, ``php.ini``'s `session.sid_bits_per_character`_ directive will be relied on. +**type**: ``boolean`` **default**: ``true`` -.. deprecated:: 7.2 +Whether to enable or not Messenger. - The ``sid_bits_per_character`` option was deprecated in Symfony 7.2. No alternative - is provided as PHP 8.4 has deprecated the related option. +.. seealso:: -save_path -......... + For more details, see the :doc:`Messenger component ` + documentation. -**type**: ``string`` | ``null`` **default**: ``%kernel.cache_dir%/sessions`` +php_errors +~~~~~~~~~~ -This determines the argument to be passed to the save handler. If you choose -the default file handler, this is the path where the session files are created. +log +... -If ``null``, ``php.ini``'s `session.save_path`_ directive will be relied on: +**type**: ``boolean`` | ``int`` | ``array`` **default**: ``true`` + +Use the application logger instead of the PHP logger for logging PHP errors. +When an integer value is used, it defines a bitmask of PHP errors that will +be logged. Those integer values must be the same used in the +`error_reporting PHP option`_. The default log levels will be used for each +PHP error. +When a boolean value is used, ``true`` enables logging for all PHP errors +while ``false`` disables logging entirely. + +This option also accepts a map of PHP errors to log levels: .. configuration-block:: @@ -1925,8 +2250,23 @@ If ``null``, ``php.ini``'s `session.save_path`_ directive will be relied on: # config/packages/framework.yaml framework: - session: - save_path: ~ + php_errors: + log: + !php/const \E_DEPRECATED: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_USER_DEPRECATED: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_NOTICE: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_USER_NOTICE: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_STRICT: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_WARNING: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_USER_WARNING: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_COMPILE_WARNING: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_CORE_WARNING: !php/const Psr\Log\LogLevel::ERROR + !php/const \E_USER_ERROR: !php/const Psr\Log\LogLevel::CRITICAL + !php/const \E_RECOVERABLE_ERROR: !php/const Psr\Log\LogLevel::CRITICAL + !php/const \E_COMPILE_ERROR: !php/const Psr\Log\LogLevel::CRITICAL + !php/const \E_PARSE: !php/const Psr\Log\LogLevel::CRITICAL + !php/const \E_ERROR: !php/const Psr\Log\LogLevel::CRITICAL + !php/const \E_CORE_ERROR: !php/const Psr\Log\LogLevel::CRITICAL .. code-block:: xml @@ -1940,282 +2280,225 @@ If ``null``, ``php.ini``'s `session.save_path`_ directive will be relied on: http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> - + + + + .. code-block:: php // config/packages/framework.php + use Psr\Log\LogLevel; use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->session() - ->savePath(null); + $framework->phpErrors()->log(\E_DEPRECATED, LogLevel::ERROR); + $framework->phpErrors()->log(\E_USER_DEPRECATED, LogLevel::ERROR); + // ... }; -.. _reference-session-metadata-update-threshold: - -metadata_update_threshold -......................... +throw +..... -**type**: ``integer`` **default**: ``0`` +**type**: ``boolean`` **default**: ``%kernel.debug%`` -This is how many seconds to wait between updating/writing the session metadata. -This can be useful if, for some reason, you want to limit the frequency at which -the session persists, instead of doing that on every request. +Throw PHP errors as ``\ErrorException`` instances. The parameter +``debug.error_handler.throw_at`` controls the threshold. -.. _reference-session-enabled: +profiler +~~~~~~~~ -enabled +collect ....... **type**: ``boolean`` **default**: ``true`` -Whether to enable the session support in the framework. +This option configures the way the profiler behaves when it is enabled. If set +to ``true``, the profiler collects data for all requests. If you want to only +collect information on-demand, you can set the ``collect`` flag to ``false`` and +activate the data collectors manually:: -.. configuration-block:: + $profiler->enable(); - .. code-block:: yaml +collect_parameter +................. - # config/packages/framework.yaml - framework: - session: - enabled: true +**type**: ``string`` **default**: ``null`` - .. code-block:: xml +This specifies name of a query parameter, a body parameter or a request attribute +used to enable or disable collection of data by the profiler for each request. +Combine it with the ``collect`` option to enable/disable the profiler on demand: - - - +* If the ``collect`` option is set to ``true`` but this parameter exists in a + request and has any value other than ``true``, ``yes``, ``on`` or ``1``, the + request data will not be collected; +* If the ``collect`` option is set to ``false``, but this parameter exists in a + request and has value of ``true``, ``yes``, ``on`` or ``1``, the request data + will be collected. - - - - +.. _collect_serializer_data: - .. code-block:: php +collect_serializer_data +....................... - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +**type**: ``boolean`` **default**: ``false`` - return static function (FrameworkConfig $framework): void { - $framework->session() - ->enabled(true); - }; +Set this option to ``true`` to enable the serializer data collector and its +profiler panel. When this option is ``true``, all normalizers and encoders are +decorated by traceable implementations that collect profiling information about them. -use_cookies -........... +.. _profiler-dsn: -**type**: ``boolean`` +dsn +... -This specifies if the session ID is stored on the client side using cookies or -not. +**type**: ``string`` **default**: ``file:%kernel.cache_dir%/profiler`` -If not set, ``php.ini``'s `session.use_cookies`_ directive will be relied on. +The DSN where to store the profiling information. -ssi -~~~ +.. _reference-profiler-enabled: enabled ....... **type**: ``boolean`` **default**: ``false`` -Whether to enable or not SSI support in your application. - -assets -~~~~~~ - -.. _reference-assets-base-path: +The profiler can be enabled by setting this option to ``true``. When you +install it using Symfony Flex, the profiler is enabled in the ``dev`` +and ``test`` environments. -base_path -......... +.. note:: -**type**: ``string`` + The profiler works independently from the Web Developer Toolbar, see + the :doc:`WebProfilerBundle configuration ` + on how to disable/enable the toolbar. -This option allows you to define a base path to be used for assets: +only_exceptions +............... -.. configuration-block:: +**type**: ``boolean`` **default**: ``false`` - .. code-block:: yaml +When this is set to ``true``, the profiler will only be enabled when an +exception is thrown during the handling of the request. - # config/packages/framework.yaml - framework: - # ... - assets: - base_path: '/images' +.. _only_master_requests: - .. code-block:: xml +only_main_requests +.................. - - - +**type**: ``boolean`` **default**: ``false`` - - - - +When this is set to ``true``, the profiler will only be enabled on the main +requests (and not on the subrequests). - .. code-block:: php +property_access +~~~~~~~~~~~~~~~ - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +magic_call +.......... - return static function (FrameworkConfig $framework): void { - // ... - $framework->assets() - ->basePath('/images'); - }; +**type**: ``boolean`` **default**: ``false`` -.. _reference-templating-base-urls: -.. _reference-assets-base-urls: +When enabled, the ``property_accessor`` service uses PHP's +:ref:`magic __call() method ` when +its ``getValue()`` method is called. -base_urls +magic_get ......... -**type**: ``array`` - -This option allows you to define base URLs to be used for assets. -If multiple base URLs are provided, Symfony will select one from the -collection each time it generates an asset's path: - -.. configuration-block:: - - .. code-block:: yaml - - # config/packages/framework.yaml - framework: - # ... - assets: - base_urls: - - 'http://cdn.example.com/' - - .. code-block:: xml - - - - - - - - - +**type**: ``boolean`` **default**: ``true`` - .. code-block:: php +When enabled, the ``property_accessor`` service uses PHP's +:ref:`magic __get() method ` when +its ``getValue()`` method is called. - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +magic_set +......... - return static function (FrameworkConfig $framework): void { - // ... - $framework->assets() - ->baseUrls(['http://cdn.example.com/']); - }; +**type**: ``boolean`` **default**: ``true`` -.. _reference-framework-assets-packages: +When enabled, the ``property_accessor`` service uses PHP's +:ref:`magic __set() method ` when +its ``setValue()`` method is called. -packages -........ +throw_exception_on_invalid_index +................................ -You can group assets into packages, to specify different base URLs for them: +**type**: ``boolean`` **default**: ``false`` -.. configuration-block:: +When enabled, the ``property_accessor`` service throws an exception when you +try to access an invalid index of an array. - .. code-block:: yaml +throw_exception_on_invalid_property_path +........................................ - # config/packages/framework.yaml - framework: - # ... - assets: - packages: - avatars: - base_urls: 'http://static_cdn.example.com/avatars' +**type**: ``boolean`` **default**: ``true`` - .. code-block:: xml +When enabled, the ``property_accessor`` service throws an exception when you +try to access an invalid property path of an object. - - - +property_info +~~~~~~~~~~~~~ - - - - - - +.. _reference-property-info-enabled: - .. code-block:: php +enabled +....... - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation - return static function (FrameworkConfig $framework): void { - // ... - $framework->assets() - ->package('avatars') - ->baseUrls(['http://static_cdn.example.com/avatars']); - }; +rate_limiter +~~~~~~~~~~~~ -Now you can use the ``avatars`` package in your templates: +.. _reference-rate-limiter-name: -.. code-block:: html+twig +name +.... - +**type**: ``prototype`` -Each package can configure the following options: +Name of the rate limiter you want to create. -* :ref:`base_path ` -* :ref:`base_urls ` -* :ref:`version_strategy ` -* :ref:`version ` -* :ref:`version_format ` -* :ref:`json_manifest_path ` -* :ref:`strict_mode ` +lock_factory +"""""""""""" -.. _reference-framework-assets-version: -.. _ref-framework-assets-version: +**type**: ``string`` **default:** ``lock.factory`` -version -....... +The service that is used to create a lock. The service has to be an instance of +the :class:`Symfony\\Component\\Lock\\LockFactory` class. -**type**: ``string`` +policy +"""""" -This option is used to *bust* the cache on assets by globally adding a query -parameter to all rendered asset paths (e.g. ``/images/logo.png?v2``). This -applies only to assets rendered via the Twig ``asset()`` function (or PHP -equivalent). +**type**: ``string`` **required** -For example, suppose you have the following: +The name of the rate limiting algorithm to use. Example names are ``fixed_window``, +``sliding_window`` and ``no_limit``. See :ref:`Rate Limiter Policies `) +for more information. -.. code-block:: html+twig +request +~~~~~~~ - Symfony! +formats +....... -By default, this will render a path to your image such as ``/images/logo.png``. -Now, activate the ``version`` option: +**type**: ``array`` **default**: ``[]`` + +This setting is used to associate additional request formats (e.g. ``html``) +to one or more mime types (e.g. ``text/html``), which will allow you to use the +format & mime types to call +:method:`Request::getFormat($mimeType) ` or +:method:`Request::getMimeType($format) `. + +In practice, this is important because Symfony uses it to automatically set the +``Content-Type`` header on the ``Response`` (if you don't explicitly set one). +If you pass an array of mime types, the first will be used for the header. + +To configure a ``jsonp`` format: .. configuration-block:: @@ -2223,23 +2506,29 @@ Now, activate the ``version`` option: # config/packages/framework.yaml framework: - # ... - assets: - version: 'v2' + request: + formats: + jsonp: 'application/javascript' .. code-block:: xml + + http://symfony.com/schema/dic/symfony + https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> - + + + application/javascript + + @@ -2249,583 +2538,464 @@ Now, activate the ``version`` option: use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - // ... - $framework->assets() - ->version('v2'); + $framework->request() + ->format('jsonp', 'application/javascript'); }; -Now, the same asset will be rendered as ``/images/logo.png?v2`` If you use -this feature, you **must** manually increment the ``version`` value -before each deployment so that the query parameters change. - -You can also control how the query string works via the `version_format`_ -option. - -.. note:: - - This parameter cannot be set at the same time as ``version_strategy`` or ``json_manifest_path``. - -.. tip:: - - As with all settings, you can use a parameter as value for the - ``version``. This makes it easier to increment the cache on each - deployment. - -.. _reference-templating-version-format: -.. _reference-assets-version-format: - -version_format -.............. - -**type**: ``string`` **default**: ``%%s?%%s`` - -This specifies a :phpfunction:`sprintf` pattern that will be used with the -`version`_ option to construct an asset's path. By default, the pattern -adds the asset's version as a query string. For example, if -``version_format`` is set to ``%%s?version=%%s`` and ``version`` -is set to ``5``, the asset's path would be ``/images/logo.png?version=5``. - -.. note:: - - All percentage signs (``%``) in the format string must be doubled to - escape the character. Without escaping, values might inadvertently be - interpreted as :ref:`service-container-parameters`. +router +~~~~~~ -.. tip:: +cache_dir +......... - Some CDN's do not support cache-busting via query strings, so injecting - the version into the actual file path is necessary. Thankfully, - ``version_format`` is not limited to producing versioned query - strings. +**type**: ``string`` **default**: ``%kernel.cache_dir%`` - The pattern receives the asset's original path and version as its first - and second parameters, respectively. Since the asset's path is one - parameter, you cannot modify it in-place (e.g. ``/images/logo-v5.png``); - however, you can prefix the asset's path using a pattern of - ``version-%%2$s/%%1$s``, which would result in the path - ``version-5/images/logo.png``. +The directory where routing information will be cached. Can be set to +``~`` (``null``) to disable route caching. - URL rewrite rules could then be used to disregard the version prefix - before serving the asset. Alternatively, you could copy assets to the - appropriate version path as part of your deployment process and forgot - any URL rewriting. The latter option is useful if you would like older - asset versions to remain accessible at their original URL. +.. deprecated:: 7.1 -.. _reference-assets-version-strategy: -.. _reference-templating-version-strategy: + Setting the ``cache_dir`` option is deprecated since Symfony 7.1. The routes + are now always cached in the ``%kernel.build_dir%`` directory. -version_strategy -................ +default_uri +........... -**type**: ``string`` **default**: ``null`` +**type**: ``string`` -The service id of the :doc:`asset version strategy ` -applied to the assets. This option can be set globally for all assets and -individually for each asset package: +The default URI used to generate URLs in a non-HTTP context (see +:ref:`Generating URLs in Commands `). -.. configuration-block:: +http_port +......... - .. code-block:: yaml +**type**: ``integer`` **default**: ``80`` - # config/packages/framework.yaml - framework: - assets: - # this strategy is applied to every asset (including packages) - version_strategy: 'app.asset.my_versioning_strategy' - packages: - foo_package: - # this package removes any versioning (its assets won't be versioned) - version: ~ - bar_package: - # this package uses its own strategy (the default strategy is ignored) - version_strategy: 'app.asset.another_version_strategy' - baz_package: - # this package inherits the default strategy - base_path: '/images' +The port for normal http requests (this is used when matching the scheme). - .. code-block:: xml +https_port +.......... - - - +**type**: ``integer`` **default**: ``443`` - - - - - - - - - - - +The port for https requests (this is used when matching the scheme). - .. code-block:: php +resource +........ - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +**type**: ``string`` **required** - return static function (FrameworkConfig $framework): void { - // ... - $framework->assets() - ->versionStrategy('app.asset.my_versioning_strategy'); +The path the main routing resource (e.g. a YAML file) that contains the +routes and imports the router should load. - $framework->assets()->package('foo_package') - // this package removes any versioning (its assets won't be versioned) - ->version(null); +strict_requirements +................... - $framework->assets()->package('bar_package') - // this package uses its own strategy (the default strategy is ignored) - ->versionStrategy('app.asset.another_version_strategy'); +**type**: ``mixed`` **default**: ``true`` - $framework->assets()->package('baz_package') - // this package inherits the default strategy - ->basePath('/images'); - }; +Determines the routing generator behavior. When generating a route that +has specific :ref:`parameter requirements `, the generator +can behave differently in case the used parameters do not meet these requirements. -.. note:: +The value can be one of: - This parameter cannot be set at the same time as ``version`` or ``json_manifest_path``. +``true`` + Throw an exception when the requirements are not met; +``false`` + Disable exceptions when the requirements are not met and return ``''`` + instead; +``null`` + Disable checking the requirements (thus, match the route even when the + requirements don't match). -.. _reference-assets-json-manifest-path: -.. _reference-templating-json-manifest-path: +``true`` is recommended in the development environment, while ``false`` +or ``null`` might be preferred in production. -json_manifest_path -.................. +.. _reference-router-type: -**type**: ``string`` **default**: ``null`` +type +.... -The file path or absolute URL to a ``manifest.json`` file containing an -associative array of asset names and their respective compiled names. A common -cache-busting technique using a "manifest" file works by writing out assets with -a "hash" appended to their file names (e.g. ``main.ae433f1cb.css``) during a -front-end compilation routine. +**type**: ``string`` -.. tip:: +The type of the resource to hint the loaders about the format. This isn't +needed when you use the default routers with the expected file extensions +(``.xml``, ``.yaml``, ``.php``). - Symfony's :ref:`Webpack Encore ` supports - :ref:`outputting hashed assets `. Moreover, this - can be incorporated into many other workflows, including Webpack and - Gulp using `webpack-manifest-plugin`_ and `gulp-rev`_, respectively. +utf8 +.... -This option can be set globally for all assets and individually for each asset -package: +**type**: ``boolean`` **default**: ``true`` -.. configuration-block:: +When this option is set to ``true``, the regular expressions used in the +:ref:`requirements of route parameters ` will be run +using the `utf-8 modifier`_. This will for example match any UTF-8 character +when using ``.``, instead of matching only a single byte. - .. code-block:: yaml +If the charset of your application is UTF-8 (as defined in the +:ref:`getCharset() method ` of your kernel) it's +recommended setting it to ``true``. This will make non-UTF8 URLs to generate 404 +errors. - # config/packages/framework.yaml - framework: - assets: - # this manifest is applied to every asset (including packages) - json_manifest_path: "%kernel.project_dir%/public/build/manifest.json" - # you can use absolute URLs too and Symfony will download them automatically - # json_manifest_path: 'https://cdn.example.com/manifest.json' - packages: - foo_package: - # this package uses its own manifest (the default file is ignored) - json_manifest_path: "%kernel.project_dir%/public/build/a_different_manifest.json" - # Throws an exception when an asset is not found in the manifest - strict_mode: %kernel.debug% - bar_package: - # this package uses the global manifest (the default file is used) - base_path: '/images' +.. _configuration-framework-secret: - .. code-block:: xml +secret +~~~~~~ - - - +**type**: ``string`` **required** - - - - - - - - - - - - - +This is a string that should be unique to your application and it's commonly +used to add more entropy to security related operations. Its value should +be a series of characters, numbers and symbols chosen randomly and the +recommended length is around 32 characters. - .. code-block:: php +In practice, Symfony uses this value for encrypting the cookies used +in the :doc:`remember me functionality ` and for +creating signed URIs when using :ref:`ESI (Edge Side Includes) `. +That's why you should treat this value as if it were a sensitive credential and +**never make it public**. - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +This option becomes the service container parameter named ``kernel.secret``, +which you can use whenever the application needs an immutable random string +to add more entropy. - return static function (FrameworkConfig $framework): void { - // ... - $framework->assets() - // this manifest is applied to every asset (including packages) - ->jsonManifestPath('%kernel.project_dir%/public/build/manifest.json'); +As with any other security-related parameter, it is a good practice to change +this value from time to time. However, keep in mind that changing this value +will invalidate all signed URIs and Remember Me cookies. That's why, after +changing this value, you should regenerate the application cache and log +out all the application users. - // you can use absolute URLs too and Symfony will download them automatically - // 'json_manifest_path' => 'https://cdn.example.com/manifest.json', - $framework->assets()->package('foo_package') - // this package uses its own manifest (the default file is ignored) - ->jsonManifestPath('%kernel.project_dir%/public/build/a_different_manifest.json') - // Throws an exception when an asset is not found in the manifest - ->setStrictMode('%kernel.debug%'); +secrets +~~~~~~~ - $framework->assets()->package('bar_package') - // this package uses the global manifest (the default file is used) - ->basePath('/images'); - }; +decryption_env_var +.................. -.. note:: +**type**: ``string`` **default**: ``base64:default::SYMFONY_DECRYPTION_SECRET`` - This parameter cannot be set at the same time as ``version`` or ``version_strategy``. - Additionally, this option cannot be nullified at the package scope if a global manifest - file is specified. +The env var name that contains the vault decryption secret. By default, this +value will be decoded from base64. -.. tip:: +enabled +....... - If you request an asset that is *not found* in the ``manifest.json`` file, the original - - *unmodified* - asset path will be returned. - You can set ``strict_mode`` to ``true`` to get an exception when an asset is *not found*. +**type**: ``boolean`` **default**: ``true`` -.. note:: +Whether to enable or not secrets managements. - If a URL is set, the JSON manifest is downloaded on each request using the `http_client`_. +local_dotenv_file +................. -.. _reference-assets-strict-mode: +**type**: ``string`` **default**: ``%kernel.project_dir%/.env.%kernel.environment%.local`` -strict_mode -........... +The path to the local ``.env`` file. This file must contain the vault +decryption key, given by the ``decryption_env_var`` option. -**type**: ``boolean`` **default**: ``false`` +vault_directory +............... -When enabled, the strict mode asserts that all requested assets are in the -manifest file. This option is useful to detect typos or missing assets, the -recommended value is ``%kernel.debug%``. +**type**: ``string`` **default**: ``%kernel.project_dir%/config/secrets/%kernel.runtime_environment%`` -translator -~~~~~~~~~~ +The directory to store the secret vault. By default, the path includes the value +of the :ref:`kernel.runtime_environment ` +parameter. -cache_dir -......... +semaphore +~~~~~~~~~ -**type**: ``string`` | ``null`` **default**: ``%kernel.cache_dir%/translations`` +**type**: ``string`` | ``array`` -Defines the directory where the translation cache is stored. Use ``null`` to -disable this cache. +The default semaphore adapter. Store's DSN are also allowed. -.. _reference-translator-enabled: +.. _reference-semaphore-enabled: enabled ....... -**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation +**type**: ``boolean`` **default**: ``true`` -Whether or not to enable the ``translator`` service in the service container. +Whether to enable the support for semaphore or not. This setting is +automatically set to ``true`` when one of the child settings is configured. -.. _fallback: +.. _reference-semaphore-resources: -fallbacks +resources ......... -**type**: ``string|array`` **default**: value of `default_locale`_ +**type**: ``array`` -This option is used when the translation key for the current locale wasn't -found. +A map of semaphore stores to be created by the framework extension, with +the name as key and DSN as value: -.. seealso:: +.. configuration-block:: - For more details, see :doc:`/translation`. + .. code-block:: yaml -.. _reference-framework-translator-logging: + # config/packages/semaphore.yaml + framework: + semaphore: '%env(SEMAPHORE_DSN)%' -logging -....... + .. code-block:: xml -**default**: ``true`` when the debug mode is enabled, ``false`` otherwise. + + + -When ``true``, a log entry is made whenever the translator cannot find a translation -for a given key. The logs are made to the ``translation`` channel at the -``debug`` level for keys where there is a translation in the fallback -locale, and the ``warning`` level if there is no translation to use at all. + + + %env(SEMAPHORE_DSN)% + + + -.. _reference-framework-translator-formatter: + .. code-block:: php -formatter -......... + // config/packages/semaphore.php + use Symfony\Config\FrameworkConfig; -**type**: ``string`` **default**: ``translator.formatter.default`` + return static function (FrameworkConfig $framework): void { + $framework->semaphore() + ->resource('default', ['%env(SEMAPHORE_DSN)%']); + }; -The ID of the service used to format translation messages. The service class -must implement the :class:`Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface`. +.. _reference-semaphore-resources-name: -.. _reference-translator-paths: +name +"""" + +**type**: ``prototype`` + +Name of the semaphore you want to create. + +.. _configuration-framework-serializer: + +serializer +~~~~~~~~~~ + +.. _reference-serializer-circular_reference_handler: -paths -..... +circular_reference_handler +.......................... -**type**: ``array`` **default**: ``[]`` +**type** ``string`` -This option allows to define an array of paths where the component will look -for translation files. The later a path is added, the more priority it has -(translations from later paths overwrite earlier ones). Translations from the -:ref:`default_path ` have more priority than -translations from all these paths. +The service id that is used as the circular reference handler of the default +serializer. The service has to implement the magic ``__invoke($object)`` +method. -.. _reference-translator-default_path: +.. seealso:: -default_path -............ + For more information, see + :ref:`component-serializer-handling-circular-references`. -**type**: ``string`` **default**: ``%kernel.project_dir%/translations`` +default_context +............... -This option allows to define the path where the application translations files -are stored. +**type**: ``array`` **default**: ``[]`` -.. _reference-translator-providers: +A map with default context options that will be used with each ``serialize`` and ``deserialize`` +call. This can be used for example to set the json encoding behavior by setting ``json_encode_options`` +to a `json_encode flags bitmask`_. -providers -......... +You can inspect the :ref:`serializer context builders ` +to discover the available settings. -**type**: ``array`` **default**: ``[]`` +.. _reference-serializer-enable_annotations: -This option enables and configures :ref:`translation providers ` -to push and pull your translations to/from third party translation services. +enable_attributes +................. -property_access -~~~~~~~~~~~~~~~ +**type**: ``boolean`` **default**: ``true`` -magic_call -.......... +Enables support for `PHP attributes`_ in the serializer component. -**type**: ``boolean`` **default**: ``false`` +.. seealso:: -When enabled, the ``property_accessor`` service uses PHP's -:ref:`magic __call() method ` when -its ``getValue()`` method is called. + See :ref:`the reference ` for a list of supported annotations. -magic_get -......... +.. _reference-serializer-enabled: -**type**: ``boolean`` **default**: ``true`` +enabled +....... -When enabled, the ``property_accessor`` service uses PHP's -:ref:`magic __get() method ` when -its ``getValue()`` method is called. +**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation -magic_set -......... +Whether to enable the ``serializer`` service or not in the service container. -**type**: ``boolean`` **default**: ``true`` +.. _reference-serializer-mapping: -When enabled, the ``property_accessor`` service uses PHP's -:ref:`magic __set() method ` when -its ``setValue()`` method is called. +mapping +....... -throw_exception_on_invalid_index -................................ +.. _reference-serializer-mapping-paths: -**type**: ``boolean`` **default**: ``false`` +paths +""""" -When enabled, the ``property_accessor`` service throws an exception when you -try to access an invalid index of an array. +**type**: ``array`` **default**: ``[]`` -throw_exception_on_invalid_property_path -........................................ +This option allows to define an array of paths with files or directories where +the component will look for additional serialization files. -**type**: ``boolean`` **default**: ``true`` +.. _reference-serializer-name_converter: -When enabled, the ``property_accessor`` service throws an exception when you -try to access an invalid property path of an object. +name_converter +.............. -property_info -~~~~~~~~~~~~~ +**type**: ``string`` -.. _reference-property-info-enabled: +The name converter to use. +The :class:`Symfony\\Component\\Serializer\\NameConverter\\CamelCaseToSnakeCaseNameConverter` +name converter can enabled by using the ``serializer.name_converter.camel_case_to_snake_case`` +value. -enabled -....... +.. seealso:: -**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation + For more information, see :ref:`serializer-name-conversion`. -.. _reference-validation: +.. _config-framework-session: -validation -~~~~~~~~~~ +session +~~~~~~~ -.. _reference-validation-auto-mapping: +cache_limiter +............. -auto_mapping -............ +**type**: ``string`` **default**: ``0`` -**type**: ``array`` **default**: ``[]`` +If set to ``0``, Symfony won't set any particular header related to the cache +and it will rely on ``php.ini``'s `session.cache_limiter`_ directive. -Defines the Doctrine entities that will be introspected to add -:ref:`automatic validation constraints ` to them: +Unlike the other session options, ``cache_limiter`` is set as a regular +:ref:`container parameter `: .. configuration-block:: .. code-block:: yaml - framework: - validation: - auto_mapping: - # an empty array means that all entities that belong to that - # namespace will add automatic validation - 'App\Entity\': [] - 'Foo\': ['Foo\Some\Entity', 'Foo\Another\Entity'] + # config/services.yaml + parameters: + session.storage.options: + cache_limiter: 0 .. code-block:: xml - + - - - - - + https://symfony.com/schema/dic/services/services-1.0.xsd"> - Foo\Some\Entity - Foo\Another\Entity - - - + + + 0 + + .. code-block:: php - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; - - return static function (FrameworkConfig $framework): void { - $framework->validation() - ->autoMapping() - ->paths([ - 'App\\Entity\\' => [], - 'Foo\\' => ['Foo\\Some\\Entity', 'Foo\\Another\\Entity'], - ]); - }; - -.. _reference-validation-enabled: + // config/services.php + $container->setParameter('session.storage.options', [ + 'cache_limiter' => 0, + ]); -enabled -....... +Be aware that if you configure it, you'll have to set other session-related options +as parameters as well. -**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation +cookie_domain +............. -Whether or not to enable validation support. +**type**: ``string`` -This option will automatically be set to ``true`` when one of the child -settings is configured. +This determines the domain to set in the session cookie. -.. _reference-validation-enable_annotations: +If not set, ``php.ini``'s `session.cookie_domain`_ directive will be relied on. -enable_attributes -................. +cookie_httponly +............... **type**: ``boolean`` **default**: ``true`` -If this option is enabled, validation constraints can be defined using `PHP attributes`_. +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 :ref:`XSS attacks `. -translation_domain -.................. +cookie_lifetime +............... -**type**: ``string | false`` **default**: ``validators`` +**type**: ``integer`` -The translation domain that is used when translating validation constraint -error messages. Use false to disable translations. +This determines the lifetime of the session - in seconds. +Setting this value to ``0`` means the cookie is valid for +the length of the browser session. -.. _reference-validation-not-compromised-password: +If not set, ``php.ini``'s `session.cookie_lifetime`_ directive will be relied on. -not_compromised_password -........................ +cookie_path +........... -The :doc:`NotCompromisedPassword ` -constraint makes HTTP requests to a public API to check if the given password -has been compromised in a data breach. +**type**: ``string`` -.. _reference-validation-not-compromised-password-enabled: +This determines the path to set in the session cookie. -enabled -""""""" +If not set, ``php.ini``'s `session.cookie_path`_ directive will be relied on. -**type**: ``boolean`` **default**: ``true`` +cookie_samesite +............... -If you set this option to ``false``, no HTTP requests will be made and the given -password will be considered valid. This is useful when you don't want or can't -make HTTP requests, such as in ``dev`` and ``test`` environments or in -continuous integration servers. +**type**: ``string`` or ``null`` **default**: ``null`` -endpoint -"""""""" +It controls the way cookies are sent when the HTTP request did not originate +from the same domain that is associated with the cookies. Setting this option is +recommended to mitigate `CSRF security attacks`_. -**type**: ``string`` **default**: ``null`` +By default, browsers send all cookies related to the domain of the HTTP request. +This may be a problem for example when you visit a forum and some malicious +comment includes a link like ``https://some-bank.com/?send_money_to=attacker&amount=1000``. +If you were previously logged into your bank website, the browser will send all +those cookies when making that HTTP request. -By default, the :doc:`NotCompromisedPassword ` -constraint uses the public API provided by `haveibeenpwned.com`_. This option -allows to define a different, but compatible, API endpoint to make the password -checks. It's useful for example when the Symfony application is run in an -intranet without public access to the internet. +The possible values for this option are: + +* ``null``, use ``php.ini``'s `session.cookie_samesite`_ directive. +* ``'none'`` (or the ``Symfony\Component\HttpFoundation\Cookie::SAMESITE_NONE`` constant), use it to allow + sending of cookies when the HTTP request originated from a different domain + (previously this was the default behavior of null, but in newer browsers ``'lax'`` + would be applied when the header has not been set) +* ``'strict'`` (or the ``Cookie::SAMESITE_STRICT`` constant), use it to never + send any cookie when the HTTP request did not originate from the same domain. +* ``'lax'`` (or the ``Cookie::SAMESITE_LAX`` constant), use it to allow sending + cookies when the request originated from a different domain, but only when the + user consciously made the request (by clicking a link or submitting a form + with the ``GET`` method). -static_method +cookie_secure ............. -**type**: ``string | array`` **default**: ``['loadValidatorMetadata']`` - -Defines the name of the static method which is called to load the validation -metadata of the class. You can define an array of strings with the names of -several methods. In that case, all of them will be called in that order to load -the metadata. - -.. _reference-validation-email_validation_mode: - -email_validation_mode -..................... +**type**: ``boolean`` or ``'auto'`` -**type**: ``string`` **default**: ``html5`` +This determines whether cookies should only be sent over secure connections. In +addition to ``true`` and ``false``, there's a special ``'auto'`` value that +means ``true`` for HTTPS requests and ``false`` for HTTP requests. -Sets the default value for the -:ref:`"mode" option of the Email validator `. +If not set, ``php.ini``'s `session.cookie_secure`_ directive will be relied on. -.. _reference-validation-mapping: +.. _reference-session-enabled: -mapping +enabled ....... -.. _reference-validation-mapping-paths: - -paths -""""" - -**type**: ``array`` **default**: ``['config/validation/']`` +**type**: ``boolean`` **default**: ``true`` -This option allows to define an array of paths with files or directories where -the component will look for additional validation files: +Whether to enable the session support in the framework. .. configuration-block:: @@ -2833,10 +3003,8 @@ the component will look for additional validation files: # config/packages/framework.yaml framework: - validation: - mapping: - paths: - - "%kernel.project_dir%/config/validation/" + session: + enabled: true .. code-block:: xml @@ -2850,11 +3018,7 @@ the component will look for additional validation files: http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> - - - %kernel.project_dir%/config/validation/ - - + @@ -2864,152 +3028,163 @@ the component will look for additional validation files: use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->validation() - ->mapping() - ->paths(['%kernel.project_dir%/config/validation/']); + $framework->session() + ->enabled(true); }; -annotations -~~~~~~~~~~~ - -.. _reference-annotations-cache: - -cache -..... +gc_divisor +.......... -**type**: ``string`` **default**: ``php_array`` +**type**: ``integer`` -This option can be one of the following values: +See `gc_probability`_. -php_array - Use a PHP array to cache annotations in memory -file - Use the filesystem to cache annotations -none - Disable the caching of annotations +If not set, ``php.ini``'s `session.gc_divisor`_ directive will be relied on. -file_cache_dir +gc_maxlifetime .............. -**type**: ``string`` **default**: ``%kernel.cache_dir%/annotations`` - -The directory to store cache files for annotations, in case -``annotations.cache`` is set to ``'file'``. - -debug -..... - -**type**: ``boolean`` **default**: ``%kernel.debug%`` - -Whether to enable debug mode for caching. If enabled, the cache will -automatically update when the original file is changed (both with code and -annotation changes). For performance reasons, it is recommended to disable -debug mode in production, which will happen automatically if you use the -default value. - -.. _configuration-framework-serializer: - -serializer -~~~~~~~~~~ - -.. _reference-serializer-enabled: +**type**: ``integer`` -enabled -....... +This determines the number of seconds after which data will be seen as "garbage" +and potentially cleaned up. Garbage collection may occur during session +start and depends on `gc_divisor`_ and `gc_probability`_. -**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation +If not set, ``php.ini``'s `session.gc_maxlifetime`_ directive will be relied on. -Whether to enable the ``serializer`` service or not in the service container. +gc_probability +.............. -.. _reference-serializer-enable_annotations: +**type**: ``integer`` -enable_attributes -................. +This defines the probability that the garbage collector (GC) process is +started on every session initialization. The probability is calculated by +using ``gc_probability`` / ``gc_divisor``, e.g. 1/100 means there is a 1% +chance that the GC process will start on each request. -**type**: ``boolean`` **default**: ``true`` +If not set, Symfony will use the value of the `session.gc_probability`_ directive +in the ``php.ini`` configuration file. -Enables support for `PHP attributes`_ in the serializer component. +.. versionadded:: 7.2 -.. seealso:: + Relying on ``php.ini``'s directive as default for ``gc_probability`` was + introduced in Symfony 7.2. - See :ref:`the reference ` for a list of supported annotations. +.. _config-framework-session-handler-id: -.. _reference-serializer-name_converter: +handler_id +.......... -name_converter -.............. +**type**: ``string`` | ``null`` **default**: ``null`` -**type**: ``string`` +If ``framework.session.save_path`` is not set, the default value of this option +is ``null``, which means to use the session handler configured in php.ini. If the +``framework.session.save_path`` option is set, then Symfony stores sessions using +the native file session handler. -The name converter to use. -The :class:`Symfony\\Component\\Serializer\\NameConverter\\CamelCaseToSnakeCaseNameConverter` -name converter can enabled by using the ``serializer.name_converter.camel_case_to_snake_case`` -value. +It is possible to :ref:`store sessions in a database `, +and also to configure the session handler with a DSN: -.. seealso:: +.. configuration-block:: - For more information, see :ref:`serializer-name-conversion`. + .. code-block:: yaml -.. _reference-serializer-circular_reference_handler: + # config/packages/framework.yaml + framework: + session: + # a few possible examples + handler_id: 'redis://localhost' + handler_id: '%env(REDIS_URL)%' + handler_id: '%env(DATABASE_URL)%' + handler_id: 'file://%kernel.project_dir%/var/sessions' -circular_reference_handler -.......................... + .. code-block:: xml -**type** ``string`` + + + + + + + + -The service id that is used as the circular reference handler of the default -serializer. The service has to implement the magic ``__invoke($object)`` -method. + .. code-block:: php -.. seealso:: + // config/packages/framework.php + use function Symfony\Component\DependencyInjection\Loader\Configurator\env; + use Symfony\Config\FrameworkConfig; - For more information, see - :ref:`component-serializer-handling-circular-references`. + return static function (FrameworkConfig $framework): void { + // ... -.. _reference-serializer-mapping: + $framework->session() + // a few possible examples + ->handlerId('redis://localhost') + ->handlerId(env('REDIS_URL')) + ->handlerId(env('DATABASE_URL')) + ->handlerId('file://%kernel.project_dir%/var/sessions'); + }; -mapping -....... +.. note:: -.. _reference-serializer-mapping-paths: + Supported DSN protocols are the following: -paths -""""" + * ``file`` + * ``redis`` + * ``rediss`` (Redis over TLS) + * ``memcached`` (requires :doc:`symfony/cache `) + * ``pdo_oci`` (requires :doc:`doctrine/dbal `) + * ``mssql`` + * ``mysql`` + * ``mysql2`` + * ``pgsql`` + * ``postgres`` + * ``postgresql`` + * ``sqlsrv`` + * ``sqlite`` + * ``sqlite3`` -**type**: ``array`` **default**: ``[]`` +.. _reference-session-metadata-update-threshold: -This option allows to define an array of paths with files or directories where -the component will look for additional serialization files. +metadata_update_threshold +......................... -default_context -............... +**type**: ``integer`` **default**: ``0`` -**type**: ``array`` **default**: ``[]`` +This is how many seconds to wait between updating/writing the session metadata. +This can be useful if, for some reason, you want to limit the frequency at which +the session persists, instead of doing that on every request. -A map with default context options that will be used with each ``serialize`` and ``deserialize`` -call. This can be used for example to set the json encoding behavior by setting ``json_encode_options`` -to a `json_encode flags bitmask`_. +.. _name: -You can inspect the :ref:`serializer context builders ` -to discover the available settings. +name +.... -php_errors -~~~~~~~~~~ +**type**: ``string`` -log -... +This specifies the name of the session cookie. -**type**: ``boolean`` | ``int`` | ``array`` **default**: ``true`` +If not set, ``php.ini``'s `session.name`_ directive will be relied on. -Use the application logger instead of the PHP logger for logging PHP errors. -When an integer value is used, it defines a bitmask of PHP errors that will -be logged. Those integer values must be the same used in the -`error_reporting PHP option`_. The default log levels will be used for each -PHP error. -When a boolean value is used, ``true`` enables logging for all PHP errors -while ``false`` disables logging entirely. +save_path +......... -This option also accepts a map of PHP errors to log levels: +**type**: ``string`` | ``null`` **default**: ``%kernel.cache_dir%/sessions`` + +This determines the argument to be passed to the save handler. If you choose +the default file handler, this is the path where the session files are created. + +If ``null``, ``php.ini``'s `session.save_path`_ directive will be relied on: .. configuration-block:: @@ -3017,23 +3192,8 @@ This option also accepts a map of PHP errors to log levels: # config/packages/framework.yaml framework: - php_errors: - log: - !php/const \E_DEPRECATED: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_USER_DEPRECATED: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_NOTICE: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_USER_NOTICE: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_STRICT: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_WARNING: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_USER_WARNING: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_COMPILE_WARNING: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_CORE_WARNING: !php/const Psr\Log\LogLevel::ERROR - !php/const \E_USER_ERROR: !php/const Psr\Log\LogLevel::CRITICAL - !php/const \E_RECOVERABLE_ERROR: !php/const Psr\Log\LogLevel::CRITICAL - !php/const \E_COMPILE_ERROR: !php/const Psr\Log\LogLevel::CRITICAL - !php/const \E_PARSE: !php/const Psr\Log\LogLevel::CRITICAL - !php/const \E_ERROR: !php/const Psr\Log\LogLevel::CRITICAL - !php/const \E_CORE_ERROR: !php/const Psr\Log\LogLevel::CRITICAL + session: + save_path: ~ .. code-block:: xml @@ -3047,322 +3207,267 @@ This option also accepts a map of PHP errors to log levels: http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> - - - - + .. code-block:: php // config/packages/framework.php - use Psr\Log\LogLevel; use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->phpErrors()->log(\E_DEPRECATED, LogLevel::ERROR); - $framework->phpErrors()->log(\E_USER_DEPRECATED, LogLevel::ERROR); - // ... + $framework->session() + ->savePath(null); }; -throw -..... - -**type**: ``boolean`` **default**: ``%kernel.debug%`` - -Throw PHP errors as ``\ErrorException`` instances. The parameter -``debug.error_handler.throw_at`` controls the threshold. - -.. _reference-cache: - -cache -~~~~~ - -.. _reference-cache-app: - -app -... - -**type**: ``string`` **default**: ``cache.adapter.filesystem`` +sid_bits_per_character +...................... -The cache adapter used by the ``cache.app`` service. The FrameworkBundle -ships with multiple adapters: ``cache.adapter.apcu``, ``cache.adapter.system``, -``cache.adapter.filesystem``, ``cache.adapter.psr6``, ``cache.adapter.redis``, -``cache.adapter.memcached``, ``cache.adapter.pdo`` and -``cache.adapter.doctrine_dbal``. +**type**: ``integer`` -There's also a special adapter called ``cache.adapter.array`` which stores -contents in memory using a PHP array and it's used to disable caching (mostly on -the ``dev`` environment). +This determines the number of bits in the encoded session ID character. The possible +values are ``4`` (0-9, a-f), ``5`` (0-9, a-v), and ``6`` (0-9, a-z, A-Z, "-", ","). +The more bits results in stronger session ID. ``5`` is recommended value for +most environments. -.. tip:: +If not set, ``php.ini``'s `session.sid_bits_per_character`_ directive will be relied on. - It might be tough to understand at the beginning, so to avoid confusion - remember that all pools perform the same actions but on different medium - given the adapter they are based on. Internally, a pool wraps the definition - of an adapter. +.. deprecated:: 7.2 -.. _reference-cache-system: + The ``sid_bits_per_character`` option was deprecated in Symfony 7.2. No alternative + is provided as PHP 8.4 has deprecated the related option. -system -...... +sid_length +.......... -**type**: ``string`` **default**: ``cache.adapter.system`` +**type**: ``integer`` -The cache adapter used by the ``cache.system`` service. It supports the same -adapters available for the ``cache.app`` service. +This determines the length of session ID string, which can be an integer between +``22`` and ``256`` (both inclusive), ``32`` being the recommended value. Longer +session IDs are harder to guess. -directory -......... +If not set, ``php.ini``'s `session.sid_length`_ directive will be relied on. -**type**: ``string`` **default**: ``%kernel.cache_dir%/pools`` +.. deprecated:: 7.2 -The path to the cache directory used by services inheriting from the -``cache.adapter.filesystem`` adapter (including ``cache.app``). + The ``sid_length`` option was deprecated in Symfony 7.2. No alternative is + provided as PHP 8.4 has deprecated the related option. -default_doctrine_provider -......................... +.. _storage_id: -**type**: ``string`` +storage_factory_id +.................. -The service name to use as your default Doctrine provider. The provider is -available as the ``cache.default_doctrine_provider`` service. +**type**: ``string`` **default**: ``session.storage.factory.native`` -default_psr6_provider -..................... +The service ID used for creating the ``SessionStorageInterface`` that stores +the session. This service is available in the Symfony application via the +``session.storage.factory`` service alias. The class has to implement +:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\SessionStorageFactoryInterface`. +To see a list of all available storages, run: -**type**: ``string`` +.. code-block:: terminal -The service name to use as your default PSR-6 provider. It is available as -the ``cache.default_psr6_provider`` service. + $ php bin/console debug:container session.storage.factory. -default_redis_provider -...................... +use_cookies +........... -**type**: ``string`` **default**: ``redis://localhost`` +**type**: ``boolean`` -The DSN to use by the Redis provider. The provider is available as the ``cache.default_redis_provider`` -service. +This specifies if the session ID is stored on the client side using cookies or +not. -default_memcached_provider -.......................... +If not set, ``php.ini``'s `session.use_cookies`_ directive will be relied on. -**type**: ``string`` **default**: ``memcached://localhost`` +ssi +~~~ -The DSN to use by the Memcached provider. The provider is available as the ``cache.default_memcached_provider`` -service. +enabled +....... -default_pdo_provider -.................... +**type**: ``boolean`` **default**: ``false`` -**type**: ``string`` **default**: ``doctrine.dbal.default_connection`` +Whether to enable or not SSI support in your application. -The service id of the database connection, which should be either a PDO or a -Doctrine DBAL instance. The provider is available as the ``cache.default_pdo_provider`` -service. +.. _reference-framework-test: -pools -..... +test +~~~~ -**type**: ``array`` +**type**: ``boolean`` -A list of cache pools to be created by the framework extension. +If this configuration setting is present (and not ``false``), then the services +related to testing your application (e.g. ``test.client``) are loaded. This +setting should be present in your ``test`` environment (usually via +``config/packages/test/framework.yaml``). .. seealso:: - For more information about how pools work, see :ref:`cache pools `. - -To configure a Redis cache pool with a default lifetime of 1 hour, do the following: - -.. configuration-block:: - - .. code-block:: yaml - - # config/packages/framework.yaml - framework: - cache: - pools: - cache.mycache: - adapter: cache.adapter.redis - default_lifetime: 3600 - - .. code-block:: xml - - - - + For more information, see :doc:`/testing`. - - - - - - - +translator +~~~~~~~~~~ - .. code-block:: php +cache_dir +......... - // config/packages/framework.php - use Symfony\Config\FrameworkConfig; +**type**: ``string`` | ``null`` **default**: ``%kernel.cache_dir%/translations`` - return static function (FrameworkConfig $framework): void { - $framework->cache() - ->pool('cache.mycache') - ->adapters(['cache.adapter.redis']) - ->defaultLifetime(3600); - }; +Defines the directory where the translation cache is stored. Use ``null`` to +disable this cache. -.. _reference-cache-pools-name: +.. _reference-translator-default_path: -name -"""" +default_path +............ -**type**: ``prototype`` +**type**: ``string`` **default**: ``%kernel.project_dir%/translations`` -Name of the pool you want to create. +This option allows to define the path where the application translations files +are stored. -.. note:: +.. _reference-translator-enabled: - Your pool name must differ from ``cache.app`` or ``cache.system``. +enabled +....... -adapter -""""""" +**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation -**type**: ``string`` **default**: ``cache.app`` +Whether or not to enable the ``translator`` service in the service container. -The service name of the adapter to use. You can specify one of the default -services that follow the pattern ``cache.adapter.[type]``. Alternatively you -can specify another cache pool as base, which will make this pool inherit the -settings from the base pool as defaults. +.. _fallback: -.. note:: +fallbacks +......... - Your service needs to implement the ``Psr\Cache\CacheItemPoolInterface`` interface. +**type**: ``string|array`` **default**: value of `default_locale`_ -public -"""""" +This option is used when the translation key for the current locale wasn't +found. -**type**: ``boolean`` **default**: ``false`` +.. seealso:: -Whether your service should be public or not. + For more details, see :doc:`/translation`. -tags -"""" +.. _reference-framework-translator-formatter: -**type**: ``boolean`` | ``string`` **default**: ``null`` +formatter +......... -Whether your service should be able to handle tags or not. -Can also be the service id of another cache pool where tags will be stored. +**type**: ``string`` **default**: ``translator.formatter.default`` -default_lifetime -"""""""""""""""" +The ID of the service used to format translation messages. The service class +must implement the :class:`Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface`. -**type**: ``integer`` | ``string`` +.. _reference-framework-translator-logging: -Default lifetime of your cache items. Give an integer value to set the default -lifetime in seconds. A string value could be ISO 8601 time interval, like ``"PT5M"`` -or a PHP date expression that is accepted by ``strtotime()``, like ``"5 minutes"``. +logging +....... -If no value is provided, the cache adapter will fallback to the default value on -the actual cache storage. +**default**: ``true`` when the debug mode is enabled, ``false`` otherwise. -provider -"""""""" +When ``true``, a log entry is made whenever the translator cannot find a translation +for a given key. The logs are made to the ``translation`` channel at the +``debug`` level for keys where there is a translation in the fallback +locale, and the ``warning`` level if there is no translation to use at all. -**type**: ``string`` +.. _reference-translator-paths: -Overwrite the default service name or DSN respectively, if you do not want to -use what is configured as ``default_X_provider`` under ``cache``. See the -description of the default provider setting above for information on how to -specify your specific provider. +paths +..... -clearer -""""""" +**type**: ``array`` **default**: ``[]`` -**type**: ``string`` +This option allows to define an array of paths where the component will look +for translation files. The later a path is added, the more priority it has +(translations from later paths overwrite earlier ones). Translations from the +:ref:`default_path ` have more priority than +translations from all these paths. -The cache clearer used to clear your PSR-6 cache. +.. _reference-translator-providers: -.. seealso:: +providers +......... - For more information, see :class:`Symfony\\Component\\HttpKernel\\CacheClearer\\Psr6CacheClearer`. +**type**: ``array`` **default**: ``[]`` -.. _reference-cache-prefix-seed: +This option enables and configures :ref:`translation providers ` +to push and pull your translations to/from third party translation services. -prefix_seed -........... +trust_x_sendfile_type_header +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -**type**: ``string`` **default**: ``_%kernel.project_dir%.%kernel.container_class%`` +**type**: ``boolean`` **default**: ``%env(bool:default::SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER)%`` -This value is used as part of the "namespace" generated for the -cache item keys. A common practice is to use the unique name of the application -(e.g. ``symfony.com``) because that prevents naming collisions when deploying -multiple applications into the same path (on different servers) that share the -same cache backend. +.. versionadded:: 7.2 -It's also useful when using `blue/green deployment`_ strategies and more -generally, when you need to abstract out the actual deployment directory (for -example, when warming caches offline). + In Symfony 7.2, the default value of this option was changed from ``false`` to the + value stored in the ``SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER`` environment variable. -.. note:: +``X-Sendfile`` is a special HTTP header that tells web servers to replace the +response contents by the file that is defined in that header. This improves +performance because files are no longer served by your application but directly +by the web server. - The ``prefix_seed`` option is used at compile time. This means - that any change made to this value after container's compilation - will have no effect. +This configuration option determines whether to trust ``x-sendfile`` header for +BinaryFileResponse. If enabled, Symfony calls the +:method:`BinaryFileResponse::trustXSendfileTypeHeader ` +method automatically. It becomes the service container parameter named +``kernel.trust_x_sendfile_type_header``. -.. _reference-lock: +.. _reference-framework-trusted-headers: -lock -~~~~ +trusted_headers +~~~~~~~~~~~~~~~ -**type**: ``string`` | ``array`` +The ``trusted_headers`` option is needed to configure which client information +should be trusted (e.g. their host) when running Symfony behind a load balancer +or a reverse proxy. See :doc:`/deployment/proxies`. -The default lock adapter. If not defined, the value is set to ``semaphore`` when -available, or to ``flock`` otherwise. Store's DSN are also allowed. +.. _configuration-framework-trusted-hosts: -.. _reference-lock-enabled: +trusted_hosts +~~~~~~~~~~~~~ -enabled -....... +**type**: ``array`` | ``string`` **default**: ``['%env(default::SYMFONY_TRUSTED_HOSTS)%']`` -**type**: ``boolean`` **default**: ``true`` +.. versionadded:: 7.2 -Whether to enable the support for lock or not. This setting is -automatically set to ``true`` when one of the child settings is configured. + In Symfony 7.2, the default value of this option was changed from ``[]`` to the + value stored in the ``SYMFONY_TRUSTED_HOSTS`` environment variable. -.. _reference-lock-resources: +A lot of different attacks have been discovered relying on inconsistencies +in handling the ``Host`` header by various software (web servers, reverse +proxies, web frameworks, etc.). Basically, every time the framework is +generating an absolute URL (when sending an email to reset a password for +instance), the host might have been manipulated by an attacker. -resources -......... +.. seealso:: -**type**: ``array`` + You can read `HTTP Host header attacks`_ for more information about + these kinds of attacks. -A map of lock stores to be created by the framework extension, with -the name as key and DSN as value: +The Symfony :method:`Request::getHost() ` +method might be vulnerable to some of these attacks because it depends on +the configuration of your web server. One simple solution to avoid these +attacks is to configure a list of hosts that your Symfony application can respond +to. That's the purpose of this ``trusted_hosts`` option. If the incoming +request's hostname doesn't match one of the regular expressions in this list, +the application won't respond and the user will receive a 400 response. .. configuration-block:: .. code-block:: yaml - # config/packages/lock.yaml + # config/packages/framework.yaml framework: - lock: '%env(LOCK_DSN)%' + trusted_hosts: ['^example\.com$', '^example\.org$'] .. code-block:: xml - + - - %env(LOCK_DSN)% - + ^example\.com$ + ^example\.org$ + .. code-block:: php - // config/packages/lock.php + // config/packages/framework.php use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->lock() - ->resource('default', [env('LOCK_DSN')]); + $framework->trustedHosts(['^example\.com$', '^example\.org$']); }; -.. seealso:: - - For more details, see :doc:`/lock`. - -.. _reference-lock-resources-name: +Hosts can also be configured to respond to any subdomain, via +``^(.+\.)?example\.com$`` for instance. -name -"""" +In addition, you can also set the trusted hosts in the front controller +using the ``Request::setTrustedHosts()`` method:: -**type**: ``prototype`` + // public/index.php + Request::setTrustedHosts(['^(.+\.)?example\.com$', '^(.+\.)?example\.org$']); -Name of the lock you want to create. +The default value for this option is an empty array, meaning that the application +can respond to any given host. -semaphore -~~~~~~~~~ +.. seealso:: -**type**: ``string`` | ``array`` + Read more about this in the `Security Advisory Blog post`_. -The default semaphore adapter. Store's DSN are also allowed. +.. _reference-framework-trusted-proxies: -.. _reference-semaphore-enabled: +trusted_proxies +~~~~~~~~~~~~~~~ -enabled -....... +The ``trusted_proxies`` option is needed to get precise information about the +client (e.g. their IP address) when running Symfony behind a load balancer or a +reverse proxy. See :doc:`/deployment/proxies`. -**type**: ``boolean`` **default**: ``true`` +.. _reference-validation: -Whether to enable the support for semaphore or not. This setting is -automatically set to ``true`` when one of the child settings is configured. +validation +~~~~~~~~~~ -.. _reference-semaphore-resources: +.. _reference-validation-auto-mapping: -resources -......... +auto_mapping +............ -**type**: ``array`` +**type**: ``array`` **default**: ``[]`` -A map of semaphore stores to be created by the framework extension, with -the name as key and DSN as value: +Defines the Doctrine entities that will be introspected to add +:ref:`automatic validation constraints ` to them: .. configuration-block:: .. code-block:: yaml - # config/packages/semaphore.yaml framework: - semaphore: '%env(SEMAPHORE_DSN)%' + validation: + auto_mapping: + # an empty array means that all entities that belong to that + # namespace will add automatic validation + 'App\Entity\': [] + 'Foo\': ['Foo\Some\Entity', 'Foo\Another\Entity'] .. code-block:: xml - + - - %env(SEMAPHORE_DSN)% - + + + + + Foo\Some\Entity + Foo\Another\Entity + + .. code-block:: php - // config/packages/semaphore.php + // config/packages/framework.php use Symfony\Config\FrameworkConfig; return static function (FrameworkConfig $framework): void { - $framework->semaphore() - ->resource('default', ['%env(SEMAPHORE_DSN)%']); + $framework->validation() + ->autoMapping() + ->paths([ + 'App\\Entity\\' => [], + 'Foo\\' => ['Foo\\Some\\Entity', 'Foo\\Another\\Entity'], + ]); }; -.. _reference-semaphore-resources-name: - -name -"""" - -**type**: ``prototype`` - -Name of the semaphore you want to create. +.. _reference-validation-email_validation_mode: -mailer -~~~~~~ +email_validation_mode +..................... -.. _mailer-dsn: +**type**: ``string`` **default**: ``html5`` -dsn -... +Sets the default value for the +:ref:`"mode" option of the Email validator `. -**type**: ``string`` **default**: ``null`` +.. _reference-validation-enable_annotations: -The DSN used by the mailer. When several DSN may be used, use -``transports`` option (see below) instead. +enable_attributes +................. -transports -.......... +**type**: ``boolean`` **default**: ``true`` -**type**: ``array`` +If this option is enabled, validation constraints can be defined using `PHP attributes`_. -A :ref:`list of DSN ` that can be used by the -mailer. A transport name is the key and the dsn is the value. +.. _reference-validation-enabled: -message_bus -........... +enabled +....... -**type**: ``string`` **default**: ``null`` or default bus if Messenger component is installed +**type**: ``boolean`` **default**: ``true`` or ``false`` depending on your installation -Service identifier of the message bus to use when using the -:doc:`Messenger component ` (e.g. ``messenger.default_bus``). +Whether or not to enable validation support. -envelope -........ +This option will automatically be set to ``true`` when one of the child +settings is configured. -sender -"""""" +.. _reference-validation-mapping: -**type**: ``string`` +mapping +....... -The "envelope sender" which is used as the value of ``MAIL FROM`` during the -`SMTP session`_. This value overrides any other sender set in the code. +.. _reference-validation-mapping-paths: -recipients -"""""""""" +paths +""""" -**type**: ``array`` +**type**: ``array`` **default**: ``['config/validation/']`` -The "envelope recipient" which is used as the value of ``RCPT TO`` during the -the `SMTP session`_. This value overrides any other recipient set in the code. +This option allows to define an array of paths with files or directories where +the component will look for additional validation files: .. configuration-block:: .. code-block:: yaml - # config/packages/mailer.yaml + # config/packages/framework.yaml framework: - mailer: - dsn: 'smtp://localhost:25' - envelope: - recipients: ['admin@symfony.com', 'lead@symfony.com'] + validation: + mapping: + paths: + - "%kernel.project_dir%/config/validation/" .. code-block:: xml - + + - - - admin@symfony.com - lead@symfony.com - - + + + %kernel.project_dir%/config/validation/ + + .. code-block:: php - // config/packages/mailer.php - namespace Symfony\Component\DependencyInjection\Loader\Configurator; + // config/packages/framework.php + use Symfony\Config\FrameworkConfig; - return static function (ContainerConfigurator $container): void { - $container->extension('framework', [ - 'mailer' => [ - 'dsn' => 'smtp://localhost:25', - 'envelope' => [ - 'recipients' => [ - 'admin@symfony.com', - 'lead@symfony.com', - ], - ], - ], - ]); + return static function (FrameworkConfig $framework): void { + $framework->validation() + ->mapping() + ->paths(['%kernel.project_dir%/config/validation/']); }; -.. _mailer-headers: +.. _reference-validation-not-compromised-password: -headers -....... +not_compromised_password +........................ -**type**: ``array`` +The :doc:`NotCompromisedPassword ` +constraint makes HTTP requests to a public API to check if the given password +has been compromised in a data breach. -Headers to add to emails. The key (``name`` attribute in xml format) is the -header name and value the header value. +static_method +............. -.. seealso:: +**type**: ``string | array`` **default**: ``['loadValidatorMetadata']`` - For more information, see :ref:`Configuring Emails Globally ` +Defines the name of the static method which is called to load the validation +metadata of the class. You can define an array of strings with the names of +several methods. In that case, all of them will be called in that order to load +the metadata. -messenger -~~~~~~~~~ +translation_domain +.................. + +**type**: ``string | false`` **default**: ``validators`` + +The translation domain that is used when translating validation constraint +error messages. Use false to disable translations. + + +.. _reference-validation-not-compromised-password-enabled: enabled -....... +""""""" **type**: ``boolean`` **default**: ``true`` -Whether to enable or not Messenger. +If you set this option to ``false``, no HTTP requests will be made and the given +password will be considered valid. This is useful when you don't want or can't +make HTTP requests, such as in ``dev`` and ``test`` environments or in +continuous integration servers. -.. seealso:: +endpoint +"""""""" - For more details, see the :doc:`Messenger component ` - documentation. +**type**: ``string`` **default**: ``null`` + +By default, the :doc:`NotCompromisedPassword ` +constraint uses the public API provided by `haveibeenpwned.com`_. This option +allows to define a different, but compatible, API endpoint to make the password +checks. It's useful for example when the Symfony application is run in an +intranet without public access to the internet. web_link ~~~~~~~~ @@ -3770,125 +3890,6 @@ Defines the kind of workflow that is going to be created, which can be either a normal workflow or a state machine. Read :doc:`this article ` to know their differences. -.. _framework_exceptions: - -exceptions -~~~~~~~~~~ - -**type**: ``array`` - -Defines the :ref:`log level ` and HTTP status code applied to the -exceptions that match the given exception class: - -.. configuration-block:: - - .. code-block:: yaml - - # config/packages/exceptions.yaml - framework: - exceptions: - Symfony\Component\HttpKernel\Exception\BadRequestHttpException: - log_level: 'debug' - status_code: 422 - - .. code-block:: xml - - - - - - - - - - - - .. code-block:: php - - // config/packages/exceptions.php - use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; - use Symfony\Config\FrameworkConfig; - - return static function (FrameworkConfig $framework): void { - $framework->exception(BadRequestHttpException::class) - ->logLevel('debug') - ->statusCode(422) - ; - }; - -The order in which you configure exceptions is important because Symfony will -use the configuration of the first exception that matches ``instanceof``: - -.. code-block:: yaml - - # config/packages/exceptions.yaml - framework: - exceptions: - Exception: - log_level: 'debug' - status_code: 404 - # The following configuration will never be used because \RuntimeException extends \Exception - RuntimeException: - log_level: 'debug' - status_code: 422 - -You can map a status code and a set of headers to an exception thanks -to the ``#[WithHttpStatus]`` attribute on the exception class:: - - namespace App\Exception; - - use Symfony\Component\HttpKernel\Attribute\WithHttpStatus; - - #[WithHttpStatus(422, [ - 'Retry-After' => 10, - 'X-Custom-Header' => 'header-value', - ])] - class CustomException extends \Exception - { - } - -It is also possible to map a log level on a custom exception class using -the ``#[WithLogLevel]`` attribute:: - - namespace App\Exception; - - use Psr\Log\LogLevel; - use Symfony\Component\HttpKernel\Attribute\WithLogLevel; - - #[WithLogLevel(LogLevel::WARNING)] - class CustomException extends \Exception - { - } - -The attributes can also be added to interfaces directly:: - - namespace App\Exception; - - use Symfony\Component\HttpKernel\Attribute\WithHttpStatus; - - #[WithHttpStatus(422)] - interface CustomExceptionInterface - { - } - - class CustomException extends \Exception implements CustomExceptionInterface - { - } - -.. versionadded:: 7.1 - - Support to use ``#[WithHttpStatus]`` and ``#[WithLogLevel]`` attributes - on interfaces was introduced in Symfony 7.1. - .. _`HTTP Host header attacks`: https://www.skeletonscribe.net/2013/05/practical-http-host-header-attacks.html .. _`Security Advisory Blog post`: https://symfony.com/blog/security-releases-symfony-2-0-24-2-1-12-2-2-5-and-2-3-3-released#cve-2013-4752-request-gethost-poisoning .. _`phpstorm-url-handler`: https://github.com/sanduhrs/phpstorm-url-handler