diff --git a/.alexrc b/.alexrc
new file mode 100644
index 00000000000..168d412c177
--- /dev/null
+++ b/.alexrc
@@ -0,0 +1,16 @@
+{
+ "allow": [
+ "attack",
+ "attacks",
+ "bigger",
+ "color",
+ "colors",
+ "failure",
+ "hook",
+ "hooks",
+ "host-hostess",
+ "invalid",
+ "remain",
+ "special"
+ ]
+}
diff --git a/.doctor-rst.yaml b/.doctor-rst.yaml
index 04e1162c00a..dfb85021586 100644
--- a/.doctor-rst.yaml
+++ b/.doctor-rst.yaml
@@ -1,86 +1,123 @@
rules:
- no_inheritdoc: ~
+ american_english: ~
avoid_repetetive_words: ~
+ blank_line_after_anchor: ~
blank_line_after_directive: ~
- short_array_syntax: ~
- no_app_console: ~
- typo: ~
- replacement: ~
+ blank_line_before_directive: ~
composer_dev_option_not_at_the_end: ~
- yarn_dev_option_at_the_end: ~
- versionadded_directive_should_have_version: ~
+ correct_code_block_directive_based_on_the_content: ~
deprecated_directive_should_have_version: ~
- no_composer_req: ~
- no_php_open_tag_in_code_block_php_directive: ~
- no_blank_line_after_filepath_in_php_code_block: ~
- no_blank_line_after_filepath_in_yaml_code_block: ~
- no_blank_line_after_filepath_in_xml_code_block: ~
- no_blank_line_after_filepath_in_twig_code_block: ~
- php_prefix_before_bin_console: ~
- use_deprecated_directive_instead_of_versionadded: ~
- no_space_before_self_xml_closing_tag: ~
- no_explicit_use_of_code_block_php: ~
+ ensure_bash_prompt_before_composer_command: ~
+ ensure_class_constant: ~
+ ensure_correct_format_for_phpfunction: ~
+ ensure_exactly_one_space_before_directive_type: ~
+ ensure_exactly_one_space_between_link_definition_and_link: ~
+ ensure_explicit_nullable_types: ~
+ ensure_github_directive_start_with_prefix:
+ prefix: 'Symfony'
+ ensure_link_bottom: ~
+ ensure_link_definition_contains_valid_url: ~
ensure_order_of_code_blocks_in_configuration_block: ~
- american_english: ~
- valid_use_statements: ~
+ ensure_php_reference_syntax: ~
+ extend_abstract_controller: ~
+ # extension_xlf_instead_of_xliff: ~
+ forbidden_directives:
+ directives:
+ - '.. index::'
+ - directive: '.. caution::'
+ replacements: ['.. warning::', '.. danger::']
+ indention: ~
lowercase_as_in_use_statements: ~
- ordered_use_statements: ~
- no_namespace_after_use_statements: ~
- correct_code_block_directive_based_on_the_content: ~
max_blank_lines:
max: 2
+ max_colons: ~
+ no_app_console: ~
+ no_attribute_redundant_parenthesis: ~
+ no_blank_line_after_filepath_in_php_code_block: ~
+ no_blank_line_after_filepath_in_twig_code_block: ~
+ no_blank_line_after_filepath_in_xml_code_block: ~
+ no_blank_line_after_filepath_in_yaml_code_block: ~
+ no_brackets_in_method_directive: ~
+ no_broken_ref_directive: ~
+ no_composer_req: ~
+ no_directive_after_shorthand: ~
+ no_duplicate_use_statements: ~
+ no_empty_literals: ~
+ no_explicit_use_of_code_block_php: ~
+ no_footnotes: ~
+ no_inheritdoc: ~
+ no_merge_conflict: ~
+ no_namespace_after_use_statements: ~
+ no_php_open_tag_in_code_block_php_directive: ~
+ no_space_before_self_xml_closing_tag: ~
+ no_typographic_quotes: ~
+ non_static_phpunit_assertions: ~
+ only_backslashes_in_namespace_in_php_code_block: ~
+ only_backslashes_in_use_statements_in_php_code_block: ~
+ ordered_use_statements: ~
+ php_prefix_before_bin_console: ~
+ remove_trailing_whitespace: ~
replace_code_block_types: ~
+ replacement: ~
+ short_array_syntax: ~
+ space_between_label_and_link_in_doc: ~
+ space_between_label_and_link_in_ref: ~
+ string_replacement: ~
+ title_underline_length_must_match_title_length: ~
+ typo: ~
+ unused_links: ~
+ use_deprecated_directive_instead_of_versionadded: ~
+ use_named_constructor_without_new_keyword_rule: ~
use_https_xsd_urls: ~
- blank_line_before_directive: ~
- extension_xlf_instead_of_xliff: ~
valid_inline_highlighted_namespaces: ~
- indention: ~
- unused_links: ~
+ valid_use_statements: ~
+ versionadded_directive_should_have_version: ~
yaml_instead_of_yml_suffix: ~
- extend_abstract_controller: ~
-# no_app_bundle: ~
- # master
versionadded_directive_major_version:
- major_version: 5
+ major_version: 7
versionadded_directive_min_version:
- min_version: '5.0'
+ min_version: '7.0'
deprecated_directive_major_version:
- major_version: 5
+ major_version: 7
deprecated_directive_min_version:
- min_version: '5.0'
+ min_version: '7.0'
+
+exclude_rule_for_file:
+ - path: configuration/multiple_kernels.rst
+ rule_name: replacement
+ - path: page_creation.rst
+ rule_name: no_php_open_tag_in_code_block_php_directive
+ - path: frontend/create_ux_bundle.rst
+ rule_name: argument_variable_must_match_type
# do not report as violation
whitelist:
regex:
- - '/FOSUserBundle(.*)\.yml/'
- '/``.yml``/'
- '/(.*)\.orm\.yml/' # currently DoctrineBundle only supports .yml
lines:
- 'in config files, so the old ``app/config/config_dev.yml`` goes to'
- '#. The most important config file is ``app/config/services.yml``, which now is'
- - 'code in production without a proxy, it becomes trivially easy to abuse your'
- - '.. _`EasyDeployBundle`: https://github.com/EasyCorp/easy-deploy-bundle'
- 'The bin/console Command'
- - '# username is your full Gmail or Google Apps email address'
- '.. _`LDAP injection`: http://projects.webappsec.org/w/page/13246947/LDAP%20Injection'
- - '.. versionadded:: 0.21.0' # Encore
- - '.. versionadded:: 2.4.0' # SwiftMailer
- - '.. versionadded:: 1.26' # Twig
- - '.. versionadded:: 1.30' # Twig
- - '.. versionadded:: 1.2' # MakerBundle
- - '.. versionadded:: 1.11' # MakerBundle
- - '.. versionadded:: 1.3' # MakerBundle
- - '.. versionadded:: 1.8' # MakerBundle
- - '0 => 123' # assertion for var_dumper - components/var_dumper.rst
- - '1 => "foo"' # assertion for var_dumper - components/var_dumper.rst
+ - '.. versionadded:: 2.8.0' # Doctrine
+ - '.. versionadded:: 1.9.0' # Encore
+ - '.. versionadded:: 1.18' # Flex in setup/upgrade_minor.rst
+ - '.. versionadded:: 1.0.0' # Encore
+ - '.. versionadded:: 2.7.1' # Doctrine
- '123,' # assertion for var_dumper - components/var_dumper.rst
- '"foo",' # assertion for var_dumper - components/var_dumper.rst
- '$var .= "Because of this `\xE9` octet (\\xE9),\n";'
- - "`Deploying Symfony 4 Apps on Heroku`_."
- - ".. _`Deploying Symfony 4 Apps on Heroku`: https://devcenter.heroku.com/articles/deploying-symfony4"
- - "// 224, 165, 141, 224, 164, 164, 224, 165, 135])"
- '.. versionadded:: 0.2' # MercureBundle
+ - '.. versionadded:: 3.6' # MonologBundle
+ - '.. versionadded:: 3.8' # MonologBundle
+ - '.. versionadded:: 3.5' # Monolog
+ - '.. versionadded:: 3.0' # Doctrine ORM
+ - '.. _`a feature to test applications using Mercure`: https://github.com/symfony/panther#creating-isolated-browsers-to-test-apps-using-mercure-or-websocket'
+ - 'End to End Tests (E2E)'
+ - '.. versionadded:: 2.2.0' # Panther
+ - '* Inline code blocks use double-ticks (````like this````).'
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index d917bbee7ac..9eb5d91783b 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -1,11 +1,14 @@
+# GithubActions workflows
+/.github/workflows* @OskarStark
+
# Console
/console* @chalasr
/components/console* @chalasr
# Form
-/forms.rst @xabbuh
-/components/form* @xabbuh
-/reference/forms* @xabbuh
+/forms.rst @xabbuh @HeahDude
+/components/form* @xabbuh @HeahDude
+/reference/forms* @xabbuh @HeahDude
# PropertyInfo
/components/property_info* @dunglas
@@ -15,9 +18,9 @@
/components/security* @chalasr
# Validator
-/validation/*
-/components/validator* @xabbuh
-/reference/constraints* @xabbuh
+/validation/* @xabbuh @HeahDude
+/components/validator* @xabbuh @HeahDude
+/reference/constraints* @xabbuh @HeahDude
# Workflow
/workflow* @lyrixx
diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md
deleted file mode 100644
index 9a4e5a2cedc..00000000000
--- a/.github/CODE_OF_CONDUCT.md
+++ /dev/null
@@ -1,12 +0,0 @@
-Code of Conduct
-===============
-
-This project follows a [Code of Conduct][code_of_conduct] in order to ensure an
-open and welcoming environment. Please read the full text for understanding the
-accepted and unaccepted behavior.
-
-Please read also the [reporting guidelines][guidelines], in case you encountered
-or witnessed any misbehavior.
-
-[code_of_conduct]: https://symfony.com/doc/current/contributing/code_of_conduct/code_of_conduct.html
-[guidelines]: https://symfony.com/doc/current/contributing/code_of_conduct/reporting_guidelines.html
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index bc7d6a94182..f32043e4523 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,9 +1,9 @@
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
new file mode 100644
index 00000000000..3722546330d
--- /dev/null
+++ b/.github/workflows/ci.yaml
@@ -0,0 +1,145 @@
+name: CI
+
+on:
+ push:
+ branches-ignore:
+ - 'github-comments'
+ pull_request:
+ branches-ignore:
+ - 'github-comments'
+
+permissions:
+ contents: read
+
+jobs:
+ symfony-docs-builder-build:
+ name: Build (symfony-tools/docs-builder)
+
+ runs-on: ubuntu-latest
+
+ continue-on-error: true
+
+ steps:
+ - name: "Checkout"
+ uses: actions/checkout@v4
+
+ - name: "Set-up PHP"
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: 8.4
+ coverage: none
+
+ - name: Get composer cache directory
+ id: composercache
+ working-directory: _build
+ run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
+
+ - name: Cache dependencies
+ uses: actions/cache@v3
+ with:
+ path: ${{ steps.composercache.outputs.dir }}
+ key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
+ restore-keys: ${{ runner.os }}-composer-
+
+ - name: "Install dependencies"
+ working-directory: _build
+ run: composer install --prefer-dist --no-progress
+
+ - name: "Build the docs"
+ working-directory: _build
+ run: php build.php --disable-cache
+
+ doctor-rst:
+ name: Lint (DOCtor-RST)
+
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: "Checkout"
+ uses: actions/checkout@v4
+
+ - name: "Create cache dir"
+ run: mkdir .cache
+
+ - name: "Extract base branch name"
+ run: echo "branch=$(echo ${GITHUB_BASE_REF:=${GITHUB_REF##*/}})" >> $GITHUB_OUTPUT
+ id: extract_base_branch
+
+ - name: "Cache DOCtor-RST"
+ uses: actions/cache@v3
+ with:
+ path: .cache
+ key: ${{ runner.os }}-doctor-rst-${{ steps.extract_base_branch.outputs.branch }}
+
+ - name: "Run DOCtor-RST"
+ uses: docker://oskarstark/doctor-rst:1.69.1
+ with:
+ args: --short --error-format=github --cache-file=/github/workspace/.cache/doctor-rst.cache
+
+ symfony-code-block-checker:
+ name: Code Blocks
+
+ runs-on: ubuntu-latest
+
+ continue-on-error: true
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+ with:
+ path: 'docs'
+
+ - name: Set-up PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: 8.4
+ coverage: none
+
+ - name: Fetch branch from where the PR started
+ working-directory: docs
+ run: git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/*
+
+ - name: Find modified files
+ id: find-files
+ working-directory: docs
+ run: echo "files=$(git diff --name-only origin/${{ github.base_ref }} HEAD | grep ".rst" | tr '\n' ' ')" >> $GITHUB_OUTPUT
+
+ - name: Get composer cache directory
+ id: composercache
+ working-directory: docs/_build
+ run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
+
+ - name: Cache dependencies
+ if: ${{ steps.find-files.outputs.files }}
+ uses: actions/cache@v3
+ with:
+ path: ${{ steps.composercache.outputs.dir }}
+ key: ${{ runner.os }}-composer-codeBlocks-${{ hashFiles('_checker/composer.lock', '_sf_app/composer.lock') }}
+ restore-keys: ${{ runner.os }}-composer-codeBlocks-
+
+ - name: Install dependencies
+ if: ${{ steps.find-files.outputs.files }}
+ run: composer create-project symfony-tools/code-block-checker:@dev _checker
+
+ - name: Install test application
+ if: ${{ steps.find-files.outputs.files }}
+ run: |
+ git clone -b ${{ github.base_ref }} --depth 5 --single-branch https://github.com/symfony-tools/symfony-application.git _sf_app
+ cd _sf_app
+ composer update
+
+ - name: Generate baseline
+ if: ${{ steps.find-files.outputs.files }}
+ working-directory: docs
+ run: |
+ CURRENT=$(git rev-parse HEAD)
+ git checkout -m ${{ github.base_ref }}
+ ../_checker/code-block-checker.php verify:docs `pwd` ${{ steps.find-files.outputs.files }} --generate-baseline=baseline.json --symfony-application=`realpath ../_sf_app`
+ git checkout -m $CURRENT
+ cat baseline.json
+
+ - name: Verify examples
+ if: ${{ steps.find-files.outputs.files }}
+ working-directory: docs
+ run: |
+ ../_checker/code-block-checker.php verify:docs `pwd` ${{ steps.find-files.outputs.files }} --baseline=baseline.json --output-format=github --symfony-application=`realpath ../_sf_app`
diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml
deleted file mode 100644
index ada570e342c..00000000000
--- a/.github/workflows/lint.yaml
+++ /dev/null
@@ -1,12 +0,0 @@
-on: [push, pull_request]
-name: Lint
-jobs:
- doctor-rst:
- name: DOCtor-RST
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@master
- - name: DOCtor-RST
- uses: docker://oskarstark/doctor-rst
- with:
- args: --short
diff --git a/.gitignore b/.gitignore
index a5eb433eea3..b69047f69a1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,2 @@
-/_build/doctrees
-/_build/html
-*.pyc
+/_build/vendor
+/_build/output
diff --git a/.symfony.cloud.yaml b/.symfony.cloud.yaml
deleted file mode 100644
index faa3c24780e..00000000000
--- a/.symfony.cloud.yaml
+++ /dev/null
@@ -1,58 +0,0 @@
-# This file describes an application. You can have multiple applications
-# in the same project.
-
-# The name of this app. Must be unique within a project.
-name: symfonydocs
-
-# The toolstack used to build the application.
-type: "python:3.7"
-
-# The configuration of app when it is exposed to the web.
-web:
- # The public directory of the app, relative to its root.
- document_root: "/_build/html"
- index_files:
- - index.html
- whitelist:
- - \.html$
- - \.txt$
-
- # CSS and Javascript.
- - \.css$
- - \.js$
- - \.hbs$
-
- # image/* types.
- - \.gif$
- - \.png$
- - \.ico$
- - \.svgz?$
-
- # fonts types.
- - \.ttf$
- - \.eot$
- - \.woff$
- - \.otf$
-
- # robots.txt.
- - /robots\.txt$
-
-# The size of the persistent disk of the application (in MB).
-disk: 512
-
-# Build time dependencies.
-dependencies:
- python:
- virtualenv: 15.1.0
-
-# The hooks that will be performed when the package is deployed.
-hooks:
- build: |
- virtualenv .virtualenv
- . .virtualenv/bin/activate
- # SymfonyCloud currently sets PIP_USER=1.
- export PIP_USER=
- pip install pip==9.0.1 wheel==0.29.0
- pip install -r _build/.requirements.txt
- find .virtualenv -type f -name "*.rst" -delete
- make -C _build html
diff --git a/.symfony/routes.yaml b/.symfony/routes.yaml
deleted file mode 100644
index caf4875f732..00000000000
--- a/.symfony/routes.yaml
+++ /dev/null
@@ -1,11 +0,0 @@
-https://{default}/:
- cache:
- cookies:
- - '*'
- default_ttl: 0
- enabled: true
- headers:
- - Accept
- - Accept-Language
- type: upstream
- upstream: symfonydocs:http
diff --git a/.symfony/services.yaml b/.symfony/services.yaml
deleted file mode 100644
index ec9369f2b00..00000000000
--- a/.symfony/services.yaml
+++ /dev/null
@@ -1 +0,0 @@
-# Keeping this file empty to not deploy unused services.
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 8ed2088e6ee..00000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: python
-
-python: 2.7
-
-sudo: false
-cache:
- directories: [$HOME/.cache/pip]
-
-install: pip install -r _build/.requirements.txt
-
-script: make -C _build SPHINXOPTS=-nW html
-
-branches:
- except:
- - github-comments
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
deleted file mode 100644
index d211dd419d0..00000000000
--- a/CODE_OF_CONDUCT.md
+++ /dev/null
@@ -1,83 +0,0 @@
-Code of Conduct
-===============
-
-Our Pledge
-----------
-
-In the interest of fostering an open and welcoming environment, we as
-contributors and maintainers pledge to making participation in our project and
-our community a harassment-free experience for everyone, regardless of age, body
-size, disability, ethnic origin, gender identity and expression, level of
-experience, education, socio-economic status, nationality, personal appearance,
-religion, or sexual identity and orientation.
-
-Our Standards
--------------
-
-Examples of behavior that contributes to creating a positive environment
-include:
-
-* Using welcoming and inclusive language
-* Being respectful of differing viewpoints and experiences
-* Gracefully accepting constructive criticism
-* Focusing on what is best for the community
-* Showing empathy towards other community members
-
-Examples of unacceptable behavior by participants include:
-
-* The use of sexualized language or imagery and unwelcome sexual attention or
- advances
-* Trolling, insulting/derogatory comments, and personal or political attacks
-* Public or private harassment
-* Publishing others' private information, such as a physical or electronic
- address, without explicit permission
-* Other conduct which could reasonably be considered inappropriate in a
- professional setting
-
-Our Responsibilities
---------------------
-
-[CoC Active Response Ensurers, or CARE][1], are responsible for clarifying the
-standards of acceptable behavior and are expected to take appropriate and fair
-corrective action in response to any instances of unacceptable behavior.
-
-CARE team members have the right and responsibility to remove, edit, or reject
-comments, commits, code, wiki edits, issues, and other contributions that are
-not aligned to this Code of Conduct, or to ban temporarily or permanently any
-contributor for other behaviors that they deem inappropriate, threatening,
-offensive, or harmful.
-
-Scope
------
-
-This Code of Conduct applies both within project spaces and in public spaces
-when an individual is representing the project or its community. Examples of
-representing a project or community include using an official project e-mail
-address, posting via an official social media account, or acting as an appointed
-representative at an online or offline event. Representation of a project may be
-further defined and clarified by CARE team members.
-
-Enforcement
------------
-
-Instances of abusive, harassing, or otherwise unacceptable behavior
-[may be reported][2] by contacting the [CARE team members][1].
-All complaints will be reviewed and investigated and will result in a response
-that is deemed necessary and appropriate to the circumstances. The CARE team is
-obligated to maintain confidentiality with regard to the reporter of an
-incident. Further details of specific enforcement policies may be posted
-separately.
-
-CARE team members who do not follow or enforce the Code of Conduct in good
-faith may face temporary or permanent repercussions as determined by the
-[core team][3].
-
-Attribution
------------
-
-This Code of Conduct is adapted from the [Contributor Covenant version 1.4][4].
-
-[1]: https://symfony.com/doc/current/contributing/code_of_conduct/care_team.html
-[2]: https://symfony.com/doc/current/contributing/code_of_conduct/reporting_guidelines.html
-[3]: https://symfony.com/doc/current/contributing/code/core_team.html
-[4]: https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
diff --git a/Dockerfile b/Dockerfile
deleted file mode 100644
index c1e63debe91..00000000000
--- a/Dockerfile
+++ /dev/null
@@ -1,16 +0,0 @@
-FROM python:2-stretch as builder
-
-WORKDIR /www
-
-COPY ./_build/.requirements.txt _build/
-
-RUN pip install pip==9.0.1 wheel==0.29.0 \
- && pip install -r _build/.requirements.txt
-
-COPY . /www
-
-RUN make -C _build html
-
-FROM nginx:latest
-
-COPY --from=builder /www/_build/html /usr/share/nginx/html
diff --git a/LICENSE.md b/LICENSE.md
index 01524e6ec84..547ac103984 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -195,7 +195,7 @@ b. You may Distribute or Publicly Perform an Adaptation only under the terms of:
(i) this License; (ii) a later version of this License with the same License
Elements as this License; (iii) a Creative Commons jurisdiction license (either
this or a later license version) that contains the same License Elements as this
-License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
+License (e.g. Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
Compatible License. If you license the Adaptation under one of the licenses
mentioned in (iv), you must comply with the terms of that license. If you
license the Adaptation under the terms of any of the licenses mentioned in (i),
@@ -221,7 +221,7 @@ Collections, You must, unless a request has been made pursuant to Section 4(a),
keep intact all copyright notices for the Work and provide, reasonable to the
medium or means You are utilizing: (i) the name of the Original Author (or
pseudonym, if applicable) if supplied, and/or if the Original Author and/or
-Licensor designate another party or parties (e.g., a sponsor institute,
+Licensor designate another party or parties (e.g. a sponsor institute,
publishing entity, journal) for attribution ("Attribution Parties") in
Licensor's copyright notice, terms of service or by other reasonable means, the
name of such party or parties; (ii) the title of the Work if supplied; (iii) to
@@ -229,7 +229,7 @@ the extent reasonably practicable, the URI, if any, that Licensor specifies to
be associated with the Work, unless such URI does not refer to the copyright
notice or licensing information for the Work; and (iv) , consistent with Section
3(b), in the case of an Adaptation, a credit identifying the use of the Work in
-the Adaptation (e.g., "French translation of the Work by Original Author," or
+the Adaptation (e.g. "French translation of the Work by Original Author," or
"Screenplay based on original Work by Original Author"). The credit required by
this Section 4(c) may be implemented in any reasonable manner; provided,
however, that in the case of a Adaptation or Collection, at a minimum such
diff --git a/README.markdown b/README.markdown
deleted file mode 100644
index c1c1000be1a..00000000000
--- a/README.markdown
+++ /dev/null
@@ -1,38 +0,0 @@
-Symfony Documentation
-=====================
-
-This documentation is rendered online at https://symfony.com/doc/current/
-
-Contributing
-------------
-
-We love contributors! For more information on how you can contribute to the
-Symfony documentation, please read
-[Contributing to the Documentation](https://symfony.com/doc/current/contributing/documentation/overview.html)
-
-> **Note**
-> Unless you're documenting a feature that was introduced *after* Symfony 3.4
-> (e.g. in Symfony 4.2), all pull requests must be based off of the **3.4** branch,
-> **not** the master or older branches.
-
-SymfonyCloud
-------------
-
-Pull requests are automatically built by [SymfonyCloud](https://symfony.com/cloud).
-
-Docker
-------
-
-You can build the doc locally with these commands:
-
-```bash
-# build the image...
-$ docker build . -t symfony-docs
-
-# ...and start the local web server
-# (if it's already in use, change the '8080' port by any other port)
-$ docker run --rm -p 8080:80 symfony-docs
-```
-
-You can now read the docs at http://127.0.0.1:8080 (if you use a virtual
-machine, browse its IP instead of localhost; e.g. `http://192.168.99.100:8080`).
diff --git a/README.md b/README.md
new file mode 100644
index 00000000000..5c063058c02
--- /dev/null
+++ b/README.md
@@ -0,0 +1,56 @@
+
+
+
+
+
+ The official Symfony Documentation
+
+
+
+
+ Online version
+
+ |
+
+ Components
+
+ |
+
+ Screencasts
+
+
+
+Contributing
+------------
+
+We love contributors! For more information on how you can contribute, please read
+the [Symfony Docs Contributing Guide](https://symfony.com/doc/current/contributing/documentation/overview.html).
+
+> [!IMPORTANT]
+> Use `6.4` branch as the base of your pull requests, unless you are documenting a
+> feature that was introduced *after* Symfony 6.4 (e.g. in Symfony 7.2).
+
+Build Documentation Locally
+---------------------------
+
+This is not needed for contributing, but it's useful if you would like to debug some
+issue in the docs or if you want to read Symfony Documentation offline.
+
+```bash
+$ git clone git@github.com:symfony/symfony-docs.git
+
+$ cd symfony-docs/
+$ cd _build/
+
+$ composer install
+
+$ php build.php
+```
+
+After generating docs, serve them with the internal PHP server:
+
+```bash
+$ php -S localhost:8000 -t output/
+```
+
+Browse `http://localhost:8000` to read the docs.
diff --git a/_build/.requirements.txt b/_build/.requirements.txt
deleted file mode 100644
index 53c6c3ddff0..00000000000
--- a/_build/.requirements.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-alabaster==0.7.10
-Babel==2.4.0
-docutils==0.13.1
-imagesize==0.7.1
-Jinja2==2.10.1
-MarkupSafe==1.0
-Pygments==2.2.0
-pytz==2017.2
-requests==2.20.0
-six==1.10.0
-snowballstemmer==1.2.1
-Sphinx==1.3.6
-git+https://github.com/fabpot/sphinx-php.git@7312eccce9465640752e51373a480da700e02345#egg_name=sphinx-php
diff --git a/_build/Makefile b/_build/Makefile
deleted file mode 100644
index 25b660056fe..00000000000
--- a/_build/Makefile
+++ /dev/null
@@ -1,153 +0,0 @@
-# Makefile for Sphinx documentation
-#
-
-# You can set these variables from the command line.
-SPHINXOPTS =
-SPHINXBUILD = sphinx-build
-PAPER =
-BUILDDIR = .
-
-# Internal variables.
-PAPEROPT_a4 = -D latex_paper_size=a4
-PAPEROPT_letter = -D latex_paper_size=letter
-ALLSPHINXOPTS = -c $(BUILDDIR) -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) ../
-# the i18n builder cannot share the environment and doctrees with the others
-I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
-
-.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
-
-help:
- @echo "Please use \`make ' where is one of"
- @echo " html to make standalone HTML files"
- @echo " dirhtml to make HTML files named index.html in directories"
- @echo " singlehtml to make a single large HTML file"
- @echo " pickle to make pickle files"
- @echo " json to make JSON files"
- @echo " htmlhelp to make HTML files and a HTML help project"
- @echo " qthelp to make HTML files and a qthelp project"
- @echo " devhelp to make HTML files and a Devhelp project"
- @echo " epub to make an epub"
- @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
- @echo " latexpdf to make LaTeX files and run them through pdflatex"
- @echo " text to make text files"
- @echo " man to make manual pages"
- @echo " texinfo to make Texinfo files"
- @echo " info to make Texinfo files and run them through makeinfo"
- @echo " gettext to make PO message catalogs"
- @echo " changes to make an overview of all changed/added/deprecated items"
- @echo " linkcheck to check all external links for integrity"
- @echo " doctest to run all doctests embedded in the documentation (if enabled)"
-
-clean:
- -rm -rf $(BUILDDIR)/*
-
-html:
- $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
- @echo
- @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
-
-dirhtml:
- $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
- @echo
- @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
-
-singlehtml:
- $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
- @echo
- @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
-
-pickle:
- $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
- @echo
- @echo "Build finished; now you can process the pickle files."
-
-json:
- $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
- @echo
- @echo "Build finished; now you can process the JSON files."
-
-htmlhelp:
- $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
- @echo
- @echo "Build finished; now you can run HTML Help Workshop with the" \
- ".hhp project file in $(BUILDDIR)/htmlhelp."
-
-qthelp:
- $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
- @echo
- @echo "Build finished; now you can run "qcollectiongenerator" with the" \
- ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
- @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Symfony.qhcp"
- @echo "To view the help file:"
- @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Symfony.qhc"
-
-devhelp:
- $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
- @echo
- @echo "Build finished."
- @echo "To view the help file:"
- @echo "# mkdir -p $$HOME/.local/share/devhelp/Symfony"
- @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Symfony"
- @echo "# devhelp"
-
-epub:
- $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
- @echo
- @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
-
-latex:
- $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
- @echo
- @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
- @echo "Run \`make' in that directory to run these through (pdf)latex" \
- "(use \`make latexpdf' here to do that automatically)."
-
-latexpdf:
- $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
- @echo "Running LaTeX files through pdflatex..."
- $(MAKE) -C $(BUILDDIR)/latex all-pdf
- @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
-
-text:
- $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
- @echo
- @echo "Build finished. The text files are in $(BUILDDIR)/text."
-
-man:
- $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
- @echo
- @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
-
-texinfo:
- $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
- @echo
- @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
- @echo "Run \`make' in that directory to run these through makeinfo" \
- "(use \`make info' here to do that automatically)."
-
-info:
- $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
- @echo "Running Texinfo files through makeinfo..."
- make -C $(BUILDDIR)/texinfo info
- @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
-
-gettext:
- $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
- @echo
- @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
-
-changes:
- $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
- @echo
- @echo "The overview file is in $(BUILDDIR)/changes."
-
-linkcheck:
- $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
- @echo
- @echo "Link check complete; look for any errors in the above output " \
- "or in $(BUILDDIR)/linkcheck/output.txt."
-
-doctest:
- $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
- @echo "Testing of doctests in the sources finished, look at the " \
- "results in $(BUILDDIR)/doctest/output.txt."
diff --git a/_build/_themes/_exts/symfonycom/__init__.py b/_build/_themes/_exts/symfonycom/__init__.py
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/_build/_themes/_exts/symfonycom/sphinx/__init__.py b/_build/_themes/_exts/symfonycom/sphinx/__init__.py
deleted file mode 100644
index 426d79826d7..00000000000
--- a/_build/_themes/_exts/symfonycom/sphinx/__init__.py
+++ /dev/null
@@ -1,163 +0,0 @@
-from sphinx.highlighting import lexers, PygmentsBridge
-from pygments.style import Style
-from pygments.formatters import HtmlFormatter
-from pygments.token import Keyword, Name, Comment, String, Error, \
- Number, Operator, Generic, Whitespace, Punctuation, Other, Literal
-
-from sphinx.writers.html import HTMLTranslator
-from docutils import nodes
-from sphinx.locale import admonitionlabels, lazy_gettext
-
-customadmonitionlabels = admonitionlabels
-l_ = lazy_gettext
-customadmonitionlabels['best-practice'] = l_('Best Practice')
-
-def _getType(path):
- return path[:path.find('/')]
-
-def _isIndex(path):
- return 'index' in path
-
-class SensioHTMLTranslator(HTMLTranslator):
- def __init__(self, builder, *args, **kwds):
- HTMLTranslator.__init__(self, builder, *args, **kwds)
- builder.templates.environment.filters['get_type'] = _getType
- builder.templates.environment.tests['index'] = _isIndex
- self.highlightlinenothreshold = 0
-
- def visit_literal(self, node):
- self.body.append(self.starttag(node, 'code', '', CLASS='docutils literal notranslate'))
-
- def depart_literal(self, node):
- self.body.append('')
-
- def visit_admonition(self, node, name=''):
- self.body.append(self.starttag(node, 'div', CLASS=('admonition-wrapper')))
- self.body.append('')
- if name and name != 'seealso':
- node.insert(0, nodes.title(name, customadmonitionlabels[name]))
- self.set_first_last(node)
-
- def depart_admonition(self, node=None):
- self.body.append('
\n')
-
- def visit_sidebar(self, node):
- self.body.append(self.starttag(node, 'div', CLASS=('admonition-wrapper')))
- self.body.append('\n')
- self.in_sidebar = None
-
- # overriden to add a new highlight div around each block
- def visit_literal_block(self, node):
- if node.rawsource != node.astext():
- # most probably a parsed-literal block -- don't highlight
- return BaseTranslator.visit_literal_block(self, node)
- lang = self.highlightlang
- linenos = node.rawsource.count('\n') >= \
- self.highlightlinenothreshold - 1
- highlight_args = node.get('highlight_args', {})
- if node.has_key('language'):
- # code-block directives
- lang = node['language']
- highlight_args['force'] = True
- if node.has_key('linenos'):
- linenos = node['linenos']
- def warner(msg):
- self.builder.warn(msg, (self.builder.current_docname, node.line))
- highlighted = self.highlighter.highlight_block(
- node.rawsource, lang, warn=warner, linenos=linenos,
- **highlight_args)
- starttag = self.starttag(node, 'div', suffix='',
- CLASS='highlight-%s' % lang)
- self.body.append('' + starttag + highlighted + '
\n')
- raise nodes.SkipNode
-
-class SensioStyle(Style):
- background_color = "#000000"
- default_style = ""
-
- styles = {
- # No corresponding class for the following:
- #Text: "", # class: ''
- Whitespace: "underline #f8f8f8", # class: 'w'
- Error: "#a40000 border:#ef2929", # class: 'err'
- Other: "#ffffff", # class 'x'
-
- Comment: "italic #B729D9", # class: 'c'
- Comment.Single: "italic #B729D9", # class: 'c1'
- Comment.Multiline: "italic #B729D9", # class: 'cm'
- Comment.Preproc: "noitalic #aaa", # class: 'cp'
-
- Keyword: "#FF8400", # class: 'k'
- Keyword.Constant: "#FF8400", # class: 'kc'
- Keyword.Declaration: "#FF8400", # class: 'kd'
- Keyword.Namespace: "#FF8400", # class: 'kn'
- Keyword.Pseudo: "#FF8400", # class: 'kp'
- Keyword.Reserved: "#FF8400", # class: 'kr'
- Keyword.Type: "#FF8400", # class: 'kt'
-
- Operator: "#E0882F", # class: 'o'
- Operator.Word: "#E0882F", # class: 'ow' - like keywords
-
- Punctuation: "#999999", # class: 'p'
-
- # because special names such as Name.Class, Name.Function, etc.
- # are not recognized as such later in the parsing, we choose them
- # to look the same as ordinary variables.
- Name: "#ffffff", # class: 'n'
- Name.Attribute: "#ffffff", # class: 'na' - to be revised
- Name.Builtin: "#ffffff", # class: 'nb'
- Name.Builtin.Pseudo: "#3465a4", # class: 'bp'
- Name.Class: "#ffffff", # class: 'nc' - to be revised
- Name.Constant: "#ffffff", # class: 'no' - to be revised
- Name.Decorator: "#888", # class: 'nd' - to be revised
- Name.Entity: "#ce5c00", # class: 'ni'
- Name.Exception: "#cc0000", # class: 'ne'
- Name.Function: "#ffffff", # class: 'nf'
- Name.Property: "#ffffff", # class: 'py'
- Name.Label: "#f57900", # class: 'nl'
- Name.Namespace: "#ffffff", # class: 'nn' - to be revised
- Name.Other: "#ffffff", # class: 'nx'
- Name.Tag: "#cccccc", # class: 'nt' - like a keyword
- Name.Variable: "#ffffff", # class: 'nv' - to be revised
- Name.Variable.Class: "#ffffff", # class: 'vc' - to be revised
- Name.Variable.Global: "#ffffff", # class: 'vg' - to be revised
- Name.Variable.Instance: "#ffffff", # class: 'vi' - to be revised
-
- Number: "#1299DA", # class: 'm'
-
- Literal: "#ffffff", # class: 'l'
- Literal.Date: "#ffffff", # class: 'ld'
-
- String: "#56DB3A", # class: 's'
- String.Backtick: "#56DB3A", # class: 'sb'
- String.Char: "#56DB3A", # class: 'sc'
- String.Doc: "italic #B729D9", # class: 'sd' - like a comment
- String.Double: "#56DB3A", # class: 's2'
- String.Escape: "#56DB3A", # class: 'se'
- String.Heredoc: "#56DB3A", # class: 'sh'
- String.Interpol: "#56DB3A", # class: 'si'
- String.Other: "#56DB3A", # class: 'sx'
- String.Regex: "#56DB3A", # class: 'sr'
- String.Single: "#56DB3A", # class: 's1'
- String.Symbol: "#56DB3A", # class: 'ss'
-
- Generic: "#ffffff", # class: 'g'
- Generic.Deleted: "#a40000", # class: 'gd'
- Generic.Emph: "italic #ffffff", # class: 'ge'
- Generic.Error: "#ef2929", # class: 'gr'
- Generic.Heading: "#000080", # class: 'gh'
- Generic.Inserted: "#00A000", # class: 'gi'
- Generic.Output: "#888", # class: 'go'
- Generic.Prompt: "#745334", # class: 'gp'
- Generic.Strong: "bold #ffffff", # class: 'gs'
- Generic.Subheading: "bold #800080", # class: 'gu'
- Generic.Traceback: "bold #a40000", # class: 'gt'
- }
-
-def setup(app):
- app.set_translator('html', SensioHTMLTranslator)
diff --git a/_build/_themes/_exts/symfonycom/sphinx/lexer.py b/_build/_themes/_exts/symfonycom/sphinx/lexer.py
deleted file mode 100644
index f1e87066236..00000000000
--- a/_build/_themes/_exts/symfonycom/sphinx/lexer.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from pygments.lexer import RegexLexer, bygroups, using
-from pygments.token import *
-from pygments.lexers.shell import BashLexer, BatchLexer
-
-class TerminalLexer(RegexLexer):
- name = 'Terminal'
- aliases = ['terminal']
- filenames = []
-
- tokens = {
- 'root': [
- ('^\$', Generic.Prompt, 'bash-prompt'),
- ('^>', Generic.Prompt, 'dos-prompt'),
- ('^#.+$', Comment.Single),
- ('^.+$', Generic.Output),
- ],
- 'bash-prompt': [
- ('(.+)$', bygroups(using(BashLexer)), '#pop')
- ],
- 'dos-prompt': [
- ('(.+)$', bygroups(using(BatchLexer)), '#pop')
- ],
- }
diff --git a/_build/_themes/sphinx_rtd_theme/__init__.py b/_build/_themes/sphinx_rtd_theme/__init__.py
deleted file mode 100755
index dfa448a21a2..00000000000
--- a/_build/_themes/sphinx_rtd_theme/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Sphinx ReadTheDocs theme.
-
-From https://github.com/ryan-roemer/sphinx-bootstrap-theme.
-
-"""
-from os import path
-
-__version__ = '0.4.0'
-__version_full__ = __version__
-
-
-def get_html_theme_path():
- """Return list of HTML theme paths."""
- cur_dir = path.abspath(path.dirname(path.dirname(__file__)))
- return cur_dir
-
-# See http://www.sphinx-doc.org/en/stable/theming.html#distribute-your-theme-as-a-python-package
-def setup(app):
- app.add_html_theme('sphinx_rtd_theme', path.abspath(path.dirname(__file__)))
diff --git a/_build/_themes/sphinx_rtd_theme/breadcrumbs.html b/_build/_themes/sphinx_rtd_theme/breadcrumbs.html
deleted file mode 100755
index 31550d8b37a..00000000000
--- a/_build/_themes/sphinx_rtd_theme/breadcrumbs.html
+++ /dev/null
@@ -1,82 +0,0 @@
-{# Support for Sphinx 1.3+ page_source_suffix, but don't break old builds. #}
-
-{% if page_source_suffix %}
-{% set suffix = page_source_suffix %}
-{% else %}
-{% set suffix = source_suffix %}
-{% endif %}
-
-{% if meta is defined and meta is not none %}
-{% set check_meta = True %}
-{% else %}
-{% set check_meta = False %}
-{% endif %}
-
-{% if check_meta and 'github_url' in meta %}
-{% set display_github = True %}
-{% endif %}
-
-{% if check_meta and 'bitbucket_url' in meta %}
-{% set display_bitbucket = True %}
-{% endif %}
-
-{% if check_meta and 'gitlab_url' in meta %}
-{% set display_gitlab = True %}
-{% endif %}
-
-
-
-
-
- {% if (theme_prev_next_buttons_location == 'top' or theme_prev_next_buttons_location == 'both') and (next or prev) %}
-
- {% endif %}
-
-
diff --git a/_build/_themes/sphinx_rtd_theme/footer.html b/_build/_themes/sphinx_rtd_theme/footer.html
deleted file mode 100755
index 448d1457558..00000000000
--- a/_build/_themes/sphinx_rtd_theme/footer.html
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
diff --git a/_build/_themes/sphinx_rtd_theme/layout.html b/_build/_themes/sphinx_rtd_theme/layout.html
deleted file mode 100755
index 82950a20243..00000000000
--- a/_build/_themes/sphinx_rtd_theme/layout.html
+++ /dev/null
@@ -1,219 +0,0 @@
-{# TEMPLATE VAR SETTINGS #}
-{%- set url_root = pathto('', 1) %}
-{%- if url_root == '#' %}{% set url_root = '' %}{% endif %}
-{%- if not embedded and docstitle %}
- {%- set titlesuffix = " — "|safe + docstitle|e %}
-{%- else %}
- {%- set titlesuffix = "" %}
-{%- endif %}
-{%- set lang_attr = 'en' if language == None else (language | replace('_', '-')) %}
-
-
-
-
-
-
- {{ metatags }}
-
- {% block htmltitle %}
- {{ title|striptags|e }}{{ titlesuffix }}
- {% endblock %}
-
- {# FAVICON #}
- {% if favicon %}
-
- {% endif %}
- {# CANONICAL URL #}
- {% if theme_canonical_url %}
-
- {% endif %}
-
- {# CSS #}
-
- {# OPENSEARCH #}
- {% if not embedded %}
- {% if use_opensearch %}
-
- {% endif %}
-
- {% endif %}
-
-
-
- {%- for css in css_files %}
- {%- if css|attr("rel") %}
-
- {%- else %}
-
- {%- endif %}
- {%- endfor %}
- {%- for cssfile in extra_css_files %}
-
- {%- endfor %}
-
- {%- block linktags %}
- {%- if hasdoc('about') %}
-
- {%- endif %}
- {%- if hasdoc('genindex') %}
-
- {%- endif %}
- {%- if hasdoc('search') %}
-
- {%- endif %}
- {%- if hasdoc('copyright') %}
-
- {%- endif %}
- {%- if next %}
-
- {%- endif %}
- {%- if prev %}
-
- {%- endif %}
- {%- endblock %}
- {%- block extrahead %} {% endblock %}
-
- {# Keep modernizr in head - http://modernizr.com/docs/#installing #}
-
-
-
-
-
-
- {% block extrabody %} {% endblock %}
-
-
- {# SIDE NAV, TOGGLES ON MOBILE #}
-
-
-
-
-
-
- {# MOBILE NAV, TRIGGLES SIDE NAV ON TOGGLE #}
-
- {% block mobile_nav %}
-
- {{ project }}
- {% endblock %}
-
-
-
-
- {%- block content %}
- {% if theme_style_external_links|tobool %}
-
- {% else %}
-
- {% endif %}
- {% include "breadcrumbs.html" %}
-
- {%- block document %}
-
- {% block body %}{% endblock %}
-
- {% if self.comments()|trim %}
-
- {% block comments %}{% endblock %}
-
- {% endif%}
-
- {%- endblock %}
- {% include "footer.html" %}
-
- {%- endblock %}
-
-
-
-
-
- {% include "versions.html" %}
-
- {% if not embedded %}
-
-
- {%- for scriptfile in script_files %}
-
- {%- endfor %}
-
- {% endif %}
-
-
-
-
-
- {%- block footer %} {% endblock %}
-
-
-
diff --git a/_build/_themes/sphinx_rtd_theme/search.html b/_build/_themes/sphinx_rtd_theme/search.html
deleted file mode 100755
index e3aa9b5c6e7..00000000000
--- a/_build/_themes/sphinx_rtd_theme/search.html
+++ /dev/null
@@ -1,50 +0,0 @@
-{#
- basic/search.html
- ~~~~~~~~~~~~~~~~~
-
- Template for the search page.
-
- :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-#}
-{%- extends "layout.html" %}
-{% set title = _('Search') %}
-{% set script_files = script_files + ['_static/searchtools.js'] %}
-{% block footer %}
-
- {# this is used when loading the search index using $.ajax fails,
- such as on Chrome for documents on localhost #}
-
- {{ super() }}
-{% endblock %}
-{% block body %}
-
-
-
- {% trans %}Please activate JavaScript to enable the search
- functionality.{% endtrans %}
-
-
-
-
- {% if search_performed %}
- {{ _('Search Results') }}
- {% if not search_results %}
- {{ _('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.') }}
- {% endif %}
- {% endif %}
-
- {% if search_results %}
-
- {% for href, caption, context in search_results %}
-
- {{ caption }}
- {{ context|e }}
-
- {% endfor %}
-
- {% endif %}
-
-{% endblock %}
diff --git a/_build/_themes/sphinx_rtd_theme/searchbox.html b/_build/_themes/sphinx_rtd_theme/searchbox.html
deleted file mode 100755
index 606f5c8c9d7..00000000000
--- a/_build/_themes/sphinx_rtd_theme/searchbox.html
+++ /dev/null
@@ -1,9 +0,0 @@
-{%- if builder != 'singlehtml' %}
-
-
-
-{%- endif %}
diff --git a/_build/_themes/sphinx_rtd_theme/static/css/badge_only.css b/_build/_themes/sphinx_rtd_theme/static/css/badge_only.css
deleted file mode 100755
index 323730ae29a..00000000000
--- a/_build/_themes/sphinx_rtd_theme/static/css/badge_only.css
+++ /dev/null
@@ -1 +0,0 @@
-.fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-weight:normal;font-style:normal;src:url("../fonts/fontawesome-webfont.eot");src:url("../fonts/fontawesome-webfont.eot?#iefix") format("embedded-opentype"),url("../fonts/fontawesome-webfont.woff") format("woff"),url("../fonts/fontawesome-webfont.ttf") format("truetype"),url("../fonts/fontawesome-webfont.svg#FontAwesome") format("svg")}.fa:before{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;text-decoration:inherit}a .fa{display:inline-block;text-decoration:inherit}li .fa{display:inline-block}li .fa-large:before,li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-0.8em}ul.fas li .fa{width:.8em}ul.fas li .fa-large:before,ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before{content:""}.icon-book:before{content:""}.fa-caret-down:before{content:""}.icon-caret-down:before{content:""}.fa-caret-up:before{content:""}.icon-caret-up:before{content:""}.fa-caret-left:before{content:""}.icon-caret-left:before{content:""}.fa-caret-right:before{content:""}.icon-caret-right:before{content:""}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;z-index:400}.rst-versions a{color:#2980B9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27AE60;*zoom:1}.rst-versions .rst-current-version:before,.rst-versions .rst-current-version:after{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book{float:left}.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#E74C3C;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#F1C40F;color:#000}.rst-versions.shift-up{height:auto;max-height:100%}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:gray;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:solid 1px #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px}.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge .fa-book{float:none}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book{float:left}.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge .rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width: 768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}}
diff --git a/_build/_themes/sphinx_rtd_theme/static/css/theme.css b/_build/_themes/sphinx_rtd_theme/static/css/theme.css
deleted file mode 100755
index 60b05590c20..00000000000
--- a/_build/_themes/sphinx_rtd_theme/static/css/theme.css
+++ /dev/null
@@ -1,6 +0,0 @@
-/* sphinx_rtd_theme version 0.4.0 | MIT license */
-/* Built 20180606 11:06 */
-*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}[hidden]{display:none}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:hover,a:active{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}blockquote{margin:0}dfn{font-style:italic}ins{background:#ff9;color:#000;text-decoration:none}mark{background:#ff0;color:#000;font-style:italic;font-weight:bold}pre,code,.rst-content tt,.rst-content code,kbd,samp{font-family:monospace,serif;_font-family:"courier new",monospace;font-size:1em}pre{white-space:pre}q{quotes:none}q:before,q:after{content:"";content:none}small{font-size:85%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}ul,ol,dl{margin:0;padding:0;list-style:none;list-style-image:none}li{list-style:none}dd{margin:0}img{border:0;-ms-interpolation-mode:bicubic;vertical-align:middle;max-width:100%}svg:not(:root){overflow:hidden}figure{margin:0}form{margin:0}fieldset{border:0;margin:0;padding:0}label{cursor:pointer}legend{border:0;*margin-left:-7px;padding:0;white-space:normal}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button;*overflow:visible}button[disabled],input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;*width:13px;*height:13px}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top;resize:vertical}table{border-collapse:collapse;border-spacing:0}td{vertical-align:top}.chromeframe{margin:.2em 0;background:#ccc;color:#000;padding:.2em 0}.ir{display:block;border:0;text-indent:-999em;overflow:hidden;background-color:transparent;background-repeat:no-repeat;text-align:left;direction:ltr;*line-height:0}.ir br{display:none}.hidden{display:none !important;visibility:hidden}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.relative{position:relative}big,small{font-size:100%}@media print{html,body,section{background:none !important}*{box-shadow:none !important;text-shadow:none !important;filter:none !important;-ms-filter:none !important}a,a:visited{text-decoration:underline}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:.5cm}p,h2,.rst-content .toctree-wrapper p.caption,h3{orphans:3;widows:3}h2,.rst-content .toctree-wrapper p.caption,h3{page-break-after:avoid}}.fa:before,.wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.rst-content .admonition-title:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content dl dt .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before,.icon:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-alert,.rst-content .note,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .warning,.rst-content .seealso,.rst-content .admonition-todo,.rst-content .admonition,.btn,input[type="text"],input[type="password"],input[type="email"],input[type="url"],input[type="date"],input[type="month"],input[type="time"],input[type="datetime"],input[type="datetime-local"],input[type="week"],input[type="number"],input[type="search"],input[type="tel"],input[type="color"],select,textarea,.wy-menu-vertical li.on a,.wy-menu-vertical li.current>a,.wy-side-nav-search>a,.wy-side-nav-search .wy-dropdown>a,.wy-nav-top a{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:""}.clearfix:after{clear:both}/*!
- * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome
- * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
- */@font-face{font-family:'FontAwesome';src:url("../fonts/fontawesome-webfont.eot?v=4.7.0");src:url("../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0") format("embedded-opentype"),url("../fonts/fontawesome-webfont.woff2?v=4.7.0") format("woff2"),url("../fonts/fontawesome-webfont.woff?v=4.7.0") format("woff"),url("../fonts/fontawesome-webfont.ttf?v=4.7.0") format("truetype"),url("../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular") format("svg");font-weight:normal;font-style:normal}.fa,.wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,.rst-content .admonition-title,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink,.rst-content tt.download span:first-child,.rst-content code.download span:first-child,.icon{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.3333333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.2857142857em;text-align:center}.fa-ul{padding-left:0;margin-left:2.1428571429em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.1428571429em;width:2.1428571429em;top:.1428571429em;text-align:center}.fa-li.fa-lg{left:-1.8571428571em}.fa-border{padding:.2em .25em .15em;border:solid 0.08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.wy-menu-vertical li span.fa-pull-left.toctree-expand,.wy-menu-vertical li.on a span.fa-pull-left.toctree-expand,.wy-menu-vertical li.current>a span.fa-pull-left.toctree-expand,.rst-content .fa-pull-left.admonition-title,.rst-content h1 .fa-pull-left.headerlink,.rst-content h2 .fa-pull-left.headerlink,.rst-content h3 .fa-pull-left.headerlink,.rst-content h4 .fa-pull-left.headerlink,.rst-content h5 .fa-pull-left.headerlink,.rst-content h6 .fa-pull-left.headerlink,.rst-content dl dt .fa-pull-left.headerlink,.rst-content p.caption .fa-pull-left.headerlink,.rst-content table>caption .fa-pull-left.headerlink,.rst-content tt.download span.fa-pull-left:first-child,.rst-content code.download span.fa-pull-left:first-child,.fa-pull-left.icon{margin-right:.3em}.fa.fa-pull-right,.wy-menu-vertical li span.fa-pull-right.toctree-expand,.wy-menu-vertical li.on a span.fa-pull-right.toctree-expand,.wy-menu-vertical li.current>a span.fa-pull-right.toctree-expand,.rst-content .fa-pull-right.admonition-title,.rst-content h1 .fa-pull-right.headerlink,.rst-content h2 .fa-pull-right.headerlink,.rst-content h3 .fa-pull-right.headerlink,.rst-content h4 .fa-pull-right.headerlink,.rst-content h5 .fa-pull-right.headerlink,.rst-content h6 .fa-pull-right.headerlink,.rst-content dl dt .fa-pull-right.headerlink,.rst-content p.caption .fa-pull-right.headerlink,.rst-content table>caption .fa-pull-right.headerlink,.rst-content tt.download span.fa-pull-right:first-child,.rst-content code.download span.fa-pull-right:first-child,.fa-pull-right.icon{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left,.wy-menu-vertical li span.pull-left.toctree-expand,.wy-menu-vertical li.on a span.pull-left.toctree-expand,.wy-menu-vertical li.current>a span.pull-left.toctree-expand,.rst-content .pull-left.admonition-title,.rst-content h1 .pull-left.headerlink,.rst-content h2 .pull-left.headerlink,.rst-content h3 .pull-left.headerlink,.rst-content h4 .pull-left.headerlink,.rst-content h5 .pull-left.headerlink,.rst-content h6 .pull-left.headerlink,.rst-content dl dt .pull-left.headerlink,.rst-content p.caption .pull-left.headerlink,.rst-content table>caption .pull-left.headerlink,.rst-content tt.download span.pull-left:first-child,.rst-content code.download span.pull-left:first-child,.pull-left.icon{margin-right:.3em}.fa.pull-right,.wy-menu-vertical li span.pull-right.toctree-expand,.wy-menu-vertical li.on a span.pull-right.toctree-expand,.wy-menu-vertical li.current>a span.pull-right.toctree-expand,.rst-content .pull-right.admonition-title,.rst-content h1 .pull-right.headerlink,.rst-content h2 .pull-right.headerlink,.rst-content h3 .pull-right.headerlink,.rst-content h4 .pull-right.headerlink,.rst-content h5 .pull-right.headerlink,.rst-content h6 .pull-right.headerlink,.rst-content dl dt .pull-right.headerlink,.rst-content p.caption .pull-right.headerlink,.rst-content table>caption .pull-right.headerlink,.rst-content tt.download span.pull-right:first-child,.rst-content code.download span.pull-right:first-child,.pull-right.icon{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:""}.fa-music:before{content:""}.fa-search:before,.icon-search:before{content:""}.fa-envelope-o:before{content:""}.fa-heart:before{content:""}.fa-star:before{content:""}.fa-star-o:before{content:""}.fa-user:before{content:""}.fa-film:before{content:""}.fa-th-large:before{content:""}.fa-th:before{content:""}.fa-th-list:before{content:""}.fa-check:before{content:""}.fa-remove:before,.fa-close:before,.fa-times:before{content:""}.fa-search-plus:before{content:""}.fa-search-minus:before{content:""}.fa-power-off:before{content:""}.fa-signal:before{content:""}.fa-gear:before,.fa-cog:before{content:""}.fa-trash-o:before{content:""}.fa-home:before,.icon-home:before{content:""}.fa-file-o:before{content:""}.fa-clock-o:before{content:""}.fa-road:before{content:""}.fa-download:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before{content:""}.fa-arrow-circle-o-down:before{content:""}.fa-arrow-circle-o-up:before{content:""}.fa-inbox:before{content:""}.fa-play-circle-o:before{content:""}.fa-rotate-right:before,.fa-repeat:before{content:""}.fa-refresh:before{content:""}.fa-list-alt:before{content:""}.fa-lock:before{content:""}.fa-flag:before{content:""}.fa-headphones:before{content:""}.fa-volume-off:before{content:""}.fa-volume-down:before{content:""}.fa-volume-up:before{content:""}.fa-qrcode:before{content:""}.fa-barcode:before{content:""}.fa-tag:before{content:""}.fa-tags:before{content:""}.fa-book:before,.icon-book:before{content:""}.fa-bookmark:before{content:""}.fa-print:before{content:""}.fa-camera:before{content:""}.fa-font:before{content:""}.fa-bold:before{content:""}.fa-italic:before{content:""}.fa-text-height:before{content:""}.fa-text-width:before{content:""}.fa-align-left:before{content:""}.fa-align-center:before{content:""}.fa-align-right:before{content:""}.fa-align-justify:before{content:""}.fa-list:before{content:""}.fa-dedent:before,.fa-outdent:before{content:""}.fa-indent:before{content:""}.fa-video-camera:before{content:""}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:""}.fa-pencil:before{content:""}.fa-map-marker:before{content:""}.fa-adjust:before{content:""}.fa-tint:before{content:""}.fa-edit:before,.fa-pencil-square-o:before{content:""}.fa-share-square-o:before{content:""}.fa-check-square-o:before{content:""}.fa-arrows:before{content:""}.fa-step-backward:before{content:""}.fa-fast-backward:before{content:""}.fa-backward:before{content:""}.fa-play:before{content:""}.fa-pause:before{content:""}.fa-stop:before{content:""}.fa-forward:before{content:""}.fa-fast-forward:before{content:""}.fa-step-forward:before{content:""}.fa-eject:before{content:""}.fa-chevron-left:before{content:""}.fa-chevron-right:before{content:""}.fa-plus-circle:before{content:""}.fa-minus-circle:before{content:""}.fa-times-circle:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before{content:""}.fa-check-circle:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before{content:""}.fa-question-circle:before{content:""}.fa-info-circle:before{content:""}.fa-crosshairs:before{content:""}.fa-times-circle-o:before{content:""}.fa-check-circle-o:before{content:""}.fa-ban:before{content:""}.fa-arrow-left:before{content:""}.fa-arrow-right:before{content:""}.fa-arrow-up:before{content:""}.fa-arrow-down:before{content:""}.fa-mail-forward:before,.fa-share:before{content:""}.fa-expand:before{content:""}.fa-compress:before{content:""}.fa-plus:before{content:""}.fa-minus:before{content:""}.fa-asterisk:before{content:""}.fa-exclamation-circle:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.rst-content .admonition-title:before{content:""}.fa-gift:before{content:""}.fa-leaf:before{content:""}.fa-fire:before,.icon-fire:before{content:""}.fa-eye:before{content:""}.fa-eye-slash:before{content:""}.fa-warning:before,.fa-exclamation-triangle:before{content:""}.fa-plane:before{content:""}.fa-calendar:before{content:""}.fa-random:before{content:""}.fa-comment:before{content:""}.fa-magnet:before{content:""}.fa-chevron-up:before{content:""}.fa-chevron-down:before{content:""}.fa-retweet:before{content:""}.fa-shopping-cart:before{content:""}.fa-folder:before{content:""}.fa-folder-open:before{content:""}.fa-arrows-v:before{content:""}.fa-arrows-h:before{content:""}.fa-bar-chart-o:before,.fa-bar-chart:before{content:""}.fa-twitter-square:before{content:""}.fa-facebook-square:before{content:""}.fa-camera-retro:before{content:""}.fa-key:before{content:""}.fa-gears:before,.fa-cogs:before{content:""}.fa-comments:before{content:""}.fa-thumbs-o-up:before{content:""}.fa-thumbs-o-down:before{content:""}.fa-star-half:before{content:""}.fa-heart-o:before{content:""}.fa-sign-out:before{content:""}.fa-linkedin-square:before{content:""}.fa-thumb-tack:before{content:""}.fa-external-link:before{content:""}.fa-sign-in:before{content:""}.fa-trophy:before{content:""}.fa-github-square:before{content:""}.fa-upload:before{content:""}.fa-lemon-o:before{content:""}.fa-phone:before{content:""}.fa-square-o:before{content:""}.fa-bookmark-o:before{content:""}.fa-phone-square:before{content:""}.fa-twitter:before{content:""}.fa-facebook-f:before,.fa-facebook:before{content:""}.fa-github:before,.icon-github:before{content:""}.fa-unlock:before{content:""}.fa-credit-card:before{content:""}.fa-feed:before,.fa-rss:before{content:""}.fa-hdd-o:before{content:""}.fa-bullhorn:before{content:""}.fa-bell:before{content:""}.fa-certificate:before{content:""}.fa-hand-o-right:before{content:""}.fa-hand-o-left:before{content:""}.fa-hand-o-up:before{content:""}.fa-hand-o-down:before{content:""}.fa-arrow-circle-left:before,.icon-circle-arrow-left:before{content:""}.fa-arrow-circle-right:before,.icon-circle-arrow-right:before{content:""}.fa-arrow-circle-up:before{content:""}.fa-arrow-circle-down:before{content:""}.fa-globe:before{content:""}.fa-wrench:before{content:""}.fa-tasks:before{content:""}.fa-filter:before{content:""}.fa-briefcase:before{content:""}.fa-arrows-alt:before{content:""}.fa-group:before,.fa-users:before{content:""}.fa-chain:before,.fa-link:before,.icon-link:before{content:""}.fa-cloud:before{content:""}.fa-flask:before{content:""}.fa-cut:before,.fa-scissors:before{content:""}.fa-copy:before,.fa-files-o:before{content:""}.fa-paperclip:before{content:""}.fa-save:before,.fa-floppy-o:before{content:""}.fa-square:before{content:""}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:""}.fa-list-ul:before{content:""}.fa-list-ol:before{content:""}.fa-strikethrough:before{content:""}.fa-underline:before{content:""}.fa-table:before{content:""}.fa-magic:before{content:""}.fa-truck:before{content:""}.fa-pinterest:before{content:""}.fa-pinterest-square:before{content:""}.fa-google-plus-square:before{content:""}.fa-google-plus:before{content:""}.fa-money:before{content:""}.fa-caret-down:before,.wy-dropdown .caret:before,.icon-caret-down:before{content:""}.fa-caret-up:before{content:""}.fa-caret-left:before{content:""}.fa-caret-right:before{content:""}.fa-columns:before{content:""}.fa-unsorted:before,.fa-sort:before{content:""}.fa-sort-down:before,.fa-sort-desc:before{content:""}.fa-sort-up:before,.fa-sort-asc:before{content:""}.fa-envelope:before{content:""}.fa-linkedin:before{content:""}.fa-rotate-left:before,.fa-undo:before{content:""}.fa-legal:before,.fa-gavel:before{content:""}.fa-dashboard:before,.fa-tachometer:before{content:""}.fa-comment-o:before{content:""}.fa-comments-o:before{content:""}.fa-flash:before,.fa-bolt:before{content:""}.fa-sitemap:before{content:""}.fa-umbrella:before{content:""}.fa-paste:before,.fa-clipboard:before{content:""}.fa-lightbulb-o:before{content:""}.fa-exchange:before{content:""}.fa-cloud-download:before{content:""}.fa-cloud-upload:before{content:""}.fa-user-md:before{content:""}.fa-stethoscope:before{content:""}.fa-suitcase:before{content:""}.fa-bell-o:before{content:""}.fa-coffee:before{content:""}.fa-cutlery:before{content:""}.fa-file-text-o:before{content:""}.fa-building-o:before{content:""}.fa-hospital-o:before{content:""}.fa-ambulance:before{content:""}.fa-medkit:before{content:""}.fa-fighter-jet:before{content:""}.fa-beer:before{content:""}.fa-h-square:before{content:""}.fa-plus-square:before{content:""}.fa-angle-double-left:before{content:""}.fa-angle-double-right:before{content:""}.fa-angle-double-up:before{content:""}.fa-angle-double-down:before{content:""}.fa-angle-left:before{content:""}.fa-angle-right:before{content:""}.fa-angle-up:before{content:""}.fa-angle-down:before{content:""}.fa-desktop:before{content:""}.fa-laptop:before{content:""}.fa-tablet:before{content:""}.fa-mobile-phone:before,.fa-mobile:before{content:""}.fa-circle-o:before{content:""}.fa-quote-left:before{content:""}.fa-quote-right:before{content:""}.fa-spinner:before{content:""}.fa-circle:before{content:""}.fa-mail-reply:before,.fa-reply:before{content:""}.fa-github-alt:before{content:""}.fa-folder-o:before{content:""}.fa-folder-open-o:before{content:""}.fa-smile-o:before{content:""}.fa-frown-o:before{content:""}.fa-meh-o:before{content:""}.fa-gamepad:before{content:""}.fa-keyboard-o:before{content:""}.fa-flag-o:before{content:""}.fa-flag-checkered:before{content:""}.fa-terminal:before{content:""}.fa-code:before{content:""}.fa-mail-reply-all:before,.fa-reply-all:before{content:""}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:""}.fa-location-arrow:before{content:""}.fa-crop:before{content:""}.fa-code-fork:before{content:""}.fa-unlink:before,.fa-chain-broken:before{content:""}.fa-question:before{content:""}.fa-info:before{content:""}.fa-exclamation:before{content:""}.fa-superscript:before{content:""}.fa-subscript:before{content:""}.fa-eraser:before{content:""}.fa-puzzle-piece:before{content:""}.fa-microphone:before{content:""}.fa-microphone-slash:before{content:""}.fa-shield:before{content:""}.fa-calendar-o:before{content:""}.fa-fire-extinguisher:before{content:""}.fa-rocket:before{content:""}.fa-maxcdn:before{content:""}.fa-chevron-circle-left:before{content:""}.fa-chevron-circle-right:before{content:""}.fa-chevron-circle-up:before{content:""}.fa-chevron-circle-down:before{content:""}.fa-html5:before{content:""}.fa-css3:before{content:""}.fa-anchor:before{content:""}.fa-unlock-alt:before{content:""}.fa-bullseye:before{content:""}.fa-ellipsis-h:before{content:""}.fa-ellipsis-v:before{content:""}.fa-rss-square:before{content:""}.fa-play-circle:before{content:""}.fa-ticket:before{content:""}.fa-minus-square:before{content:""}.fa-minus-square-o:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before{content:""}.fa-level-up:before{content:""}.fa-level-down:before{content:""}.fa-check-square:before{content:""}.fa-pencil-square:before{content:""}.fa-external-link-square:before{content:""}.fa-share-square:before{content:""}.fa-compass:before{content:""}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:""}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:""}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:""}.fa-euro:before,.fa-eur:before{content:""}.fa-gbp:before{content:""}.fa-dollar:before,.fa-usd:before{content:""}.fa-rupee:before,.fa-inr:before{content:""}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:""}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:""}.fa-won:before,.fa-krw:before{content:""}.fa-bitcoin:before,.fa-btc:before{content:""}.fa-file:before{content:""}.fa-file-text:before{content:""}.fa-sort-alpha-asc:before{content:""}.fa-sort-alpha-desc:before{content:""}.fa-sort-amount-asc:before{content:""}.fa-sort-amount-desc:before{content:""}.fa-sort-numeric-asc:before{content:""}.fa-sort-numeric-desc:before{content:""}.fa-thumbs-up:before{content:""}.fa-thumbs-down:before{content:""}.fa-youtube-square:before{content:""}.fa-youtube:before{content:""}.fa-xing:before{content:""}.fa-xing-square:before{content:""}.fa-youtube-play:before{content:""}.fa-dropbox:before{content:""}.fa-stack-overflow:before{content:""}.fa-instagram:before{content:""}.fa-flickr:before{content:""}.fa-adn:before{content:""}.fa-bitbucket:before,.icon-bitbucket:before{content:""}.fa-bitbucket-square:before{content:""}.fa-tumblr:before{content:""}.fa-tumblr-square:before{content:""}.fa-long-arrow-down:before{content:""}.fa-long-arrow-up:before{content:""}.fa-long-arrow-left:before{content:""}.fa-long-arrow-right:before{content:""}.fa-apple:before{content:""}.fa-windows:before{content:""}.fa-android:before{content:""}.fa-linux:before{content:""}.fa-dribbble:before{content:""}.fa-skype:before{content:""}.fa-foursquare:before{content:""}.fa-trello:before{content:""}.fa-female:before{content:""}.fa-male:before{content:""}.fa-gittip:before,.fa-gratipay:before{content:""}.fa-sun-o:before{content:""}.fa-moon-o:before{content:""}.fa-archive:before{content:""}.fa-bug:before{content:""}.fa-vk:before{content:""}.fa-weibo:before{content:""}.fa-renren:before{content:""}.fa-pagelines:before{content:""}.fa-stack-exchange:before{content:""}.fa-arrow-circle-o-right:before{content:""}.fa-arrow-circle-o-left:before{content:""}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:""}.fa-dot-circle-o:before{content:""}.fa-wheelchair:before{content:""}.fa-vimeo-square:before{content:""}.fa-turkish-lira:before,.fa-try:before{content:""}.fa-plus-square-o:before,.wy-menu-vertical li span.toctree-expand:before{content:""}.fa-space-shuttle:before{content:""}.fa-slack:before{content:""}.fa-envelope-square:before{content:""}.fa-wordpress:before{content:""}.fa-openid:before{content:""}.fa-institution:before,.fa-bank:before,.fa-university:before{content:""}.fa-mortar-board:before,.fa-graduation-cap:before{content:""}.fa-yahoo:before{content:""}.fa-google:before{content:""}.fa-reddit:before{content:""}.fa-reddit-square:before{content:""}.fa-stumbleupon-circle:before{content:""}.fa-stumbleupon:before{content:""}.fa-delicious:before{content:""}.fa-digg:before{content:""}.fa-pied-piper-pp:before{content:""}.fa-pied-piper-alt:before{content:""}.fa-drupal:before{content:""}.fa-joomla:before{content:""}.fa-language:before{content:""}.fa-fax:before{content:""}.fa-building:before{content:""}.fa-child:before{content:""}.fa-paw:before{content:""}.fa-spoon:before{content:""}.fa-cube:before{content:""}.fa-cubes:before{content:""}.fa-behance:before{content:""}.fa-behance-square:before{content:""}.fa-steam:before{content:""}.fa-steam-square:before{content:""}.fa-recycle:before{content:""}.fa-automobile:before,.fa-car:before{content:""}.fa-cab:before,.fa-taxi:before{content:""}.fa-tree:before{content:""}.fa-spotify:before{content:""}.fa-deviantart:before{content:""}.fa-soundcloud:before{content:""}.fa-database:before{content:""}.fa-file-pdf-o:before{content:""}.fa-file-word-o:before{content:""}.fa-file-excel-o:before{content:""}.fa-file-powerpoint-o:before{content:""}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:""}.fa-file-zip-o:before,.fa-file-archive-o:before{content:""}.fa-file-sound-o:before,.fa-file-audio-o:before{content:""}.fa-file-movie-o:before,.fa-file-video-o:before{content:""}.fa-file-code-o:before{content:""}.fa-vine:before{content:""}.fa-codepen:before{content:""}.fa-jsfiddle:before{content:""}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:""}.fa-circle-o-notch:before{content:""}.fa-ra:before,.fa-resistance:before,.fa-rebel:before{content:""}.fa-ge:before,.fa-empire:before{content:""}.fa-git-square:before{content:""}.fa-git:before{content:""}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:""}.fa-tencent-weibo:before{content:""}.fa-qq:before{content:""}.fa-wechat:before,.fa-weixin:before{content:""}.fa-send:before,.fa-paper-plane:before{content:""}.fa-send-o:before,.fa-paper-plane-o:before{content:""}.fa-history:before{content:""}.fa-circle-thin:before{content:""}.fa-header:before{content:""}.fa-paragraph:before{content:""}.fa-sliders:before{content:""}.fa-share-alt:before{content:""}.fa-share-alt-square:before{content:""}.fa-bomb:before{content:""}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:""}.fa-tty:before{content:""}.fa-binoculars:before{content:""}.fa-plug:before{content:""}.fa-slideshare:before{content:""}.fa-twitch:before{content:""}.fa-yelp:before{content:""}.fa-newspaper-o:before{content:""}.fa-wifi:before{content:""}.fa-calculator:before{content:""}.fa-paypal:before{content:""}.fa-google-wallet:before{content:""}.fa-cc-visa:before{content:""}.fa-cc-mastercard:before{content:""}.fa-cc-discover:before{content:""}.fa-cc-amex:before{content:""}.fa-cc-paypal:before{content:""}.fa-cc-stripe:before{content:""}.fa-bell-slash:before{content:""}.fa-bell-slash-o:before{content:""}.fa-trash:before{content:""}.fa-copyright:before{content:""}.fa-at:before{content:""}.fa-eyedropper:before{content:""}.fa-paint-brush:before{content:""}.fa-birthday-cake:before{content:""}.fa-area-chart:before{content:""}.fa-pie-chart:before{content:""}.fa-line-chart:before{content:""}.fa-lastfm:before{content:""}.fa-lastfm-square:before{content:""}.fa-toggle-off:before{content:""}.fa-toggle-on:before{content:""}.fa-bicycle:before{content:""}.fa-bus:before{content:""}.fa-ioxhost:before{content:""}.fa-angellist:before{content:""}.fa-cc:before{content:""}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:""}.fa-meanpath:before{content:""}.fa-buysellads:before{content:""}.fa-connectdevelop:before{content:""}.fa-dashcube:before{content:""}.fa-forumbee:before{content:""}.fa-leanpub:before{content:""}.fa-sellsy:before{content:""}.fa-shirtsinbulk:before{content:""}.fa-simplybuilt:before{content:""}.fa-skyatlas:before{content:""}.fa-cart-plus:before{content:""}.fa-cart-arrow-down:before{content:""}.fa-diamond:before{content:""}.fa-ship:before{content:""}.fa-user-secret:before{content:""}.fa-motorcycle:before{content:""}.fa-street-view:before{content:""}.fa-heartbeat:before{content:""}.fa-venus:before{content:""}.fa-mars:before{content:""}.fa-mercury:before{content:""}.fa-intersex:before,.fa-transgender:before{content:""}.fa-transgender-alt:before{content:""}.fa-venus-double:before{content:""}.fa-mars-double:before{content:""}.fa-venus-mars:before{content:""}.fa-mars-stroke:before{content:""}.fa-mars-stroke-v:before{content:""}.fa-mars-stroke-h:before{content:""}.fa-neuter:before{content:""}.fa-genderless:before{content:""}.fa-facebook-official:before{content:""}.fa-pinterest-p:before{content:""}.fa-whatsapp:before{content:""}.fa-server:before{content:""}.fa-user-plus:before{content:""}.fa-user-times:before{content:""}.fa-hotel:before,.fa-bed:before{content:""}.fa-viacoin:before{content:""}.fa-train:before{content:""}.fa-subway:before{content:""}.fa-medium:before{content:""}.fa-yc:before,.fa-y-combinator:before{content:""}.fa-optin-monster:before{content:""}.fa-opencart:before{content:""}.fa-expeditedssl:before{content:""}.fa-battery-4:before,.fa-battery:before,.fa-battery-full:before{content:""}.fa-battery-3:before,.fa-battery-three-quarters:before{content:""}.fa-battery-2:before,.fa-battery-half:before{content:""}.fa-battery-1:before,.fa-battery-quarter:before{content:""}.fa-battery-0:before,.fa-battery-empty:before{content:""}.fa-mouse-pointer:before{content:""}.fa-i-cursor:before{content:""}.fa-object-group:before{content:""}.fa-object-ungroup:before{content:""}.fa-sticky-note:before{content:""}.fa-sticky-note-o:before{content:""}.fa-cc-jcb:before{content:""}.fa-cc-diners-club:before{content:""}.fa-clone:before{content:""}.fa-balance-scale:before{content:""}.fa-hourglass-o:before{content:""}.fa-hourglass-1:before,.fa-hourglass-start:before{content:""}.fa-hourglass-2:before,.fa-hourglass-half:before{content:""}.fa-hourglass-3:before,.fa-hourglass-end:before{content:""}.fa-hourglass:before{content:""}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:""}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:""}.fa-hand-scissors-o:before{content:""}.fa-hand-lizard-o:before{content:""}.fa-hand-spock-o:before{content:""}.fa-hand-pointer-o:before{content:""}.fa-hand-peace-o:before{content:""}.fa-trademark:before{content:""}.fa-registered:before{content:""}.fa-creative-commons:before{content:""}.fa-gg:before{content:""}.fa-gg-circle:before{content:""}.fa-tripadvisor:before{content:""}.fa-odnoklassniki:before{content:""}.fa-odnoklassniki-square:before{content:""}.fa-get-pocket:before{content:""}.fa-wikipedia-w:before{content:""}.fa-safari:before{content:""}.fa-chrome:before{content:""}.fa-firefox:before{content:""}.fa-opera:before{content:""}.fa-internet-explorer:before{content:""}.fa-tv:before,.fa-television:before{content:""}.fa-contao:before{content:""}.fa-500px:before{content:""}.fa-amazon:before{content:""}.fa-calendar-plus-o:before{content:""}.fa-calendar-minus-o:before{content:""}.fa-calendar-times-o:before{content:""}.fa-calendar-check-o:before{content:""}.fa-industry:before{content:""}.fa-map-pin:before{content:""}.fa-map-signs:before{content:""}.fa-map-o:before{content:""}.fa-map:before{content:""}.fa-commenting:before{content:""}.fa-commenting-o:before{content:""}.fa-houzz:before{content:""}.fa-vimeo:before{content:""}.fa-black-tie:before{content:""}.fa-fonticons:before{content:""}.fa-reddit-alien:before{content:""}.fa-edge:before{content:""}.fa-credit-card-alt:before{content:""}.fa-codiepie:before{content:""}.fa-modx:before{content:""}.fa-fort-awesome:before{content:""}.fa-usb:before{content:""}.fa-product-hunt:before{content:""}.fa-mixcloud:before{content:""}.fa-scribd:before{content:""}.fa-pause-circle:before{content:""}.fa-pause-circle-o:before{content:""}.fa-stop-circle:before{content:""}.fa-stop-circle-o:before{content:""}.fa-shopping-bag:before{content:""}.fa-shopping-basket:before{content:""}.fa-hashtag:before{content:""}.fa-bluetooth:before{content:""}.fa-bluetooth-b:before{content:""}.fa-percent:before{content:""}.fa-gitlab:before,.icon-gitlab:before{content:""}.fa-wpbeginner:before{content:""}.fa-wpforms:before{content:""}.fa-envira:before{content:""}.fa-universal-access:before{content:""}.fa-wheelchair-alt:before{content:""}.fa-question-circle-o:before{content:""}.fa-blind:before{content:""}.fa-audio-description:before{content:""}.fa-volume-control-phone:before{content:""}.fa-braille:before{content:""}.fa-assistive-listening-systems:before{content:""}.fa-asl-interpreting:before,.fa-american-sign-language-interpreting:before{content:""}.fa-deafness:before,.fa-hard-of-hearing:before,.fa-deaf:before{content:""}.fa-glide:before{content:""}.fa-glide-g:before{content:""}.fa-signing:before,.fa-sign-language:before{content:""}.fa-low-vision:before{content:""}.fa-viadeo:before{content:""}.fa-viadeo-square:before{content:""}.fa-snapchat:before{content:""}.fa-snapchat-ghost:before{content:""}.fa-snapchat-square:before{content:""}.fa-pied-piper:before{content:""}.fa-first-order:before{content:""}.fa-yoast:before{content:""}.fa-themeisle:before{content:""}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:""}.fa-fa:before,.fa-font-awesome:before{content:""}.fa-handshake-o:before{content:""}.fa-envelope-open:before{content:""}.fa-envelope-open-o:before{content:""}.fa-linode:before{content:""}.fa-address-book:before{content:""}.fa-address-book-o:before{content:""}.fa-vcard:before,.fa-address-card:before{content:""}.fa-vcard-o:before,.fa-address-card-o:before{content:""}.fa-user-circle:before{content:""}.fa-user-circle-o:before{content:""}.fa-user-o:before{content:""}.fa-id-badge:before{content:""}.fa-drivers-license:before,.fa-id-card:before{content:""}.fa-drivers-license-o:before,.fa-id-card-o:before{content:""}.fa-quora:before{content:""}.fa-free-code-camp:before{content:""}.fa-telegram:before{content:""}.fa-thermometer-4:before,.fa-thermometer:before,.fa-thermometer-full:before{content:""}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:""}.fa-thermometer-2:before,.fa-thermometer-half:before{content:""}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:""}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:""}.fa-shower:before{content:""}.fa-bathtub:before,.fa-s15:before,.fa-bath:before{content:""}.fa-podcast:before{content:""}.fa-window-maximize:before{content:""}.fa-window-minimize:before{content:""}.fa-window-restore:before{content:""}.fa-times-rectangle:before,.fa-window-close:before{content:""}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:""}.fa-bandcamp:before{content:""}.fa-grav:before{content:""}.fa-etsy:before{content:""}.fa-imdb:before{content:""}.fa-ravelry:before{content:""}.fa-eercast:before{content:""}.fa-microchip:before{content:""}.fa-snowflake-o:before{content:""}.fa-superpowers:before{content:""}.fa-wpexplorer:before{content:""}.fa-meetup:before{content:""}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}.fa,.wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,.rst-content .admonition-title,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink,.rst-content tt.download span:first-child,.rst-content code.download span:first-child,.icon,.wy-dropdown .caret,.wy-inline-validate.wy-inline-validate-success .wy-input-context,.wy-inline-validate.wy-inline-validate-danger .wy-input-context,.wy-inline-validate.wy-inline-validate-warning .wy-input-context,.wy-inline-validate.wy-inline-validate-info .wy-input-context{font-family:inherit}.fa:before,.wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.rst-content .admonition-title:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content dl dt .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before,.icon:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before{font-family:"FontAwesome";display:inline-block;font-style:normal;font-weight:normal;line-height:1;text-decoration:inherit}a .fa,a .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li a span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,a .rst-content .admonition-title,.rst-content a .admonition-title,a .rst-content h1 .headerlink,.rst-content h1 a .headerlink,a .rst-content h2 .headerlink,.rst-content h2 a .headerlink,a .rst-content h3 .headerlink,.rst-content h3 a .headerlink,a .rst-content h4 .headerlink,.rst-content h4 a .headerlink,a .rst-content h5 .headerlink,.rst-content h5 a .headerlink,a .rst-content h6 .headerlink,.rst-content h6 a .headerlink,a .rst-content dl dt .headerlink,.rst-content dl dt a .headerlink,a .rst-content p.caption .headerlink,.rst-content p.caption a .headerlink,a .rst-content table>caption .headerlink,.rst-content table>caption a .headerlink,a .rst-content tt.download span:first-child,.rst-content tt.download a span:first-child,a .rst-content code.download span:first-child,.rst-content code.download a span:first-child,a .icon{display:inline-block;text-decoration:inherit}.btn .fa,.btn .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .btn span.toctree-expand,.btn .wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.on a .btn span.toctree-expand,.btn .wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.current>a .btn span.toctree-expand,.btn .rst-content .admonition-title,.rst-content .btn .admonition-title,.btn .rst-content h1 .headerlink,.rst-content h1 .btn .headerlink,.btn .rst-content h2 .headerlink,.rst-content h2 .btn .headerlink,.btn .rst-content h3 .headerlink,.rst-content h3 .btn .headerlink,.btn .rst-content h4 .headerlink,.rst-content h4 .btn .headerlink,.btn .rst-content h5 .headerlink,.rst-content h5 .btn .headerlink,.btn .rst-content h6 .headerlink,.rst-content h6 .btn .headerlink,.btn .rst-content dl dt .headerlink,.rst-content dl dt .btn .headerlink,.btn .rst-content p.caption .headerlink,.rst-content p.caption .btn .headerlink,.btn .rst-content table>caption .headerlink,.rst-content table>caption .btn .headerlink,.btn .rst-content tt.download span:first-child,.rst-content tt.download .btn span:first-child,.btn .rst-content code.download span:first-child,.rst-content code.download .btn span:first-child,.btn .icon,.nav .fa,.nav .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .nav span.toctree-expand,.nav .wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.on a .nav span.toctree-expand,.nav .wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.current>a .nav span.toctree-expand,.nav .rst-content .admonition-title,.rst-content .nav .admonition-title,.nav .rst-content h1 .headerlink,.rst-content h1 .nav .headerlink,.nav .rst-content h2 .headerlink,.rst-content h2 .nav .headerlink,.nav .rst-content h3 .headerlink,.rst-content h3 .nav .headerlink,.nav .rst-content h4 .headerlink,.rst-content h4 .nav .headerlink,.nav .rst-content h5 .headerlink,.rst-content h5 .nav .headerlink,.nav .rst-content h6 .headerlink,.rst-content h6 .nav .headerlink,.nav .rst-content dl dt .headerlink,.rst-content dl dt .nav .headerlink,.nav .rst-content p.caption .headerlink,.rst-content p.caption .nav .headerlink,.nav .rst-content table>caption .headerlink,.rst-content table>caption .nav .headerlink,.nav .rst-content tt.download span:first-child,.rst-content tt.download .nav span:first-child,.nav .rst-content code.download span:first-child,.rst-content code.download .nav span:first-child,.nav .icon{display:inline}.btn .fa.fa-large,.btn .wy-menu-vertical li span.fa-large.toctree-expand,.wy-menu-vertical li .btn span.fa-large.toctree-expand,.btn .rst-content .fa-large.admonition-title,.rst-content .btn .fa-large.admonition-title,.btn .rst-content h1 .fa-large.headerlink,.rst-content h1 .btn .fa-large.headerlink,.btn .rst-content h2 .fa-large.headerlink,.rst-content h2 .btn .fa-large.headerlink,.btn .rst-content h3 .fa-large.headerlink,.rst-content h3 .btn .fa-large.headerlink,.btn .rst-content h4 .fa-large.headerlink,.rst-content h4 .btn .fa-large.headerlink,.btn .rst-content h5 .fa-large.headerlink,.rst-content h5 .btn .fa-large.headerlink,.btn .rst-content h6 .fa-large.headerlink,.rst-content h6 .btn .fa-large.headerlink,.btn .rst-content dl dt .fa-large.headerlink,.rst-content dl dt .btn .fa-large.headerlink,.btn .rst-content p.caption .fa-large.headerlink,.rst-content p.caption .btn .fa-large.headerlink,.btn .rst-content table>caption .fa-large.headerlink,.rst-content table>caption .btn .fa-large.headerlink,.btn .rst-content tt.download span.fa-large:first-child,.rst-content tt.download .btn span.fa-large:first-child,.btn .rst-content code.download span.fa-large:first-child,.rst-content code.download .btn span.fa-large:first-child,.btn .fa-large.icon,.nav .fa.fa-large,.nav .wy-menu-vertical li span.fa-large.toctree-expand,.wy-menu-vertical li .nav span.fa-large.toctree-expand,.nav .rst-content .fa-large.admonition-title,.rst-content .nav .fa-large.admonition-title,.nav .rst-content h1 .fa-large.headerlink,.rst-content h1 .nav .fa-large.headerlink,.nav .rst-content h2 .fa-large.headerlink,.rst-content h2 .nav .fa-large.headerlink,.nav .rst-content h3 .fa-large.headerlink,.rst-content h3 .nav .fa-large.headerlink,.nav .rst-content h4 .fa-large.headerlink,.rst-content h4 .nav .fa-large.headerlink,.nav .rst-content h5 .fa-large.headerlink,.rst-content h5 .nav .fa-large.headerlink,.nav .rst-content h6 .fa-large.headerlink,.rst-content h6 .nav .fa-large.headerlink,.nav .rst-content dl dt .fa-large.headerlink,.rst-content dl dt .nav .fa-large.headerlink,.nav .rst-content p.caption .fa-large.headerlink,.rst-content p.caption .nav .fa-large.headerlink,.nav .rst-content table>caption .fa-large.headerlink,.rst-content table>caption .nav .fa-large.headerlink,.nav .rst-content tt.download span.fa-large:first-child,.rst-content tt.download .nav span.fa-large:first-child,.nav .rst-content code.download span.fa-large:first-child,.rst-content code.download .nav span.fa-large:first-child,.nav .fa-large.icon{line-height:.9em}.btn .fa.fa-spin,.btn .wy-menu-vertical li span.fa-spin.toctree-expand,.wy-menu-vertical li .btn span.fa-spin.toctree-expand,.btn .rst-content .fa-spin.admonition-title,.rst-content .btn .fa-spin.admonition-title,.btn .rst-content h1 .fa-spin.headerlink,.rst-content h1 .btn .fa-spin.headerlink,.btn .rst-content h2 .fa-spin.headerlink,.rst-content h2 .btn .fa-spin.headerlink,.btn .rst-content h3 .fa-spin.headerlink,.rst-content h3 .btn .fa-spin.headerlink,.btn .rst-content h4 .fa-spin.headerlink,.rst-content h4 .btn .fa-spin.headerlink,.btn .rst-content h5 .fa-spin.headerlink,.rst-content h5 .btn .fa-spin.headerlink,.btn .rst-content h6 .fa-spin.headerlink,.rst-content h6 .btn .fa-spin.headerlink,.btn .rst-content dl dt .fa-spin.headerlink,.rst-content dl dt .btn .fa-spin.headerlink,.btn .rst-content p.caption .fa-spin.headerlink,.rst-content p.caption .btn .fa-spin.headerlink,.btn .rst-content table>caption .fa-spin.headerlink,.rst-content table>caption .btn .fa-spin.headerlink,.btn .rst-content tt.download span.fa-spin:first-child,.rst-content tt.download .btn span.fa-spin:first-child,.btn .rst-content code.download span.fa-spin:first-child,.rst-content code.download .btn span.fa-spin:first-child,.btn .fa-spin.icon,.nav .fa.fa-spin,.nav .wy-menu-vertical li span.fa-spin.toctree-expand,.wy-menu-vertical li .nav span.fa-spin.toctree-expand,.nav .rst-content .fa-spin.admonition-title,.rst-content .nav .fa-spin.admonition-title,.nav .rst-content h1 .fa-spin.headerlink,.rst-content h1 .nav .fa-spin.headerlink,.nav .rst-content h2 .fa-spin.headerlink,.rst-content h2 .nav .fa-spin.headerlink,.nav .rst-content h3 .fa-spin.headerlink,.rst-content h3 .nav .fa-spin.headerlink,.nav .rst-content h4 .fa-spin.headerlink,.rst-content h4 .nav .fa-spin.headerlink,.nav .rst-content h5 .fa-spin.headerlink,.rst-content h5 .nav .fa-spin.headerlink,.nav .rst-content h6 .fa-spin.headerlink,.rst-content h6 .nav .fa-spin.headerlink,.nav .rst-content dl dt .fa-spin.headerlink,.rst-content dl dt .nav .fa-spin.headerlink,.nav .rst-content p.caption .fa-spin.headerlink,.rst-content p.caption .nav .fa-spin.headerlink,.nav .rst-content table>caption .fa-spin.headerlink,.rst-content table>caption .nav .fa-spin.headerlink,.nav .rst-content tt.download span.fa-spin:first-child,.rst-content tt.download .nav span.fa-spin:first-child,.nav .rst-content code.download span.fa-spin:first-child,.rst-content code.download .nav span.fa-spin:first-child,.nav .fa-spin.icon{display:inline-block}.btn.fa:before,.wy-menu-vertical li span.btn.toctree-expand:before,.rst-content .btn.admonition-title:before,.rst-content h1 .btn.headerlink:before,.rst-content h2 .btn.headerlink:before,.rst-content h3 .btn.headerlink:before,.rst-content h4 .btn.headerlink:before,.rst-content h5 .btn.headerlink:before,.rst-content h6 .btn.headerlink:before,.rst-content dl dt .btn.headerlink:before,.rst-content p.caption .btn.headerlink:before,.rst-content table>caption .btn.headerlink:before,.rst-content tt.download span.btn:first-child:before,.rst-content code.download span.btn:first-child:before,.btn.icon:before{opacity:.5;-webkit-transition:opacity .05s ease-in;-moz-transition:opacity .05s ease-in;transition:opacity .05s ease-in}.btn.fa:hover:before,.wy-menu-vertical li span.btn.toctree-expand:hover:before,.rst-content .btn.admonition-title:hover:before,.rst-content h1 .btn.headerlink:hover:before,.rst-content h2 .btn.headerlink:hover:before,.rst-content h3 .btn.headerlink:hover:before,.rst-content h4 .btn.headerlink:hover:before,.rst-content h5 .btn.headerlink:hover:before,.rst-content h6 .btn.headerlink:hover:before,.rst-content dl dt .btn.headerlink:hover:before,.rst-content p.caption .btn.headerlink:hover:before,.rst-content table>caption .btn.headerlink:hover:before,.rst-content tt.download span.btn:first-child:hover:before,.rst-content code.download span.btn:first-child:hover:before,.btn.icon:hover:before{opacity:1}.btn-mini .fa:before,.btn-mini .wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li .btn-mini span.toctree-expand:before,.btn-mini .rst-content .admonition-title:before,.rst-content .btn-mini .admonition-title:before,.btn-mini .rst-content h1 .headerlink:before,.rst-content h1 .btn-mini .headerlink:before,.btn-mini .rst-content h2 .headerlink:before,.rst-content h2 .btn-mini .headerlink:before,.btn-mini .rst-content h3 .headerlink:before,.rst-content h3 .btn-mini .headerlink:before,.btn-mini .rst-content h4 .headerlink:before,.rst-content h4 .btn-mini .headerlink:before,.btn-mini .rst-content h5 .headerlink:before,.rst-content h5 .btn-mini .headerlink:before,.btn-mini .rst-content h6 .headerlink:before,.rst-content h6 .btn-mini .headerlink:before,.btn-mini .rst-content dl dt .headerlink:before,.rst-content dl dt .btn-mini .headerlink:before,.btn-mini .rst-content p.caption .headerlink:before,.rst-content p.caption .btn-mini .headerlink:before,.btn-mini .rst-content table>caption .headerlink:before,.rst-content table>caption .btn-mini .headerlink:before,.btn-mini .rst-content tt.download span:first-child:before,.rst-content tt.download .btn-mini span:first-child:before,.btn-mini .rst-content code.download span:first-child:before,.rst-content code.download .btn-mini span:first-child:before,.btn-mini .icon:before{font-size:14px;vertical-align:-15%}.wy-alert,.rst-content .note,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .warning,.rst-content .seealso,.rst-content .admonition-todo,.rst-content .admonition{padding:12px;line-height:24px;margin-bottom:24px;background:#e7f2fa}.wy-alert-title,.rst-content .admonition-title{color:#fff;font-weight:bold;display:block;color:#fff;background:#6ab0de;margin:-12px;padding:6px 12px;margin-bottom:12px}.wy-alert.wy-alert-danger,.rst-content .wy-alert-danger.note,.rst-content .wy-alert-danger.attention,.rst-content .wy-alert-danger.caution,.rst-content .danger,.rst-content .error,.rst-content .wy-alert-danger.hint,.rst-content .wy-alert-danger.important,.rst-content .wy-alert-danger.tip,.rst-content .wy-alert-danger.warning,.rst-content .wy-alert-danger.seealso,.rst-content .wy-alert-danger.admonition-todo,.rst-content .wy-alert-danger.admonition{background:#fdf3f2}.wy-alert.wy-alert-danger .wy-alert-title,.rst-content .wy-alert-danger.note .wy-alert-title,.rst-content .wy-alert-danger.attention .wy-alert-title,.rst-content .wy-alert-danger.caution .wy-alert-title,.rst-content .danger .wy-alert-title,.rst-content .error .wy-alert-title,.rst-content .wy-alert-danger.hint .wy-alert-title,.rst-content .wy-alert-danger.important .wy-alert-title,.rst-content .wy-alert-danger.tip .wy-alert-title,.rst-content .wy-alert-danger.warning .wy-alert-title,.rst-content .wy-alert-danger.seealso .wy-alert-title,.rst-content .wy-alert-danger.admonition-todo .wy-alert-title,.rst-content .wy-alert-danger.admonition .wy-alert-title,.wy-alert.wy-alert-danger .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-danger .admonition-title,.rst-content .wy-alert-danger.note .admonition-title,.rst-content .wy-alert-danger.attention .admonition-title,.rst-content .wy-alert-danger.caution .admonition-title,.rst-content .danger .admonition-title,.rst-content .error .admonition-title,.rst-content .wy-alert-danger.hint .admonition-title,.rst-content .wy-alert-danger.important .admonition-title,.rst-content .wy-alert-danger.tip .admonition-title,.rst-content .wy-alert-danger.warning .admonition-title,.rst-content .wy-alert-danger.seealso .admonition-title,.rst-content .wy-alert-danger.admonition-todo .admonition-title,.rst-content .wy-alert-danger.admonition .admonition-title{background:#f29f97}.wy-alert.wy-alert-warning,.rst-content .wy-alert-warning.note,.rst-content .attention,.rst-content .caution,.rst-content .wy-alert-warning.danger,.rst-content .wy-alert-warning.error,.rst-content .wy-alert-warning.hint,.rst-content .wy-alert-warning.important,.rst-content .wy-alert-warning.tip,.rst-content .warning,.rst-content .wy-alert-warning.seealso,.rst-content .admonition-todo,.rst-content .wy-alert-warning.admonition{background:#ffedcc}.wy-alert.wy-alert-warning .wy-alert-title,.rst-content .wy-alert-warning.note .wy-alert-title,.rst-content .attention .wy-alert-title,.rst-content .caution .wy-alert-title,.rst-content .wy-alert-warning.danger .wy-alert-title,.rst-content .wy-alert-warning.error .wy-alert-title,.rst-content .wy-alert-warning.hint .wy-alert-title,.rst-content .wy-alert-warning.important .wy-alert-title,.rst-content .wy-alert-warning.tip .wy-alert-title,.rst-content .warning .wy-alert-title,.rst-content .wy-alert-warning.seealso .wy-alert-title,.rst-content .admonition-todo .wy-alert-title,.rst-content .wy-alert-warning.admonition .wy-alert-title,.wy-alert.wy-alert-warning .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-warning .admonition-title,.rst-content .wy-alert-warning.note .admonition-title,.rst-content .attention .admonition-title,.rst-content .caution .admonition-title,.rst-content .wy-alert-warning.danger .admonition-title,.rst-content .wy-alert-warning.error .admonition-title,.rst-content .wy-alert-warning.hint .admonition-title,.rst-content .wy-alert-warning.important .admonition-title,.rst-content .wy-alert-warning.tip .admonition-title,.rst-content .warning .admonition-title,.rst-content .wy-alert-warning.seealso .admonition-title,.rst-content .admonition-todo .admonition-title,.rst-content .wy-alert-warning.admonition .admonition-title{background:#f0b37e}.wy-alert.wy-alert-info,.rst-content .note,.rst-content .wy-alert-info.attention,.rst-content .wy-alert-info.caution,.rst-content .wy-alert-info.danger,.rst-content .wy-alert-info.error,.rst-content .wy-alert-info.hint,.rst-content .wy-alert-info.important,.rst-content .wy-alert-info.tip,.rst-content .wy-alert-info.warning,.rst-content .seealso,.rst-content .wy-alert-info.admonition-todo,.rst-content .wy-alert-info.admonition{background:#e7f2fa}.wy-alert.wy-alert-info .wy-alert-title,.rst-content .note .wy-alert-title,.rst-content .wy-alert-info.attention .wy-alert-title,.rst-content .wy-alert-info.caution .wy-alert-title,.rst-content .wy-alert-info.danger .wy-alert-title,.rst-content .wy-alert-info.error .wy-alert-title,.rst-content .wy-alert-info.hint .wy-alert-title,.rst-content .wy-alert-info.important .wy-alert-title,.rst-content .wy-alert-info.tip .wy-alert-title,.rst-content .wy-alert-info.warning .wy-alert-title,.rst-content .seealso .wy-alert-title,.rst-content .wy-alert-info.admonition-todo .wy-alert-title,.rst-content .wy-alert-info.admonition .wy-alert-title,.wy-alert.wy-alert-info .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-info .admonition-title,.rst-content .note .admonition-title,.rst-content .wy-alert-info.attention .admonition-title,.rst-content .wy-alert-info.caution .admonition-title,.rst-content .wy-alert-info.danger .admonition-title,.rst-content .wy-alert-info.error .admonition-title,.rst-content .wy-alert-info.hint .admonition-title,.rst-content .wy-alert-info.important .admonition-title,.rst-content .wy-alert-info.tip .admonition-title,.rst-content .wy-alert-info.warning .admonition-title,.rst-content .seealso .admonition-title,.rst-content .wy-alert-info.admonition-todo .admonition-title,.rst-content .wy-alert-info.admonition .admonition-title{background:#6ab0de}.wy-alert.wy-alert-success,.rst-content .wy-alert-success.note,.rst-content .wy-alert-success.attention,.rst-content .wy-alert-success.caution,.rst-content .wy-alert-success.danger,.rst-content .wy-alert-success.error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .wy-alert-success.warning,.rst-content .wy-alert-success.seealso,.rst-content .wy-alert-success.admonition-todo,.rst-content .wy-alert-success.admonition{background:#dbfaf4}.wy-alert.wy-alert-success .wy-alert-title,.rst-content .wy-alert-success.note .wy-alert-title,.rst-content .wy-alert-success.attention .wy-alert-title,.rst-content .wy-alert-success.caution .wy-alert-title,.rst-content .wy-alert-success.danger .wy-alert-title,.rst-content .wy-alert-success.error .wy-alert-title,.rst-content .hint .wy-alert-title,.rst-content .important .wy-alert-title,.rst-content .tip .wy-alert-title,.rst-content .wy-alert-success.warning .wy-alert-title,.rst-content .wy-alert-success.seealso .wy-alert-title,.rst-content .wy-alert-success.admonition-todo .wy-alert-title,.rst-content .wy-alert-success.admonition .wy-alert-title,.wy-alert.wy-alert-success .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-success .admonition-title,.rst-content .wy-alert-success.note .admonition-title,.rst-content .wy-alert-success.attention .admonition-title,.rst-content .wy-alert-success.caution .admonition-title,.rst-content .wy-alert-success.danger .admonition-title,.rst-content .wy-alert-success.error .admonition-title,.rst-content .hint .admonition-title,.rst-content .important .admonition-title,.rst-content .tip .admonition-title,.rst-content .wy-alert-success.warning .admonition-title,.rst-content .wy-alert-success.seealso .admonition-title,.rst-content .wy-alert-success.admonition-todo .admonition-title,.rst-content .wy-alert-success.admonition .admonition-title{background:#1abc9c}.wy-alert.wy-alert-neutral,.rst-content .wy-alert-neutral.note,.rst-content .wy-alert-neutral.attention,.rst-content .wy-alert-neutral.caution,.rst-content .wy-alert-neutral.danger,.rst-content .wy-alert-neutral.error,.rst-content .wy-alert-neutral.hint,.rst-content .wy-alert-neutral.important,.rst-content .wy-alert-neutral.tip,.rst-content .wy-alert-neutral.warning,.rst-content .wy-alert-neutral.seealso,.rst-content .wy-alert-neutral.admonition-todo,.rst-content .wy-alert-neutral.admonition{background:#f3f6f6}.wy-alert.wy-alert-neutral .wy-alert-title,.rst-content .wy-alert-neutral.note .wy-alert-title,.rst-content .wy-alert-neutral.attention .wy-alert-title,.rst-content .wy-alert-neutral.caution .wy-alert-title,.rst-content .wy-alert-neutral.danger .wy-alert-title,.rst-content .wy-alert-neutral.error .wy-alert-title,.rst-content .wy-alert-neutral.hint .wy-alert-title,.rst-content .wy-alert-neutral.important .wy-alert-title,.rst-content .wy-alert-neutral.tip .wy-alert-title,.rst-content .wy-alert-neutral.warning .wy-alert-title,.rst-content .wy-alert-neutral.seealso .wy-alert-title,.rst-content .wy-alert-neutral.admonition-todo .wy-alert-title,.rst-content .wy-alert-neutral.admonition .wy-alert-title,.wy-alert.wy-alert-neutral .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-neutral .admonition-title,.rst-content .wy-alert-neutral.note .admonition-title,.rst-content .wy-alert-neutral.attention .admonition-title,.rst-content .wy-alert-neutral.caution .admonition-title,.rst-content .wy-alert-neutral.danger .admonition-title,.rst-content .wy-alert-neutral.error .admonition-title,.rst-content .wy-alert-neutral.hint .admonition-title,.rst-content .wy-alert-neutral.important .admonition-title,.rst-content .wy-alert-neutral.tip .admonition-title,.rst-content .wy-alert-neutral.warning .admonition-title,.rst-content .wy-alert-neutral.seealso .admonition-title,.rst-content .wy-alert-neutral.admonition-todo .admonition-title,.rst-content .wy-alert-neutral.admonition .admonition-title{color:#404040;background:#e1e4e5}.wy-alert.wy-alert-neutral a,.rst-content .wy-alert-neutral.note a,.rst-content .wy-alert-neutral.attention a,.rst-content .wy-alert-neutral.caution a,.rst-content .wy-alert-neutral.danger a,.rst-content .wy-alert-neutral.error a,.rst-content .wy-alert-neutral.hint a,.rst-content .wy-alert-neutral.important a,.rst-content .wy-alert-neutral.tip a,.rst-content .wy-alert-neutral.warning a,.rst-content .wy-alert-neutral.seealso a,.rst-content .wy-alert-neutral.admonition-todo a,.rst-content .wy-alert-neutral.admonition a{color:#2980B9}.wy-alert p:last-child,.rst-content .note p:last-child,.rst-content .attention p:last-child,.rst-content .caution p:last-child,.rst-content .danger p:last-child,.rst-content .error p:last-child,.rst-content .hint p:last-child,.rst-content .important p:last-child,.rst-content .tip p:last-child,.rst-content .warning p:last-child,.rst-content .seealso p:last-child,.rst-content .admonition-todo p:last-child,.rst-content .admonition p:last-child{margin-bottom:0}.wy-tray-container{position:fixed;bottom:0px;left:0;z-index:600}.wy-tray-container li{display:block;width:300px;background:transparent;color:#fff;text-align:center;box-shadow:0 5px 5px 0 rgba(0,0,0,0.1);padding:0 24px;min-width:20%;opacity:0;height:0;line-height:56px;overflow:hidden;-webkit-transition:all .3s ease-in;-moz-transition:all .3s ease-in;transition:all .3s ease-in}.wy-tray-container li.wy-tray-item-success{background:#27AE60}.wy-tray-container li.wy-tray-item-info{background:#2980B9}.wy-tray-container li.wy-tray-item-warning{background:#E67E22}.wy-tray-container li.wy-tray-item-danger{background:#E74C3C}.wy-tray-container li.on{opacity:1;height:56px}@media screen and (max-width: 768px){.wy-tray-container{bottom:auto;top:0;width:100%}.wy-tray-container li{width:100%}}button{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle;cursor:pointer;line-height:normal;-webkit-appearance:button;*overflow:visible}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}button[disabled]{cursor:default}.btn{display:inline-block;border-radius:2px;line-height:normal;white-space:nowrap;text-align:center;cursor:pointer;font-size:100%;padding:6px 12px 8px 12px;color:#fff;border:1px solid rgba(0,0,0,0.1);background-color:#27AE60;text-decoration:none;font-weight:normal;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;box-shadow:0px 1px 2px -1px rgba(255,255,255,0.5) inset,0px -2px 0px 0px rgba(0,0,0,0.1) inset;outline-none:false;vertical-align:middle;*display:inline;zoom:1;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-transition:all .1s linear;-moz-transition:all .1s linear;transition:all .1s linear}.btn-hover{background:#2e8ece;color:#fff}.btn:hover{background:#2cc36b;color:#fff}.btn:focus{background:#2cc36b;outline:0}.btn:active{box-shadow:0px -1px 0px 0px rgba(0,0,0,0.05) inset,0px 2px 0px 0px rgba(0,0,0,0.1) inset;padding:8px 12px 6px 12px}.btn:visited{color:#fff}.btn:disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn-disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn-disabled:hover,.btn-disabled:focus,.btn-disabled:active{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn::-moz-focus-inner{padding:0;border:0}.btn-small{font-size:80%}.btn-info{background-color:#2980B9 !important}.btn-info:hover{background-color:#2e8ece !important}.btn-neutral{background-color:#f3f6f6 !important;color:#404040 !important}.btn-neutral:hover{background-color:#e5ebeb !important;color:#404040}.btn-neutral:visited{color:#404040 !important}.btn-success{background-color:#27AE60 !important}.btn-success:hover{background-color:#295 !important}.btn-danger{background-color:#E74C3C !important}.btn-danger:hover{background-color:#ea6153 !important}.btn-warning{background-color:#E67E22 !important}.btn-warning:hover{background-color:#e98b39 !important}.btn-invert{background-color:#222}.btn-invert:hover{background-color:#2f2f2f !important}.btn-link{background-color:transparent !important;color:#2980B9;box-shadow:none;border-color:transparent !important}.btn-link:hover{background-color:transparent !important;color:#409ad5 !important;box-shadow:none}.btn-link:active{background-color:transparent !important;color:#409ad5 !important;box-shadow:none}.btn-link:visited{color:#9B59B6}.wy-btn-group .btn,.wy-control .btn{vertical-align:middle}.wy-btn-group{margin-bottom:24px;*zoom:1}.wy-btn-group:before,.wy-btn-group:after{display:table;content:""}.wy-btn-group:after{clear:both}.wy-dropdown{position:relative;display:inline-block}.wy-dropdown-active .wy-dropdown-menu{display:block}.wy-dropdown-menu{position:absolute;left:0;display:none;float:left;top:100%;min-width:100%;background:#fcfcfc;z-index:100;border:solid 1px #cfd7dd;box-shadow:0 2px 2px 0 rgba(0,0,0,0.1);padding:12px}.wy-dropdown-menu>dd>a{display:block;clear:both;color:#404040;white-space:nowrap;font-size:90%;padding:0 12px;cursor:pointer}.wy-dropdown-menu>dd>a:hover{background:#2980B9;color:#fff}.wy-dropdown-menu>dd.divider{border-top:solid 1px #cfd7dd;margin:6px 0}.wy-dropdown-menu>dd.search{padding-bottom:12px}.wy-dropdown-menu>dd.search input[type="search"]{width:100%}.wy-dropdown-menu>dd.call-to-action{background:#e3e3e3;text-transform:uppercase;font-weight:500;font-size:80%}.wy-dropdown-menu>dd.call-to-action:hover{background:#e3e3e3}.wy-dropdown-menu>dd.call-to-action .btn{color:#fff}.wy-dropdown.wy-dropdown-up .wy-dropdown-menu{bottom:100%;top:auto;left:auto;right:0}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu{background:#fcfcfc;margin-top:2px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a{padding:6px 12px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a:hover{background:#2980B9;color:#fff}.wy-dropdown.wy-dropdown-left .wy-dropdown-menu{right:0;left:auto;text-align:right}.wy-dropdown-arrow:before{content:" ";border-bottom:5px solid #f5f5f5;border-left:5px solid transparent;border-right:5px solid transparent;position:absolute;display:block;top:-4px;left:50%;margin-left:-3px}.wy-dropdown-arrow.wy-dropdown-arrow-left:before{left:11px}.wy-form-stacked select{display:block}.wy-form-aligned input,.wy-form-aligned textarea,.wy-form-aligned select,.wy-form-aligned .wy-help-inline,.wy-form-aligned label{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-form-aligned .wy-control-group>label{display:inline-block;vertical-align:middle;width:10em;margin:6px 12px 0 0;float:left}.wy-form-aligned .wy-control{float:left}.wy-form-aligned .wy-control label{display:block}.wy-form-aligned .wy-control select{margin-top:6px}fieldset{border:0;margin:0;padding:0}legend{display:block;width:100%;border:0;padding:0;white-space:normal;margin-bottom:24px;font-size:150%;*margin-left:-7px}label{display:block;margin:0 0 .3125em 0;color:#333;font-size:90%}input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}.wy-control-group{margin-bottom:24px;*zoom:1;max-width:68em;margin-left:auto;margin-right:auto;*zoom:1}.wy-control-group:before,.wy-control-group:after{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group:before,.wy-control-group:after{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group.wy-control-group-required>label:after{content:" *";color:#E74C3C}.wy-control-group .wy-form-full,.wy-control-group .wy-form-halves,.wy-control-group .wy-form-thirds{padding-bottom:12px}.wy-control-group .wy-form-full select,.wy-control-group .wy-form-halves select,.wy-control-group .wy-form-thirds select{width:100%}.wy-control-group .wy-form-full input[type="text"],.wy-control-group .wy-form-full input[type="password"],.wy-control-group .wy-form-full input[type="email"],.wy-control-group .wy-form-full input[type="url"],.wy-control-group .wy-form-full input[type="date"],.wy-control-group .wy-form-full input[type="month"],.wy-control-group .wy-form-full input[type="time"],.wy-control-group .wy-form-full input[type="datetime"],.wy-control-group .wy-form-full input[type="datetime-local"],.wy-control-group .wy-form-full input[type="week"],.wy-control-group .wy-form-full input[type="number"],.wy-control-group .wy-form-full input[type="search"],.wy-control-group .wy-form-full input[type="tel"],.wy-control-group .wy-form-full input[type="color"],.wy-control-group .wy-form-halves input[type="text"],.wy-control-group .wy-form-halves input[type="password"],.wy-control-group .wy-form-halves input[type="email"],.wy-control-group .wy-form-halves input[type="url"],.wy-control-group .wy-form-halves input[type="date"],.wy-control-group .wy-form-halves input[type="month"],.wy-control-group .wy-form-halves input[type="time"],.wy-control-group .wy-form-halves input[type="datetime"],.wy-control-group .wy-form-halves input[type="datetime-local"],.wy-control-group .wy-form-halves input[type="week"],.wy-control-group .wy-form-halves input[type="number"],.wy-control-group .wy-form-halves input[type="search"],.wy-control-group .wy-form-halves input[type="tel"],.wy-control-group .wy-form-halves input[type="color"],.wy-control-group .wy-form-thirds input[type="text"],.wy-control-group .wy-form-thirds input[type="password"],.wy-control-group .wy-form-thirds input[type="email"],.wy-control-group .wy-form-thirds input[type="url"],.wy-control-group .wy-form-thirds input[type="date"],.wy-control-group .wy-form-thirds input[type="month"],.wy-control-group .wy-form-thirds input[type="time"],.wy-control-group .wy-form-thirds input[type="datetime"],.wy-control-group .wy-form-thirds input[type="datetime-local"],.wy-control-group .wy-form-thirds input[type="week"],.wy-control-group .wy-form-thirds input[type="number"],.wy-control-group .wy-form-thirds input[type="search"],.wy-control-group .wy-form-thirds input[type="tel"],.wy-control-group .wy-form-thirds input[type="color"]{width:100%}.wy-control-group .wy-form-full{float:left;display:block;margin-right:2.3576515979%;width:100%;margin-right:0}.wy-control-group .wy-form-full:last-child{margin-right:0}.wy-control-group .wy-form-halves{float:left;display:block;margin-right:2.3576515979%;width:48.821174201%}.wy-control-group .wy-form-halves:last-child{margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(2n){margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(2n+1){clear:left}.wy-control-group .wy-form-thirds{float:left;display:block;margin-right:2.3576515979%;width:31.7615656014%}.wy-control-group .wy-form-thirds:last-child{margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n){margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n+1){clear:left}.wy-control-group.wy-control-group-no-input .wy-control{margin:6px 0 0 0;font-size:90%}.wy-control-no-input{display:inline-block;margin:6px 0 0 0;font-size:90%}.wy-control-group.fluid-input input[type="text"],.wy-control-group.fluid-input input[type="password"],.wy-control-group.fluid-input input[type="email"],.wy-control-group.fluid-input input[type="url"],.wy-control-group.fluid-input input[type="date"],.wy-control-group.fluid-input input[type="month"],.wy-control-group.fluid-input input[type="time"],.wy-control-group.fluid-input input[type="datetime"],.wy-control-group.fluid-input input[type="datetime-local"],.wy-control-group.fluid-input input[type="week"],.wy-control-group.fluid-input input[type="number"],.wy-control-group.fluid-input input[type="search"],.wy-control-group.fluid-input input[type="tel"],.wy-control-group.fluid-input input[type="color"]{width:100%}.wy-form-message-inline{display:inline-block;padding-left:.3em;color:#666;vertical-align:middle;font-size:90%}.wy-form-message{display:block;color:#999;font-size:70%;margin-top:.3125em;font-style:italic}.wy-form-message p{font-size:inherit;font-style:italic;margin-bottom:6px}.wy-form-message p:last-child{margin-bottom:0}input{line-height:normal}input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;*overflow:visible}input[type="text"],input[type="password"],input[type="email"],input[type="url"],input[type="date"],input[type="month"],input[type="time"],input[type="datetime"],input[type="datetime-local"],input[type="week"],input[type="number"],input[type="search"],input[type="tel"],input[type="color"]{-webkit-appearance:none;padding:6px;display:inline-block;border:1px solid #ccc;font-size:80%;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;box-shadow:inset 0 1px 3px #ddd;border-radius:0;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}input[type="datetime-local"]{padding:.34375em .625em}input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0;margin-right:.3125em;*height:13px;*width:13px}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}input[type="text"]:focus,input[type="password"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus{outline:0;outline:thin dotted \9;border-color:#333}input.no-focus:focus{border-color:#ccc !important}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:1px auto #129FEA}input[type="text"][disabled],input[type="password"][disabled],input[type="email"][disabled],input[type="url"][disabled],input[type="date"][disabled],input[type="month"][disabled],input[type="time"][disabled],input[type="datetime"][disabled],input[type="datetime-local"][disabled],input[type="week"][disabled],input[type="number"][disabled],input[type="search"][disabled],input[type="tel"][disabled],input[type="color"][disabled]{cursor:not-allowed;background-color:#fafafa}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#E74C3C;border:1px solid #E74C3C}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#E74C3C}input[type="file"]:focus:invalid:focus,input[type="radio"]:focus:invalid:focus,input[type="checkbox"]:focus:invalid:focus{outline-color:#E74C3C}input.wy-input-large{padding:12px;font-size:100%}textarea{overflow:auto;vertical-align:top;width:100%;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif}select,textarea{padding:.5em .625em;display:inline-block;border:1px solid #ccc;font-size:80%;box-shadow:inset 0 1px 3px #ddd;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}select{border:1px solid #ccc;background-color:#fff}select[multiple]{height:auto}select:focus,textarea:focus{outline:0}select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#fafafa}input[type="radio"][disabled],input[type="checkbox"][disabled]{cursor:not-allowed}.wy-checkbox,.wy-radio{margin:6px 0;color:#404040;display:block}.wy-checkbox input,.wy-radio input{vertical-align:baseline}.wy-form-message-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-input-prefix,.wy-input-suffix{white-space:nowrap;padding:6px}.wy-input-prefix .wy-input-context,.wy-input-suffix .wy-input-context{line-height:27px;padding:0 8px;display:inline-block;font-size:80%;background-color:#f3f6f6;border:solid 1px #ccc;color:#999}.wy-input-suffix .wy-input-context{border-left:0}.wy-input-prefix .wy-input-context{border-right:0}.wy-switch{position:relative;display:block;height:24px;margin-top:12px;cursor:pointer}.wy-switch:before{position:absolute;content:"";display:block;left:0;top:0;width:36px;height:12px;border-radius:4px;background:#ccc;-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.wy-switch:after{position:absolute;content:"";display:block;width:18px;height:18px;border-radius:4px;background:#999;left:-3px;top:-3px;-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.wy-switch span{position:absolute;left:48px;display:block;font-size:12px;color:#ccc;line-height:1}.wy-switch.active:before{background:#1e8449}.wy-switch.active:after{left:24px;background:#27AE60}.wy-switch.disabled{cursor:not-allowed;opacity:.8}.wy-control-group.wy-control-group-error .wy-form-message,.wy-control-group.wy-control-group-error>label{color:#E74C3C}.wy-control-group.wy-control-group-error input[type="text"],.wy-control-group.wy-control-group-error input[type="password"],.wy-control-group.wy-control-group-error input[type="email"],.wy-control-group.wy-control-group-error input[type="url"],.wy-control-group.wy-control-group-error input[type="date"],.wy-control-group.wy-control-group-error input[type="month"],.wy-control-group.wy-control-group-error input[type="time"],.wy-control-group.wy-control-group-error input[type="datetime"],.wy-control-group.wy-control-group-error input[type="datetime-local"],.wy-control-group.wy-control-group-error input[type="week"],.wy-control-group.wy-control-group-error input[type="number"],.wy-control-group.wy-control-group-error input[type="search"],.wy-control-group.wy-control-group-error input[type="tel"],.wy-control-group.wy-control-group-error input[type="color"]{border:solid 1px #E74C3C}.wy-control-group.wy-control-group-error textarea{border:solid 1px #E74C3C}.wy-inline-validate{white-space:nowrap}.wy-inline-validate .wy-input-context{padding:.5em .625em;display:inline-block;font-size:80%}.wy-inline-validate.wy-inline-validate-success .wy-input-context{color:#27AE60}.wy-inline-validate.wy-inline-validate-danger .wy-input-context{color:#E74C3C}.wy-inline-validate.wy-inline-validate-warning .wy-input-context{color:#E67E22}.wy-inline-validate.wy-inline-validate-info .wy-input-context{color:#2980B9}.rotate-90{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.rotate-180{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.rotate-270{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.mirror{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1);-ms-transform:scaleX(-1);-o-transform:scaleX(-1);transform:scaleX(-1)}.mirror.rotate-90{-webkit-transform:scaleX(-1) rotate(90deg);-moz-transform:scaleX(-1) rotate(90deg);-ms-transform:scaleX(-1) rotate(90deg);-o-transform:scaleX(-1) rotate(90deg);transform:scaleX(-1) rotate(90deg)}.mirror.rotate-180{-webkit-transform:scaleX(-1) rotate(180deg);-moz-transform:scaleX(-1) rotate(180deg);-ms-transform:scaleX(-1) rotate(180deg);-o-transform:scaleX(-1) rotate(180deg);transform:scaleX(-1) rotate(180deg)}.mirror.rotate-270{-webkit-transform:scaleX(-1) rotate(270deg);-moz-transform:scaleX(-1) rotate(270deg);-ms-transform:scaleX(-1) rotate(270deg);-o-transform:scaleX(-1) rotate(270deg);transform:scaleX(-1) rotate(270deg)}@media only screen and (max-width: 480px){.wy-form button[type="submit"]{margin:.7em 0 0}.wy-form input[type="text"],.wy-form input[type="password"],.wy-form input[type="email"],.wy-form input[type="url"],.wy-form input[type="date"],.wy-form input[type="month"],.wy-form input[type="time"],.wy-form input[type="datetime"],.wy-form input[type="datetime-local"],.wy-form input[type="week"],.wy-form input[type="number"],.wy-form input[type="search"],.wy-form input[type="tel"],.wy-form input[type="color"]{margin-bottom:.3em;display:block}.wy-form label{margin-bottom:.3em;display:block}.wy-form input[type="password"],.wy-form input[type="email"],.wy-form input[type="url"],.wy-form input[type="date"],.wy-form input[type="month"],.wy-form input[type="time"],.wy-form input[type="datetime"],.wy-form input[type="datetime-local"],.wy-form input[type="week"],.wy-form input[type="number"],.wy-form input[type="search"],.wy-form input[type="tel"],.wy-form input[type="color"]{margin-bottom:0}.wy-form-aligned .wy-control-group label{margin-bottom:.3em;text-align:left;display:block;width:100%}.wy-form-aligned .wy-control{margin:1.5em 0 0 0}.wy-form .wy-help-inline,.wy-form-message-inline,.wy-form-message{display:block;font-size:80%;padding:6px 0}}@media screen and (max-width: 768px){.tablet-hide{display:none}}@media screen and (max-width: 480px){.mobile-hide{display:none}}.float-left{float:left}.float-right{float:right}.full-width{width:100%}.wy-table,.rst-content table.docutils,.rst-content table.field-list{border-collapse:collapse;border-spacing:0;empty-cells:show;margin-bottom:24px}.wy-table caption,.rst-content table.docutils caption,.rst-content table.field-list caption{color:#000;font:italic 85%/1 arial,sans-serif;padding:1em 0;text-align:center}.wy-table td,.rst-content table.docutils td,.rst-content table.field-list td,.wy-table th,.rst-content table.docutils th,.rst-content table.field-list th{font-size:90%;margin:0;overflow:visible;padding:8px 16px}.wy-table td:first-child,.rst-content table.docutils td:first-child,.rst-content table.field-list td:first-child,.wy-table th:first-child,.rst-content table.docutils th:first-child,.rst-content table.field-list th:first-child{border-left-width:0}.wy-table thead,.rst-content table.docutils thead,.rst-content table.field-list thead{color:#000;text-align:left;vertical-align:bottom;white-space:nowrap}.wy-table thead th,.rst-content table.docutils thead th,.rst-content table.field-list thead th{font-weight:bold;border-bottom:solid 2px #e1e4e5}.wy-table td,.rst-content table.docutils td,.rst-content table.field-list td{background-color:transparent;vertical-align:middle}.wy-table td p,.rst-content table.docutils td p,.rst-content table.field-list td p{line-height:18px}.wy-table td p:last-child,.rst-content table.docutils td p:last-child,.rst-content table.field-list td p:last-child{margin-bottom:0}.wy-table .wy-table-cell-min,.rst-content table.docutils .wy-table-cell-min,.rst-content table.field-list .wy-table-cell-min{width:1%;padding-right:0}.wy-table .wy-table-cell-min input[type=checkbox],.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox],.wy-table .wy-table-cell-min input[type=checkbox],.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox]{margin:0}.wy-table-secondary{color:gray;font-size:90%}.wy-table-tertiary{color:gray;font-size:80%}.wy-table-odd td,.wy-table-striped tr:nth-child(2n-1) td,.rst-content table.docutils:not(.field-list) tr:nth-child(2n-1) td{background-color:#f3f6f6}.wy-table-backed{background-color:#f3f6f6}.wy-table-bordered-all,.rst-content table.docutils{border:1px solid #e1e4e5}.wy-table-bordered-all td,.rst-content table.docutils td{border-bottom:1px solid #e1e4e5;border-left:1px solid #e1e4e5}.wy-table-bordered-all tbody>tr:last-child td,.rst-content table.docutils tbody>tr:last-child td{border-bottom-width:0}.wy-table-bordered{border:1px solid #e1e4e5}.wy-table-bordered-rows td{border-bottom:1px solid #e1e4e5}.wy-table-bordered-rows tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal td,.wy-table-horizontal th{border-width:0 0 1px 0;border-bottom:1px solid #e1e4e5}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-responsive{margin-bottom:24px;max-width:100%;overflow:auto}.wy-table-responsive table{margin-bottom:0 !important}.wy-table-responsive table td,.wy-table-responsive table th{white-space:nowrap}a{color:#2980B9;text-decoration:none;cursor:pointer}a:hover{color:#3091d1}a:visited{color:#9B59B6}html{height:100%;overflow-x:hidden}body{font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;font-weight:normal;color:#404040;min-height:100%;overflow-x:hidden;background:#edf0f2}.wy-text-left{text-align:left}.wy-text-center{text-align:center}.wy-text-right{text-align:right}.wy-text-large{font-size:120%}.wy-text-normal{font-size:100%}.wy-text-small,small{font-size:80%}.wy-text-strike{text-decoration:line-through}.wy-text-warning{color:#E67E22 !important}a.wy-text-warning:hover{color:#eb9950 !important}.wy-text-info{color:#2980B9 !important}a.wy-text-info:hover{color:#409ad5 !important}.wy-text-success{color:#27AE60 !important}a.wy-text-success:hover{color:#36d278 !important}.wy-text-danger{color:#E74C3C !important}a.wy-text-danger:hover{color:#ed7669 !important}.wy-text-neutral{color:#404040 !important}a.wy-text-neutral:hover{color:#595959 !important}h1,h2,.rst-content .toctree-wrapper p.caption,h3,h4,h5,h6,legend{margin-top:0;font-weight:700;font-family:"Roboto Slab","ff-tisa-web-pro","Georgia",Arial,sans-serif}p{line-height:24px;margin:0;font-size:16px;margin-bottom:24px}h1{font-size:175%}h2,.rst-content .toctree-wrapper p.caption{font-size:150%}h3{font-size:125%}h4{font-size:115%}h5{font-size:110%}h6{font-size:100%}hr{display:block;height:1px;border:0;border-top:1px solid #e1e4e5;margin:24px 0;padding:0}code,.rst-content tt,.rst-content code{white-space:nowrap;max-width:100%;background:#fff;border:solid 1px #e1e4e5;font-size:75%;padding:0 5px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;color:#E74C3C;overflow-x:auto}code.code-large,.rst-content tt.code-large{font-size:90%}.wy-plain-list-disc,.rst-content .section ul,.rst-content .toctree-wrapper ul,article ul{list-style:disc;line-height:24px;margin-bottom:24px}.wy-plain-list-disc li,.rst-content .section ul li,.rst-content .toctree-wrapper ul li,article ul li{list-style:disc;margin-left:24px}.wy-plain-list-disc li p:last-child,.rst-content .section ul li p:last-child,.rst-content .toctree-wrapper ul li p:last-child,article ul li p:last-child{margin-bottom:0}.wy-plain-list-disc li ul,.rst-content .section ul li ul,.rst-content .toctree-wrapper ul li ul,article ul li ul{margin-bottom:0}.wy-plain-list-disc li li,.rst-content .section ul li li,.rst-content .toctree-wrapper ul li li,article ul li li{list-style:circle}.wy-plain-list-disc li li li,.rst-content .section ul li li li,.rst-content .toctree-wrapper ul li li li,article ul li li li{list-style:square}.wy-plain-list-disc li ol li,.rst-content .section ul li ol li,.rst-content .toctree-wrapper ul li ol li,article ul li ol li{list-style:decimal}.wy-plain-list-decimal,.rst-content .section ol,.rst-content ol.arabic,article ol{list-style:decimal;line-height:24px;margin-bottom:24px}.wy-plain-list-decimal li,.rst-content .section ol li,.rst-content ol.arabic li,article ol li{list-style:decimal;margin-left:24px}.wy-plain-list-decimal li p:last-child,.rst-content .section ol li p:last-child,.rst-content ol.arabic li p:last-child,article ol li p:last-child{margin-bottom:0}.wy-plain-list-decimal li ul,.rst-content .section ol li ul,.rst-content ol.arabic li ul,article ol li ul{margin-bottom:0}.wy-plain-list-decimal li ul li,.rst-content .section ol li ul li,.rst-content ol.arabic li ul li,article ol li ul li{list-style:disc}.wy-breadcrumbs{*zoom:1}.wy-breadcrumbs:before,.wy-breadcrumbs:after{display:table;content:""}.wy-breadcrumbs:after{clear:both}.wy-breadcrumbs li{display:inline-block}.wy-breadcrumbs li.wy-breadcrumbs-aside{float:right}.wy-breadcrumbs li a{display:inline-block;padding:5px}.wy-breadcrumbs li a:first-child{padding-left:0}.wy-breadcrumbs li code,.wy-breadcrumbs li .rst-content tt,.rst-content .wy-breadcrumbs li tt{padding:5px;border:none;background:none}.wy-breadcrumbs li code.literal,.wy-breadcrumbs li .rst-content tt.literal,.rst-content .wy-breadcrumbs li tt.literal{color:#404040}.wy-breadcrumbs-extra{margin-bottom:0;color:#b3b3b3;font-size:80%;display:inline-block}@media screen and (max-width: 480px){.wy-breadcrumbs-extra{display:none}.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}@media print{.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}.wy-affix{position:fixed;top:1.618em}.wy-menu a:hover{text-decoration:none}.wy-menu-horiz{*zoom:1}.wy-menu-horiz:before,.wy-menu-horiz:after{display:table;content:""}.wy-menu-horiz:after{clear:both}.wy-menu-horiz ul,.wy-menu-horiz li{display:inline-block}.wy-menu-horiz li:hover{background:rgba(255,255,255,0.1)}.wy-menu-horiz li.divide-left{border-left:solid 1px #404040}.wy-menu-horiz li.divide-right{border-right:solid 1px #404040}.wy-menu-horiz a{height:32px;display:inline-block;line-height:32px;padding:0 16px}.wy-menu-vertical{width:300px}.wy-menu-vertical header,.wy-menu-vertical p.caption{height:32px;display:inline-block;line-height:32px;padding:0 1.618em;margin-bottom:0;display:block;font-weight:bold;text-transform:uppercase;font-size:80%;white-space:nowrap}.wy-menu-vertical ul{margin-bottom:0}.wy-menu-vertical li.divide-top{border-top:solid 1px #404040}.wy-menu-vertical li.divide-bottom{border-bottom:solid 1px #404040}.wy-menu-vertical li.current{background:#e3e3e3}.wy-menu-vertical li.current a{color:gray;border-right:solid 1px #c9c9c9;padding:.4045em 2.427em}.wy-menu-vertical li.current a:hover{background:#d6d6d6}.wy-menu-vertical li code,.wy-menu-vertical li .rst-content tt,.rst-content .wy-menu-vertical li tt{border:none;background:inherit;color:inherit;padding-left:0;padding-right:0}.wy-menu-vertical li span.toctree-expand{display:block;float:left;margin-left:-1.2em;font-size:.8em;line-height:1.6em;color:#4d4d4d}.wy-menu-vertical li.on a,.wy-menu-vertical li.current>a{color:#404040;padding:.4045em 1.618em;font-weight:bold;position:relative;background:#fcfcfc;border:none;padding-left:1.618em -4px}.wy-menu-vertical li.on a:hover,.wy-menu-vertical li.current>a:hover{background:#fcfcfc}.wy-menu-vertical li.on a:hover span.toctree-expand,.wy-menu-vertical li.current>a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand{display:block;font-size:.8em;line-height:1.6em;color:#333}.wy-menu-vertical li.toctree-l1.current>a{border-bottom:solid 1px #c9c9c9;border-top:solid 1px #c9c9c9}.wy-menu-vertical li.toctree-l2 a,.wy-menu-vertical li.toctree-l3 a,.wy-menu-vertical li.toctree-l4 a{color:#404040}.wy-menu-vertical li.toctree-l1.current li.toctree-l2>ul,.wy-menu-vertical li.toctree-l2.current li.toctree-l3>ul{display:none}.wy-menu-vertical li.toctree-l1.current li.toctree-l2.current>ul,.wy-menu-vertical li.toctree-l2.current li.toctree-l3.current>ul{display:block}.wy-menu-vertical li.toctree-l2.current>a{background:#c9c9c9;padding:.4045em 2.427em}.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a{display:block;background:#c9c9c9;padding:.4045em 4.045em}.wy-menu-vertical li.toctree-l2 a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.toctree-l2 span.toctree-expand{color:#a3a3a3}.wy-menu-vertical li.toctree-l3{font-size:.9em}.wy-menu-vertical li.toctree-l3.current>a{background:#bdbdbd;padding:.4045em 4.045em}.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a{display:block;background:#bdbdbd;padding:.4045em 5.663em}.wy-menu-vertical li.toctree-l3 a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.toctree-l3 span.toctree-expand{color:#969696}.wy-menu-vertical li.toctree-l4{font-size:.9em}.wy-menu-vertical li.current ul{display:block}.wy-menu-vertical li ul{margin-bottom:0;display:none}.wy-menu-vertical li ul li a{margin-bottom:0;color:#d9d9d9;font-weight:normal}.wy-menu-vertical a{display:inline-block;line-height:18px;padding:.4045em 1.618em;display:block;position:relative;font-size:90%;color:#d9d9d9}.wy-menu-vertical a:hover{background-color:#4e4a4a;cursor:pointer}.wy-menu-vertical a:hover span.toctree-expand{color:#d9d9d9}.wy-menu-vertical a:active{background-color:#2980B9;cursor:pointer;color:#fff}.wy-menu-vertical a:active span.toctree-expand{color:#fff}.wy-side-nav-search{display:block;width:300px;padding:.809em;margin-bottom:.809em;z-index:200;background-color:#2980B9;text-align:center;padding:.809em;display:block;color:#fcfcfc;margin-bottom:.809em}.wy-side-nav-search input[type=text]{width:100%;border-radius:50px;padding:6px 12px;border-color:#2472a4}.wy-side-nav-search img{display:block;margin:auto auto .809em auto;height:45px;width:45px;background-color:#2980B9;padding:5px;border-radius:100%}.wy-side-nav-search>a,.wy-side-nav-search .wy-dropdown>a{color:#fcfcfc;font-size:100%;font-weight:bold;display:inline-block;padding:4px 6px;margin-bottom:.809em}.wy-side-nav-search>a:hover,.wy-side-nav-search .wy-dropdown>a:hover{background:rgba(255,255,255,0.1)}.wy-side-nav-search>a img.logo,.wy-side-nav-search .wy-dropdown>a img.logo{display:block;margin:0 auto;height:auto;width:auto;border-radius:0;max-width:100%;background:transparent}.wy-side-nav-search>a.icon img.logo,.wy-side-nav-search .wy-dropdown>a.icon img.logo{margin-top:.85em}.wy-side-nav-search>div.version{margin-top:-.4045em;margin-bottom:.809em;font-weight:normal;color:rgba(255,255,255,0.3)}.wy-nav .wy-menu-vertical header{color:#2980B9}.wy-nav .wy-menu-vertical a{color:#b3b3b3}.wy-nav .wy-menu-vertical a:hover{background-color:#2980B9;color:#fff}[data-menu-wrap]{-webkit-transition:all .2s ease-in;-moz-transition:all .2s ease-in;transition:all .2s ease-in;position:absolute;opacity:1;width:100%;opacity:0}[data-menu-wrap].move-center{left:0;right:auto;opacity:1}[data-menu-wrap].move-left{right:auto;left:-100%;opacity:0}[data-menu-wrap].move-right{right:-100%;left:auto;opacity:0}.wy-body-for-nav{background:#fcfcfc}.wy-grid-for-nav{position:absolute;width:100%;height:100%}.wy-nav-side{position:fixed;top:0;bottom:0;left:0;padding-bottom:2em;width:300px;overflow-x:hidden;overflow-y:hidden;min-height:100%;color:#9b9b9b;background:#343131;z-index:200}.wy-side-scroll{width:320px;position:relative;overflow-x:hidden;overflow-y:scroll;height:100%}.wy-nav-top{display:none;background:#2980B9;color:#fff;padding:.4045em .809em;position:relative;line-height:50px;text-align:center;font-size:100%;*zoom:1}.wy-nav-top:before,.wy-nav-top:after{display:table;content:""}.wy-nav-top:after{clear:both}.wy-nav-top a{color:#fff;font-weight:bold}.wy-nav-top img{margin-right:12px;height:45px;width:45px;background-color:#2980B9;padding:5px;border-radius:100%}.wy-nav-top i{font-size:30px;float:left;cursor:pointer;padding-top:inherit}.wy-nav-content-wrap{margin-left:300px;background:#fcfcfc;min-height:100%}.wy-nav-content{padding:1.618em 3.236em;height:100%;max-width:800px;margin:auto}.wy-body-mask{position:fixed;width:100%;height:100%;background:rgba(0,0,0,0.2);display:none;z-index:499}.wy-body-mask.on{display:block}footer{color:gray}footer p{margin-bottom:12px}footer span.commit code,footer span.commit .rst-content tt,.rst-content footer span.commit tt{padding:0px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;font-size:1em;background:none;border:none;color:gray}.rst-footer-buttons{*zoom:1}.rst-footer-buttons:before,.rst-footer-buttons:after{width:100%}.rst-footer-buttons:before,.rst-footer-buttons:after{display:table;content:""}.rst-footer-buttons:after{clear:both}.rst-breadcrumbs-buttons{margin-top:12px;*zoom:1}.rst-breadcrumbs-buttons:before,.rst-breadcrumbs-buttons:after{display:table;content:""}.rst-breadcrumbs-buttons:after{clear:both}#search-results .search li{margin-bottom:24px;border-bottom:solid 1px #e1e4e5;padding-bottom:24px}#search-results .search li:first-child{border-top:solid 1px #e1e4e5;padding-top:24px}#search-results .search li a{font-size:120%;margin-bottom:12px;display:inline-block}#search-results .context{color:gray;font-size:90%}@media screen and (max-width: 768px){.wy-body-for-nav{background:#fcfcfc}.wy-nav-top{display:block}.wy-nav-side{left:-300px}.wy-nav-side.shift{width:85%;left:0}.wy-side-scroll{width:auto}.wy-side-nav-search{width:auto}.wy-menu.wy-menu-vertical{width:auto}.wy-nav-content-wrap{margin-left:0}.wy-nav-content-wrap .wy-nav-content{padding:1.618em}.wy-nav-content-wrap.shift{position:fixed;min-width:100%;left:85%;top:0;height:100%;overflow:hidden}}@media screen and (min-width: 1100px){.wy-nav-content-wrap{background:rgba(0,0,0,0.05)}.wy-nav-content{margin:0;background:#fcfcfc}}@media print{.rst-versions,footer,.wy-nav-side{display:none}.wy-nav-content-wrap{margin-left:0}}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;z-index:400}.rst-versions a{color:#2980B9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27AE60;*zoom:1}.rst-versions .rst-current-version:before,.rst-versions .rst-current-version:after{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-versions .rst-current-version .fa,.rst-versions .rst-current-version .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .rst-versions .rst-current-version span.toctree-expand,.rst-versions .rst-current-version .rst-content .admonition-title,.rst-content .rst-versions .rst-current-version .admonition-title,.rst-versions .rst-current-version .rst-content h1 .headerlink,.rst-content h1 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h2 .headerlink,.rst-content h2 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h3 .headerlink,.rst-content h3 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h4 .headerlink,.rst-content h4 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h5 .headerlink,.rst-content h5 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h6 .headerlink,.rst-content h6 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content dl dt .headerlink,.rst-content dl dt .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content p.caption .headerlink,.rst-content p.caption .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content table>caption .headerlink,.rst-content table>caption .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content tt.download span:first-child,.rst-content tt.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .rst-content code.download span:first-child,.rst-content code.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .icon{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#E74C3C;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#F1C40F;color:#000}.rst-versions.shift-up{height:auto;max-height:100%}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:gray;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:solid 1px #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px}.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge .rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width: 768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}}.rst-content img{max-width:100%;height:auto}.rst-content div.figure{margin-bottom:24px}.rst-content div.figure p.caption{font-style:italic}.rst-content div.figure p:last-child.caption{margin-bottom:0px}.rst-content div.figure.align-center{text-align:center}.rst-content .section>img,.rst-content .section>a>img{margin-bottom:24px}.rst-content abbr[title]{text-decoration:none}.rst-content.style-external-links a.reference.external:after{font-family:FontAwesome;content:"";color:#b3b3b3;vertical-align:super;font-size:60%;margin:0 .2em}.rst-content blockquote{margin-left:24px;line-height:24px;margin-bottom:24px}.rst-content pre.literal-block{white-space:pre;margin:0;padding:12px 12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;display:block;overflow:auto}.rst-content pre.literal-block,.rst-content div[class^='highlight']{border:1px solid #e1e4e5;overflow-x:auto;margin:1px 0 24px 0}.rst-content pre.literal-block div[class^='highlight'],.rst-content div[class^='highlight'] div[class^='highlight']{padding:0px;border:none;margin:0}.rst-content div[class^='highlight'] td.code{width:100%}.rst-content .linenodiv pre{border-right:solid 1px #e6e9ea;margin:0;padding:12px 12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;user-select:none;pointer-events:none}.rst-content div[class^='highlight'] pre{white-space:pre;margin:0;padding:12px 12px;display:block;overflow:auto}.rst-content div[class^='highlight'] pre .hll{display:block;margin:0 -12px;padding:0 12px}.rst-content pre.literal-block,.rst-content div[class^='highlight'] pre,.rst-content .linenodiv pre{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;font-size:12px;line-height:normal}@media print{.rst-content .codeblock,.rst-content div[class^='highlight'],.rst-content div[class^='highlight'] pre{white-space:pre-wrap}}.rst-content .note .last,.rst-content .attention .last,.rst-content .caution .last,.rst-content .danger .last,.rst-content .error .last,.rst-content .hint .last,.rst-content .important .last,.rst-content .tip .last,.rst-content .warning .last,.rst-content .seealso .last,.rst-content .admonition-todo .last,.rst-content .admonition .last{margin-bottom:0}.rst-content .admonition-title:before{margin-right:4px}.rst-content .admonition table{border-color:rgba(0,0,0,0.1)}.rst-content .admonition table td,.rst-content .admonition table th{background:transparent !important;border-color:rgba(0,0,0,0.1) !important}.rst-content .section ol.loweralpha,.rst-content .section ol.loweralpha li{list-style:lower-alpha}.rst-content .section ol.upperalpha,.rst-content .section ol.upperalpha li{list-style:upper-alpha}.rst-content .section ol p,.rst-content .section ul p{margin-bottom:12px}.rst-content .section ol p:last-child,.rst-content .section ul p:last-child{margin-bottom:24px}.rst-content .line-block{margin-left:0px;margin-bottom:24px;line-height:24px}.rst-content .line-block .line-block{margin-left:24px;margin-bottom:0px}.rst-content .topic-title{font-weight:bold;margin-bottom:12px}.rst-content .toc-backref{color:#404040}.rst-content .align-right{float:right;margin:0px 0px 24px 24px}.rst-content .align-left{float:left;margin:0px 24px 24px 0px}.rst-content .align-center{margin:auto}.rst-content .align-center:not(table){display:block}.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content .toctree-wrapper p.caption .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink{visibility:hidden;font-size:14px}.rst-content h1 .headerlink:after,.rst-content h2 .headerlink:after,.rst-content .toctree-wrapper p.caption .headerlink:after,.rst-content h3 .headerlink:after,.rst-content h4 .headerlink:after,.rst-content h5 .headerlink:after,.rst-content h6 .headerlink:after,.rst-content dl dt .headerlink:after,.rst-content p.caption .headerlink:after,.rst-content table>caption .headerlink:after{content:"";font-family:FontAwesome}.rst-content h1:hover .headerlink:after,.rst-content h2:hover .headerlink:after,.rst-content .toctree-wrapper p.caption:hover .headerlink:after,.rst-content h3:hover .headerlink:after,.rst-content h4:hover .headerlink:after,.rst-content h5:hover .headerlink:after,.rst-content h6:hover .headerlink:after,.rst-content dl dt:hover .headerlink:after,.rst-content p.caption:hover .headerlink:after,.rst-content table>caption:hover .headerlink:after{visibility:visible}.rst-content table>caption .headerlink:after{font-size:12px}.rst-content .centered{text-align:center}.rst-content .sidebar{float:right;width:40%;display:block;margin:0 0 24px 24px;padding:24px;background:#f3f6f6;border:solid 1px #e1e4e5}.rst-content .sidebar p,.rst-content .sidebar ul,.rst-content .sidebar dl{font-size:90%}.rst-content .sidebar .last{margin-bottom:0}.rst-content .sidebar .sidebar-title{display:block;font-family:"Roboto Slab","ff-tisa-web-pro","Georgia",Arial,sans-serif;font-weight:bold;background:#e1e4e5;padding:6px 12px;margin:-24px;margin-bottom:24px;font-size:100%}.rst-content .highlighted{background:#F1C40F;display:inline-block;font-weight:bold;padding:0 6px}.rst-content .footnote-reference,.rst-content .citation-reference{vertical-align:baseline;position:relative;top:-0.4em;line-height:0;font-size:90%}.rst-content table.docutils.citation,.rst-content table.docutils.footnote{background:none;border:none;color:gray}.rst-content table.docutils.citation td,.rst-content table.docutils.citation tr,.rst-content table.docutils.footnote td,.rst-content table.docutils.footnote tr{border:none;background-color:transparent !important;white-space:normal}.rst-content table.docutils.citation td.label,.rst-content table.docutils.footnote td.label{padding-left:0;padding-right:0;vertical-align:top}.rst-content table.docutils.citation tt,.rst-content table.docutils.citation code,.rst-content table.docutils.footnote tt,.rst-content table.docutils.footnote code{color:#555}.rst-content .wy-table-responsive.citation,.rst-content .wy-table-responsive.footnote{margin-bottom:0}.rst-content .wy-table-responsive.citation+:not(.citation),.rst-content .wy-table-responsive.footnote+:not(.footnote){margin-top:24px}.rst-content .wy-table-responsive.citation:last-child,.rst-content .wy-table-responsive.footnote:last-child{margin-bottom:24px}.rst-content table.docutils th{border-color:#e1e4e5}.rst-content table.docutils td .last,.rst-content table.docutils td .last :last-child{margin-bottom:0}.rst-content table.field-list{border:none}.rst-content table.field-list td{border:none}.rst-content table.field-list td>strong{display:inline-block}.rst-content table.field-list .field-name{padding-right:10px;text-align:left;white-space:nowrap}.rst-content table.field-list .field-body{text-align:left}.rst-content tt,.rst-content tt,.rst-content code{color:#000;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;padding:2px 5px}.rst-content tt big,.rst-content tt em,.rst-content tt big,.rst-content code big,.rst-content tt em,.rst-content code em{font-size:100% !important;line-height:normal}.rst-content tt.literal,.rst-content tt.literal,.rst-content code.literal{color:#E74C3C}.rst-content tt.xref,a .rst-content tt,.rst-content tt.xref,.rst-content code.xref,a .rst-content tt,a .rst-content code{font-weight:bold;color:#404040}.rst-content pre,.rst-content kbd,.rst-content samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace}.rst-content a tt,.rst-content a tt,.rst-content a code{color:#2980B9}.rst-content dl{margin-bottom:24px}.rst-content dl dt{font-weight:bold;margin-bottom:12px}.rst-content dl p,.rst-content dl table,.rst-content dl ul,.rst-content dl ol{margin-bottom:12px !important}.rst-content dl dd{margin:0 0 12px 24px;line-height:24px}.rst-content dl:not(.docutils){margin-bottom:24px}.rst-content dl:not(.docutils) dt{display:table;margin:6px 0;font-size:90%;line-height:normal;background:#e7f2fa;color:#2980B9;border-top:solid 3px #6ab0de;padding:6px;position:relative}.rst-content dl:not(.docutils) dt:before{color:#6ab0de}.rst-content dl:not(.docutils) dt .headerlink{color:#404040;font-size:100% !important}.rst-content dl:not(.docutils) dl dt{margin-bottom:6px;border:none;border-left:solid 3px #ccc;background:#f0f0f0;color:#555}.rst-content dl:not(.docutils) dl dt .headerlink{color:#404040;font-size:100% !important}.rst-content dl:not(.docutils) dt:first-child{margin-top:0}.rst-content dl:not(.docutils) tt,.rst-content dl:not(.docutils) tt,.rst-content dl:not(.docutils) code{font-weight:bold}.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) tt.descclassname,.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) code.descname,.rst-content dl:not(.docutils) tt.descclassname,.rst-content dl:not(.docutils) code.descclassname{background-color:transparent;border:none;padding:0;font-size:100% !important}.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) code.descname{font-weight:bold}.rst-content dl:not(.docutils) .optional{display:inline-block;padding:0 4px;color:#000;font-weight:bold}.rst-content dl:not(.docutils) .property{display:inline-block;padding-right:8px}.rst-content .viewcode-link,.rst-content .viewcode-back{display:inline-block;color:#27AE60;font-size:80%;padding-left:24px}.rst-content .viewcode-back{display:block;float:right}.rst-content p.rubric{margin-bottom:12px;font-weight:bold}.rst-content tt.download,.rst-content code.download{background:inherit;padding:inherit;font-weight:normal;font-family:inherit;font-size:inherit;color:inherit;border:inherit;white-space:inherit}.rst-content tt.download span:first-child,.rst-content code.download span:first-child{-webkit-font-smoothing:subpixel-antialiased}.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before{margin-right:4px}.rst-content .guilabel{border:1px solid #7fbbe3;background:#e7f2fa;font-size:80%;font-weight:700;border-radius:4px;padding:2.4px 6px;margin:auto 2px}.rst-content .versionmodified{font-style:italic}@media screen and (max-width: 480px){.rst-content .sidebar{width:100%}}span[id*='MathJax-Span']{color:#404040}.math{text-align:center}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-regular.eot");src:url("../fonts/Lato/lato-regular.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-regular.woff2") format("woff2"),url("../fonts/Lato/lato-regular.woff") format("woff"),url("../fonts/Lato/lato-regular.ttf") format("truetype");font-weight:400;font-style:normal}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-bold.eot");src:url("../fonts/Lato/lato-bold.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-bold.woff2") format("woff2"),url("../fonts/Lato/lato-bold.woff") format("woff"),url("../fonts/Lato/lato-bold.ttf") format("truetype");font-weight:700;font-style:normal}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-bolditalic.eot");src:url("../fonts/Lato/lato-bolditalic.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-bolditalic.woff2") format("woff2"),url("../fonts/Lato/lato-bolditalic.woff") format("woff"),url("../fonts/Lato/lato-bolditalic.ttf") format("truetype");font-weight:700;font-style:italic}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-italic.eot");src:url("../fonts/Lato/lato-italic.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-italic.woff2") format("woff2"),url("../fonts/Lato/lato-italic.woff") format("woff"),url("../fonts/Lato/lato-italic.ttf") format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"Roboto Slab";font-style:normal;font-weight:400;src:url("../fonts/RobotoSlab/roboto-slab.eot");src:url("../fonts/RobotoSlab/roboto-slab-v7-regular.eot?#iefix") format("embedded-opentype"),url("../fonts/RobotoSlab/roboto-slab-v7-regular.woff2") format("woff2"),url("../fonts/RobotoSlab/roboto-slab-v7-regular.woff") format("woff"),url("../fonts/RobotoSlab/roboto-slab-v7-regular.ttf") format("truetype")}@font-face{font-family:"Roboto Slab";font-style:normal;font-weight:700;src:url("../fonts/RobotoSlab/roboto-slab-v7-bold.eot");src:url("../fonts/RobotoSlab/roboto-slab-v7-bold.eot?#iefix") format("embedded-opentype"),url("../fonts/RobotoSlab/roboto-slab-v7-bold.woff2") format("woff2"),url("../fonts/RobotoSlab/roboto-slab-v7-bold.woff") format("woff"),url("../fonts/RobotoSlab/roboto-slab-v7-bold.ttf") format("truetype")}
diff --git a/_build/_themes/sphinx_rtd_theme/static/fonts/FontAwesome.otf b/_build/_themes/sphinx_rtd_theme/static/fonts/FontAwesome.otf
deleted file mode 100755
index 401ec0f36e4..00000000000
Binary files a/_build/_themes/sphinx_rtd_theme/static/fonts/FontAwesome.otf and /dev/null differ
diff --git a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.eot b/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.eot
deleted file mode 100755
index e9f60ca953f..00000000000
Binary files a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.eot and /dev/null differ
diff --git a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.svg b/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.svg
deleted file mode 100755
index 855c845e538..00000000000
--- a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.svg
+++ /dev/null
@@ -1,2671 +0,0 @@
-
-
-
-
-Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016
- By ,,,
-Copyright Dave Gandy 2016. All rights reserved.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.ttf b/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.ttf
deleted file mode 100755
index 35acda2fa11..00000000000
Binary files a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.ttf and /dev/null differ
diff --git a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.woff b/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.woff
deleted file mode 100755
index 400014a4b06..00000000000
Binary files a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.woff and /dev/null differ
diff --git a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.woff2 b/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.woff2
deleted file mode 100755
index 4d13fc60404..00000000000
Binary files a/_build/_themes/sphinx_rtd_theme/static/fonts/fontawesome-webfont.woff2 and /dev/null differ
diff --git a/_build/_themes/sphinx_rtd_theme/static/js/modernizr.min.js b/_build/_themes/sphinx_rtd_theme/static/js/modernizr.min.js
deleted file mode 100755
index f65d4797478..00000000000
--- a/_build/_themes/sphinx_rtd_theme/static/js/modernizr.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/* Modernizr 2.6.2 (Custom Build) | MIT & BSD
- * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-addtest-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load
- */
-;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d',a,""].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML=" ",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,e.prefixed=function(a,b,c){return b?J(a,b,c):J(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f "),n("table.docutils.footnote").wrap(""),n("table.docutils.citation").wrap("
"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each(function(){var i=n(this);expand=n(' '),expand.on("click",function(n){return e.toggleCurrent(i),n.stopPropagation(),!1}),i.prepend(expand)})},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),i=e.find('[href="'+n+'"]');if(0===i.length){var t=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(i=e.find('[href="#'+t.attr("id")+'"]')).length&&(i=e.find('[href="#"]'))}i.length>0&&($(".wy-menu-vertical .current").removeClass("current"),i.addClass("current"),i.closest("li.toctree-l1").addClass("current"),i.closest("li.toctree-l1").parent().addClass("current"),i.closest("li.toctree-l1").addClass("current"),i.closest("li.toctree-l2").addClass("current"),i.closest("li.toctree-l3").addClass("current"),i.closest("li.toctree-l4").addClass("current"))}catch(o){console.log("Error expanding nav for anchor",o)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,i=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(i),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",function(){this.linkScroll=!1})},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current"),e.siblings().find("li.current").removeClass("current"),e.find("> ul li.current").removeClass("current"),e.toggleClass("current")}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:e.exports.ThemeNav,StickyNav:e.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],i=0;i
-
- Read the Docs
- v: {{ current_version }}
-
-
-
-
-{% endif %}
-
diff --git a/_build/build.php b/_build/build.php
new file mode 100755
index 00000000000..b684700a848
--- /dev/null
+++ b/_build/build.php
@@ -0,0 +1,91 @@
+#!/usr/bin/env php
+register('build-docs')
+ ->addOption('generate-fjson-files', null, InputOption::VALUE_NONE, 'Use this option to generate docs both in HTML and JSON formats')
+ ->addOption('disable-cache', null, InputOption::VALUE_NONE, 'Use this option to force a full regeneration of all doc contents')
+ ->setCode(function(InputInterface $input, OutputInterface $output) {
+ // the doc building app doesn't work on Windows
+ if ('\\' === DIRECTORY_SEPARATOR) {
+ $output->writeln('ERROR: The application that builds Symfony Docs does not support Windows. You can try using a Linux distribution via WSL (Windows Subsystem for Linux). ');
+
+ return 1;
+ }
+
+ $io = new SymfonyStyle($input, $output);
+ $io->text('Building all Symfony Docs...');
+
+ $outputDir = __DIR__.'/output';
+ $buildConfig = (new BuildConfig())
+ ->setSymfonyVersion('7.1')
+ ->setContentDir(__DIR__.'/..')
+ ->setOutputDir($outputDir)
+ ->setImagesDir(__DIR__.'/output/_images')
+ ->setImagesPublicPrefix('_images')
+ ->setTheme('rtd')
+ ;
+
+ $buildConfig->setExcludedPaths(['.github/', '_build/']);
+
+ if (!$generateJsonFiles = $input->getOption('generate-fjson-files')) {
+ $buildConfig->disableJsonFileGeneration();
+ }
+
+ if ($isCacheDisabled = $input->getOption('disable-cache')) {
+ $buildConfig->disableBuildCache();
+ }
+
+ $io->comment(sprintf('cache: %s / output file type(s): %s', $isCacheDisabled ? 'disabled' : 'enabled', $generateJsonFiles ? 'HTML and JSON' : 'HTML'));
+ if (!$isCacheDisabled) {
+ $io->comment('Tip: add the --disable-cache option to this command to force the re-build of all docs.');
+ }
+
+ $result = (new DocBuilder())->build($buildConfig);
+
+ if ($result->isSuccessful()) {
+ // fix assets URLs to make them absolute (otherwise, they don't work in subdirectories)
+ $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($outputDir));
+
+ foreach (new RegexIterator($iterator, '/^.+\.html$/i', RegexIterator::GET_MATCH) as $match) {
+ $htmlFilePath = array_shift($match);
+ $htmlContents = file_get_contents($htmlFilePath);
+
+ $htmlRelativeFilePath = str_replace($outputDir.'/', '', $htmlFilePath);
+ $subdirLevel = substr_count($htmlRelativeFilePath, '/');
+ $baseHref = str_repeat('../', $subdirLevel);
+
+ $htmlContents = str_replace('', ' ', $htmlContents);
+ $htmlContents = str_replace(' success(sprintf("The Symfony Docs were successfully built at %s", realpath($outputDir)));
+ } else {
+ $io->error(sprintf("There were some errors while building the docs:\n\n%s\n", $result->getErrorTrace()));
+ $io->newLine();
+ $io->comment('Tip: you can add the -v, -vv or -vvv flags to this command to get debug information.');
+
+ return 1;
+ }
+
+ return 0;
+ })
+ ->getApplication()
+ ->setDefaultCommand('build-docs', true)
+ ->run();
diff --git a/_build/composer.json b/_build/composer.json
new file mode 100644
index 00000000000..f77976b10f4
--- /dev/null
+++ b/_build/composer.json
@@ -0,0 +1,22 @@
+{
+ "minimum-stability": "dev",
+ "prefer-stable": true,
+ "config": {
+ "platform": {
+ "php": "8.3"
+ },
+ "preferred-install": {
+ "*": "dist"
+ },
+ "sort-packages": true,
+ "allow-plugins": {
+ "symfony/flex": true
+ }
+ },
+ "require": {
+ "php": ">=8.3",
+ "symfony/console": "^6.2",
+ "symfony/process": "^6.2",
+ "symfony-tools/docs-builder": "^0.27"
+ }
+}
diff --git a/_build/composer.lock b/_build/composer.lock
new file mode 100644
index 00000000000..b9a4646f8ae
--- /dev/null
+++ b/_build/composer.lock
@@ -0,0 +1,1792 @@
+{
+ "_readme": [
+ "This file locks the dependencies of your project to a known state",
+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
+ "This file is @generated automatically"
+ ],
+ "content-hash": "e38eca557458275428db96db370d2c74",
+ "packages": [
+ {
+ "name": "doctrine/event-manager",
+ "version": "2.0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/doctrine/event-manager.git",
+ "reference": "b680156fa328f1dfd874fd48c7026c41570b9c6e"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/doctrine/event-manager/zipball/b680156fa328f1dfd874fd48c7026c41570b9c6e",
+ "reference": "b680156fa328f1dfd874fd48c7026c41570b9c6e",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^8.1"
+ },
+ "conflict": {
+ "doctrine/common": "<2.9"
+ },
+ "require-dev": {
+ "doctrine/coding-standard": "^12",
+ "phpstan/phpstan": "^1.8.8",
+ "phpunit/phpunit": "^10.5",
+ "vimeo/psalm": "^5.24"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Doctrine\\Common\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Guilherme Blanco",
+ "email": "guilhermeblanco@gmail.com"
+ },
+ {
+ "name": "Roman Borschel",
+ "email": "roman@code-factory.org"
+ },
+ {
+ "name": "Benjamin Eberlei",
+ "email": "kontakt@beberlei.de"
+ },
+ {
+ "name": "Jonathan Wage",
+ "email": "jonwage@gmail.com"
+ },
+ {
+ "name": "Johannes Schmitt",
+ "email": "schmittjoh@gmail.com"
+ },
+ {
+ "name": "Marco Pivetta",
+ "email": "ocramius@gmail.com"
+ }
+ ],
+ "description": "The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.",
+ "homepage": "https://www.doctrine-project.org/projects/event-manager.html",
+ "keywords": [
+ "event",
+ "event dispatcher",
+ "event manager",
+ "event system",
+ "events"
+ ],
+ "support": {
+ "issues": "https://github.com/doctrine/event-manager/issues",
+ "source": "https://github.com/doctrine/event-manager/tree/2.0.1"
+ },
+ "funding": [
+ {
+ "url": "https://www.doctrine-project.org/sponsorship.html",
+ "type": "custom"
+ },
+ {
+ "url": "https://www.patreon.com/phpdoctrine",
+ "type": "patreon"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fevent-manager",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-05-22T20:47:39+00:00"
+ },
+ {
+ "name": "doctrine/rst-parser",
+ "version": "0.5.6",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/doctrine/rst-parser.git",
+ "reference": "ca7f5f31f9ea58fde5aeffe0f7b8eb569e71a104"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/doctrine/rst-parser/zipball/ca7f5f31f9ea58fde5aeffe0f7b8eb569e71a104",
+ "reference": "ca7f5f31f9ea58fde5aeffe0f7b8eb569e71a104",
+ "shasum": ""
+ },
+ "require": {
+ "doctrine/event-manager": "^1.0 || ^2.0",
+ "php": "^7.2 || ^8.0",
+ "symfony/filesystem": "^4.1 || ^5.0 || ^6.0 || ^7.0",
+ "symfony/finder": "^4.1 || ^5.0 || ^6.0 || ^7.0",
+ "symfony/polyfill-mbstring": "^1.0",
+ "symfony/string": "^5.3 || ^6.0 || ^7.0",
+ "symfony/translation-contracts": "^1.1 || ^2.0 || ^3.0",
+ "twig/twig": "^2.9 || ^3.3"
+ },
+ "require-dev": {
+ "doctrine/coding-standard": "^11.0",
+ "gajus/dindent": "^2.0.2",
+ "phpstan/phpstan": "^1.9",
+ "phpstan/phpstan-deprecation-rules": "^1.0",
+ "phpstan/phpstan-phpunit": "^1.2",
+ "phpstan/phpstan-strict-rules": "^1.4",
+ "phpunit/phpunit": "^7.5 || ^8.0 || ^9.0",
+ "symfony/css-selector": "4.4 || ^5.2 || ^6.0 || ^7.0",
+ "symfony/dom-crawler": "4.4 || ^5.2 || ^6.0 || ^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Doctrine\\RST\\": "lib/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Grégoire Passault",
+ "email": "g.passault@gmail.com",
+ "homepage": "http://www.gregwar.com/"
+ },
+ {
+ "name": "Jonathan H. Wage",
+ "email": "jonwage@gmail.com",
+ "homepage": "https://jwage.com"
+ }
+ ],
+ "description": "PHP library to parse reStructuredText documents and generate HTML or LaTeX documents.",
+ "homepage": "https://github.com/doctrine/rst-parser",
+ "keywords": [
+ "html",
+ "latex",
+ "markup",
+ "parser",
+ "reStructuredText",
+ "rst"
+ ],
+ "support": {
+ "issues": "https://github.com/doctrine/rst-parser/issues",
+ "source": "https://github.com/doctrine/rst-parser/tree/0.5.6"
+ },
+ "time": "2024-01-14T11:02:23+00:00"
+ },
+ {
+ "name": "masterminds/html5",
+ "version": "2.9.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/Masterminds/html5-php.git",
+ "reference": "f5ac2c0b0a2eefca70b2ce32a5809992227e75a6"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/Masterminds/html5-php/zipball/f5ac2c0b0a2eefca70b2ce32a5809992227e75a6",
+ "reference": "f5ac2c0b0a2eefca70b2ce32a5809992227e75a6",
+ "shasum": ""
+ },
+ "require": {
+ "ext-dom": "*",
+ "php": ">=5.3.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.8.35 || ^5.7.21 || ^6 || ^7 || ^8 || ^9"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "2.7-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Masterminds\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Matt Butcher",
+ "email": "technosophos@gmail.com"
+ },
+ {
+ "name": "Matt Farina",
+ "email": "matt@mattfarina.com"
+ },
+ {
+ "name": "Asmir Mustafic",
+ "email": "goetas@gmail.com"
+ }
+ ],
+ "description": "An HTML5 parser and serializer.",
+ "homepage": "http://masterminds.github.io/html5-php",
+ "keywords": [
+ "HTML5",
+ "dom",
+ "html",
+ "parser",
+ "querypath",
+ "serializer",
+ "xml"
+ ],
+ "support": {
+ "issues": "https://github.com/Masterminds/html5-php/issues",
+ "source": "https://github.com/Masterminds/html5-php/tree/2.9.0"
+ },
+ "time": "2024-03-31T07:05:07+00:00"
+ },
+ {
+ "name": "psr/container",
+ "version": "2.0.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/php-fig/container.git",
+ "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963",
+ "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.4.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "2.0.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Psr\\Container\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "PHP-FIG",
+ "homepage": "https://www.php-fig.org/"
+ }
+ ],
+ "description": "Common Container Interface (PHP FIG PSR-11)",
+ "homepage": "https://github.com/php-fig/container",
+ "keywords": [
+ "PSR-11",
+ "container",
+ "container-interface",
+ "container-interop",
+ "psr"
+ ],
+ "support": {
+ "issues": "https://github.com/php-fig/container/issues",
+ "source": "https://github.com/php-fig/container/tree/2.0.2"
+ },
+ "time": "2021-11-05T16:47:00+00:00"
+ },
+ {
+ "name": "psr/log",
+ "version": "3.0.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/php-fig/log.git",
+ "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3",
+ "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.0.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Psr\\Log\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "PHP-FIG",
+ "homepage": "https://www.php-fig.org/"
+ }
+ ],
+ "description": "Common interface for logging libraries",
+ "homepage": "https://github.com/php-fig/log",
+ "keywords": [
+ "log",
+ "psr",
+ "psr-3"
+ ],
+ "support": {
+ "source": "https://github.com/php-fig/log/tree/3.0.2"
+ },
+ "time": "2024-09-11T13:17:53+00:00"
+ },
+ {
+ "name": "scrivo/highlight.php",
+ "version": "v9.18.1.10",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/scrivo/highlight.php.git",
+ "reference": "850f4b44697a2552e892ffe71490ba2733c2fc6e"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/scrivo/highlight.php/zipball/850f4b44697a2552e892ffe71490ba2733c2fc6e",
+ "reference": "850f4b44697a2552e892ffe71490ba2733c2fc6e",
+ "shasum": ""
+ },
+ "require": {
+ "ext-json": "*",
+ "php": ">=5.4"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.8|^5.7",
+ "sabberworm/php-css-parser": "^8.3",
+ "symfony/finder": "^2.8|^3.4|^5.4",
+ "symfony/var-dumper": "^2.8|^3.4|^5.4"
+ },
+ "suggest": {
+ "ext-mbstring": "Allows highlighting code with unicode characters and supports language with unicode keywords"
+ },
+ "type": "library",
+ "autoload": {
+ "files": [
+ "HighlightUtilities/functions.php"
+ ],
+ "psr-0": {
+ "Highlight\\": "",
+ "HighlightUtilities\\": ""
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-3-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Geert Bergman",
+ "homepage": "http://www.scrivo.org/",
+ "role": "Project Author"
+ },
+ {
+ "name": "Vladimir Jimenez",
+ "homepage": "https://allejo.io",
+ "role": "Maintainer"
+ },
+ {
+ "name": "Martin Folkers",
+ "homepage": "https://twobrain.io",
+ "role": "Contributor"
+ }
+ ],
+ "description": "Server side syntax highlighter that supports 185 languages. It's a PHP port of highlight.js",
+ "keywords": [
+ "code",
+ "highlight",
+ "highlight.js",
+ "highlight.php",
+ "syntax"
+ ],
+ "support": {
+ "issues": "https://github.com/scrivo/highlight.php/issues",
+ "source": "https://github.com/scrivo/highlight.php"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/allejo",
+ "type": "github"
+ }
+ ],
+ "time": "2022-12-17T21:53:22+00:00"
+ },
+ {
+ "name": "symfony-tools/docs-builder",
+ "version": "0.27.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony-tools/docs-builder.git",
+ "reference": "720b52b2805122a4c08376496bd9661944c2624a"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony-tools/docs-builder/zipball/720b52b2805122a4c08376496bd9661944c2624a",
+ "reference": "720b52b2805122a4c08376496bd9661944c2624a",
+ "shasum": ""
+ },
+ "require": {
+ "doctrine/rst-parser": "^0.5",
+ "ext-curl": "*",
+ "ext-json": "*",
+ "php": ">=8.3",
+ "scrivo/highlight.php": "^9.18.1",
+ "symfony/console": "^5.2 || ^6.0 || ^7.0",
+ "symfony/css-selector": "^5.2 || ^6.0 || ^7.0",
+ "symfony/dom-crawler": "^5.2 || ^6.0 || ^7.0",
+ "symfony/filesystem": "^5.2 || ^6.0 || ^7.0",
+ "symfony/finder": "^5.2 || ^6.0 || ^7.0",
+ "symfony/http-client": "^5.2 || ^6.0 || ^7.0",
+ "twig/twig": "^2.14 || ^3.3"
+ },
+ "require-dev": {
+ "gajus/dindent": "^2.0",
+ "masterminds/html5": "^2.7",
+ "symfony/phpunit-bridge": "^5.2 || ^6.0 || ^7.0",
+ "symfony/process": "^5.2 || ^6.0 || ^7.0"
+ },
+ "bin": [
+ "bin/docs-builder"
+ ],
+ "type": "project",
+ "autoload": {
+ "psr-4": {
+ "SymfonyDocsBuilder\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "The build system for Symfony's documentation",
+ "support": {
+ "issues": "https://github.com/symfony-tools/docs-builder/issues",
+ "source": "https://github.com/symfony-tools/docs-builder/tree/0.27.0"
+ },
+ "time": "2025-03-21T09:48:45+00:00"
+ },
+ {
+ "name": "symfony/console",
+ "version": "v6.4.17",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/console.git",
+ "reference": "799445db3f15768ecc382ac5699e6da0520a0a04"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/console/zipball/799445db3f15768ecc382ac5699e6da0520a0a04",
+ "reference": "799445db3f15768ecc382ac5699e6da0520a0a04",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-mbstring": "~1.0",
+ "symfony/service-contracts": "^2.5|^3",
+ "symfony/string": "^5.4|^6.0|^7.0"
+ },
+ "conflict": {
+ "symfony/dependency-injection": "<5.4",
+ "symfony/dotenv": "<5.4",
+ "symfony/event-dispatcher": "<5.4",
+ "symfony/lock": "<5.4",
+ "symfony/process": "<5.4"
+ },
+ "provide": {
+ "psr/log-implementation": "1.0|2.0|3.0"
+ },
+ "require-dev": {
+ "psr/log": "^1|^2|^3",
+ "symfony/config": "^5.4|^6.0|^7.0",
+ "symfony/dependency-injection": "^5.4|^6.0|^7.0",
+ "symfony/event-dispatcher": "^5.4|^6.0|^7.0",
+ "symfony/http-foundation": "^6.4|^7.0",
+ "symfony/http-kernel": "^6.4|^7.0",
+ "symfony/lock": "^5.4|^6.0|^7.0",
+ "symfony/messenger": "^5.4|^6.0|^7.0",
+ "symfony/process": "^5.4|^6.0|^7.0",
+ "symfony/stopwatch": "^5.4|^6.0|^7.0",
+ "symfony/var-dumper": "^5.4|^6.0|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Console\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Eases the creation of beautiful and testable command line interfaces",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "cli",
+ "command-line",
+ "console",
+ "terminal"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/console/tree/v6.4.17"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-12-07T12:07:30+00:00"
+ },
+ {
+ "name": "symfony/css-selector",
+ "version": "v7.2.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/css-selector.git",
+ "reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/css-selector/zipball/601a5ce9aaad7bf10797e3663faefce9e26c24e2",
+ "reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.2"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\CssSelector\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Jean-François Simon",
+ "email": "jeanfrancois.simon@sensiolabs.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Converts CSS selectors to XPath expressions",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/css-selector/tree/v7.2.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-25T14:21:43+00:00"
+ },
+ {
+ "name": "symfony/deprecation-contracts",
+ "version": "v3.5.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/deprecation-contracts.git",
+ "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6",
+ "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.5-dev"
+ }
+ },
+ "autoload": {
+ "files": [
+ "function.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "A generic function and convention to trigger deprecation notices",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.1"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-25T14:20:29+00:00"
+ },
+ {
+ "name": "symfony/dom-crawler",
+ "version": "v7.2.4",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/dom-crawler.git",
+ "reference": "19cc7b08efe9ad1ab1b56e0948e8d02e15ed3ef7"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/19cc7b08efe9ad1ab1b56e0948e8d02e15ed3ef7",
+ "reference": "19cc7b08efe9ad1ab1b56e0948e8d02e15ed3ef7",
+ "shasum": ""
+ },
+ "require": {
+ "masterminds/html5": "^2.6",
+ "php": ">=8.2",
+ "symfony/polyfill-ctype": "~1.8",
+ "symfony/polyfill-mbstring": "~1.0"
+ },
+ "require-dev": {
+ "symfony/css-selector": "^6.4|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\DomCrawler\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Eases DOM navigation for HTML and XML documents",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/dom-crawler/tree/v7.2.4"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2025-02-17T15:53:07+00:00"
+ },
+ {
+ "name": "symfony/filesystem",
+ "version": "v7.2.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/filesystem.git",
+ "reference": "b8dce482de9d7c9fe2891155035a7248ab5c7fdb"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/filesystem/zipball/b8dce482de9d7c9fe2891155035a7248ab5c7fdb",
+ "reference": "b8dce482de9d7c9fe2891155035a7248ab5c7fdb",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.2",
+ "symfony/polyfill-ctype": "~1.8",
+ "symfony/polyfill-mbstring": "~1.8"
+ },
+ "require-dev": {
+ "symfony/process": "^6.4|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Filesystem\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides basic utilities for the filesystem",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/filesystem/tree/v7.2.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-10-25T15:15:23+00:00"
+ },
+ {
+ "name": "symfony/finder",
+ "version": "v7.2.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/finder.git",
+ "reference": "87a71856f2f56e4100373e92529eed3171695cfb"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/finder/zipball/87a71856f2f56e4100373e92529eed3171695cfb",
+ "reference": "87a71856f2f56e4100373e92529eed3171695cfb",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.2"
+ },
+ "require-dev": {
+ "symfony/filesystem": "^6.4|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Finder\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Finds files and directories via an intuitive fluent interface",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/finder/tree/v7.2.2"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-12-30T19:00:17+00:00"
+ },
+ {
+ "name": "symfony/http-client",
+ "version": "v7.2.4",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/http-client.git",
+ "reference": "78981a2ffef6437ed92d4d7e2a86a82f256c6dc6"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/http-client/zipball/78981a2ffef6437ed92d4d7e2a86a82f256c6dc6",
+ "reference": "78981a2ffef6437ed92d4d7e2a86a82f256c6dc6",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.2",
+ "psr/log": "^1|^2|^3",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/http-client-contracts": "~3.4.4|^3.5.2",
+ "symfony/service-contracts": "^2.5|^3"
+ },
+ "conflict": {
+ "amphp/amp": "<2.5",
+ "php-http/discovery": "<1.15",
+ "symfony/http-foundation": "<6.4"
+ },
+ "provide": {
+ "php-http/async-client-implementation": "*",
+ "php-http/client-implementation": "*",
+ "psr/http-client-implementation": "1.0",
+ "symfony/http-client-implementation": "3.0"
+ },
+ "require-dev": {
+ "amphp/http-client": "^4.2.1|^5.0",
+ "amphp/http-tunnel": "^1.0|^2.0",
+ "amphp/socket": "^1.1",
+ "guzzlehttp/promises": "^1.4|^2.0",
+ "nyholm/psr7": "^1.0",
+ "php-http/httplug": "^1.0|^2.0",
+ "psr/http-client": "^1.0",
+ "symfony/amphp-http-client-meta": "^1.0|^2.0",
+ "symfony/dependency-injection": "^6.4|^7.0",
+ "symfony/http-kernel": "^6.4|^7.0",
+ "symfony/messenger": "^6.4|^7.0",
+ "symfony/process": "^6.4|^7.0",
+ "symfony/rate-limiter": "^6.4|^7.0",
+ "symfony/stopwatch": "^6.4|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\HttpClient\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides powerful methods to fetch HTTP resources synchronously or asynchronously",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "http"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/http-client/tree/v7.2.4"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2025-02-13T10:27:23+00:00"
+ },
+ {
+ "name": "symfony/http-client-contracts",
+ "version": "v3.5.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/http-client-contracts.git",
+ "reference": "ee8d807ab20fcb51267fdace50fbe3494c31e645"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/ee8d807ab20fcb51267fdace50fbe3494c31e645",
+ "reference": "ee8d807ab20fcb51267fdace50fbe3494c31e645",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.5-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Contracts\\HttpClient\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Test/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Generic abstractions related to HTTP clients",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "abstractions",
+ "contracts",
+ "decoupling",
+ "interfaces",
+ "interoperability",
+ "standards"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/http-client-contracts/tree/v3.5.2"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-12-07T08:49:48+00:00"
+ },
+ {
+ "name": "symfony/polyfill-ctype",
+ "version": "v1.31.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-ctype.git",
+ "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638",
+ "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.2"
+ },
+ "provide": {
+ "ext-ctype": "*"
+ },
+ "suggest": {
+ "ext-ctype": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Ctype\\": ""
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Gert de Pagter",
+ "email": "BackEndTea@gmail.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for ctype functions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "ctype",
+ "polyfill",
+ "portable"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/polyfill-ctype/tree/v1.31.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-09T11:45:10+00:00"
+ },
+ {
+ "name": "symfony/polyfill-intl-grapheme",
+ "version": "v1.31.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-intl-grapheme.git",
+ "reference": "b9123926e3b7bc2f98c02ad54f6a4b02b91a8abe"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/b9123926e3b7bc2f98c02ad54f6a4b02b91a8abe",
+ "reference": "b9123926e3b7bc2f98c02ad54f6a4b02b91a8abe",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.2"
+ },
+ "suggest": {
+ "ext-intl": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Intl\\Grapheme\\": ""
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for intl's grapheme_* functions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "grapheme",
+ "intl",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.31.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-09T11:45:10+00:00"
+ },
+ {
+ "name": "symfony/polyfill-intl-normalizer",
+ "version": "v1.31.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-intl-normalizer.git",
+ "reference": "3833d7255cc303546435cb650316bff708a1c75c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/3833d7255cc303546435cb650316bff708a1c75c",
+ "reference": "3833d7255cc303546435cb650316bff708a1c75c",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.2"
+ },
+ "suggest": {
+ "ext-intl": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Intl\\Normalizer\\": ""
+ },
+ "classmap": [
+ "Resources/stubs"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for intl's Normalizer class and related functions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "intl",
+ "normalizer",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.31.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-09T11:45:10+00:00"
+ },
+ {
+ "name": "symfony/polyfill-mbstring",
+ "version": "v1.31.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-mbstring.git",
+ "reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/85181ba99b2345b0ef10ce42ecac37612d9fd341",
+ "reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.2"
+ },
+ "provide": {
+ "ext-mbstring": "*"
+ },
+ "suggest": {
+ "ext-mbstring": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Mbstring\\": ""
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for the Mbstring extension",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "mbstring",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.31.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-09T11:45:10+00:00"
+ },
+ {
+ "name": "symfony/process",
+ "version": "v6.4.19",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/process.git",
+ "reference": "7a1c12e87b08ec9c97abdd188c9b3f5a40e37fc3"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/process/zipball/7a1c12e87b08ec9c97abdd188c9b3f5a40e37fc3",
+ "reference": "7a1c12e87b08ec9c97abdd188c9b3f5a40e37fc3",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Process\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Executes commands in sub-processes",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/process/tree/v6.4.19"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2025-02-04T13:35:48+00:00"
+ },
+ {
+ "name": "symfony/service-contracts",
+ "version": "v3.5.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/service-contracts.git",
+ "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/service-contracts/zipball/e53260aabf78fb3d63f8d79d69ece59f80d5eda0",
+ "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1",
+ "psr/container": "^1.1|^2.0",
+ "symfony/deprecation-contracts": "^2.5|^3"
+ },
+ "conflict": {
+ "ext-psr": "<1.1|>=2"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.5-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Contracts\\Service\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Test/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Generic abstractions related to writing services",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "abstractions",
+ "contracts",
+ "decoupling",
+ "interfaces",
+ "interoperability",
+ "standards"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/service-contracts/tree/v3.5.1"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-25T14:20:29+00:00"
+ },
+ {
+ "name": "symfony/string",
+ "version": "v7.2.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/string.git",
+ "reference": "446e0d146f991dde3e73f45f2c97a9faad773c82"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/string/zipball/446e0d146f991dde3e73f45f2c97a9faad773c82",
+ "reference": "446e0d146f991dde3e73f45f2c97a9faad773c82",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.2",
+ "symfony/polyfill-ctype": "~1.8",
+ "symfony/polyfill-intl-grapheme": "~1.0",
+ "symfony/polyfill-intl-normalizer": "~1.0",
+ "symfony/polyfill-mbstring": "~1.0"
+ },
+ "conflict": {
+ "symfony/translation-contracts": "<2.5"
+ },
+ "require-dev": {
+ "symfony/emoji": "^7.1",
+ "symfony/error-handler": "^6.4|^7.0",
+ "symfony/http-client": "^6.4|^7.0",
+ "symfony/intl": "^6.4|^7.0",
+ "symfony/translation-contracts": "^2.5|^3.0",
+ "symfony/var-exporter": "^6.4|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "files": [
+ "Resources/functions.php"
+ ],
+ "psr-4": {
+ "Symfony\\Component\\String\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "grapheme",
+ "i18n",
+ "string",
+ "unicode",
+ "utf-8",
+ "utf8"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/string/tree/v7.2.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-11-13T13:31:26+00:00"
+ },
+ {
+ "name": "symfony/translation-contracts",
+ "version": "v3.5.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/translation-contracts.git",
+ "reference": "4667ff3bd513750603a09c8dedbea942487fb07c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/4667ff3bd513750603a09c8dedbea942487fb07c",
+ "reference": "4667ff3bd513750603a09c8dedbea942487fb07c",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.5-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Contracts\\Translation\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Test/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Generic abstractions related to translation",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "abstractions",
+ "contracts",
+ "decoupling",
+ "interfaces",
+ "interoperability",
+ "standards"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/translation-contracts/tree/v3.5.1"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2024-09-25T14:20:29+00:00"
+ },
+ {
+ "name": "twig/twig",
+ "version": "v3.20.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/twigphp/Twig.git",
+ "reference": "3468920399451a384bef53cf7996965f7cd40183"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/twigphp/Twig/zipball/3468920399451a384bef53cf7996965f7cd40183",
+ "reference": "3468920399451a384bef53cf7996965f7cd40183",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1.0",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-ctype": "^1.8",
+ "symfony/polyfill-mbstring": "^1.3"
+ },
+ "require-dev": {
+ "phpstan/phpstan": "^2.0",
+ "psr/container": "^1.0|^2.0",
+ "symfony/phpunit-bridge": "^5.4.9|^6.4|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "files": [
+ "src/Resources/core.php",
+ "src/Resources/debug.php",
+ "src/Resources/escaper.php",
+ "src/Resources/string_loader.php"
+ ],
+ "psr-4": {
+ "Twig\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-3-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com",
+ "homepage": "http://fabien.potencier.org",
+ "role": "Lead Developer"
+ },
+ {
+ "name": "Twig Team",
+ "role": "Contributors"
+ },
+ {
+ "name": "Armin Ronacher",
+ "email": "armin.ronacher@active-4.com",
+ "role": "Project Founder"
+ }
+ ],
+ "description": "Twig, the flexible, fast, and secure template language for PHP",
+ "homepage": "https://twig.symfony.com",
+ "keywords": [
+ "templating"
+ ],
+ "support": {
+ "issues": "https://github.com/twigphp/Twig/issues",
+ "source": "https://github.com/twigphp/Twig/tree/v3.20.0"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/twig/twig",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2025-02-13T08:34:43+00:00"
+ }
+ ],
+ "packages-dev": [],
+ "aliases": [],
+ "minimum-stability": "dev",
+ "stability-flags": {},
+ "prefer-stable": true,
+ "prefer-lowest": false,
+ "platform": {
+ "php": ">=8.3"
+ },
+ "platform-dev": {},
+ "platform-overrides": {
+ "php": "8.3"
+ },
+ "plugin-api-version": "2.6.0"
+}
diff --git a/_build/conf.py b/_build/conf.py
deleted file mode 100644
index b707b25a477..00000000000
--- a/_build/conf.py
+++ /dev/null
@@ -1,287 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Symfony documentation build configuration file, created by
-# sphinx-quickstart on Sat Jul 28 21:58:57 2012.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# Note that not all possible configuration values are present in this
-# autogenerated file.
-#
-# All configuration values have a default; values that are commented out
-# serve to show the default.
-
-import sys, os
-
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-sys.path.append(os.path.abspath('_themes/_exts'))
-
-# adding PhpLexer
-from sphinx.highlighting import lexers
-from pygments.lexers.compiled import CLexer
-from pygments.lexers.special import TextLexer
-from pygments.lexers.text import RstLexer
-from pygments.lexers.web import PhpLexer
-from symfonycom.sphinx.lexer import TerminalLexer
-
-# -- General configuration -----------------------------------------------------
-
-# If your documentation needs a minimal Sphinx version, state it here.
-#needs_sphinx = '1.0'
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = [
- 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo',
- 'sensio.sphinx.refinclude', 'sensio.sphinx.configurationblock', 'sensio.sphinx.phpcode', 'sensio.sphinx.bestpractice', 'sensio.sphinx.codeblock',
- 'symfonycom.sphinx'
-]
-
-# Add any paths that contain templates here, relative to this directory.
-# templates_path = ['_theme/_templates']
-
-# The suffix of source filenames.
-source_suffix = '.rst'
-
-# The encoding of source files.
-#source_encoding = 'utf-8-sig'
-
-# The master toctree document.
-master_doc = 'index'
-
-# General information about the project.
-project = 'Symfony Framework Documentation'
-copyright = ''
-
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
-# version = '2.2'
-# The full version, including alpha/beta/rc tags.
-# release = '2.2.13'
-
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
-
-# List of patterns, relative to source directory, that match files and
-# directories to ignore when looking for source files.
-exclude_patterns = ['_build']
-
-# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
-
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-# -- Settings for symfony doc extension ---------------------------------------------------
-
-# enable highlighting for PHP code not between ```` by default
-lexers['markdown'] = TextLexer()
-lexers['php'] = PhpLexer(startinline=True)
-lexers['php-annotations'] = PhpLexer(startinline=True)
-lexers['php-standalone'] = PhpLexer(startinline=True)
-lexers['php-symfony'] = PhpLexer(startinline=True)
-lexers['rst'] = RstLexer()
-lexers['varnish3'] = CLexer()
-lexers['varnish4'] = CLexer()
-lexers['terminal'] = TerminalLexer()
-
-config_block = {
- 'apache': 'Apache',
- 'markdown': 'Markdown',
- 'nginx': 'Nginx',
- 'rst': 'reStructuredText',
- 'terminal': 'Terminal',
- 'varnish3': 'Varnish 3',
- 'varnish4': 'Varnish 4'
-}
-
-# use PHP as the primary domain
-primary_domain = 'php'
-
-# set url for API links
-api_url = 'http://api.symfony.com/master/%s'
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages. See the documentation for
-# a list of builtin themes.
-html_theme = "sphinx_rtd_theme"
-html_theme_path = ["_themes", ]
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further. For a list of options available for each theme, see the
-# documentation.
-#html_theme_options = {}
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# " v documentation".
-#html_title = None
-
-# A shorter title for the navigation bar. Default is the same as html_title.
-#html_short_title = None
-
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-#html_logo = None
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
-#html_static_path = ['_static']
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = {}
-
-# If false, no module index is generated.
-#html_domain_indices = True
-
-# If false, no index is generated.
-#html_use_index = True
-
-# If true, the index is split into individual pages for each letter.
-#html_split_index = False
-
-# If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
-
-# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
-#html_show_sphinx = True
-
-# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
-#html_show_copyright = True
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a tag referring to it. The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# This is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = None
-
-# Output file base name for HTML help builder.
-htmlhelp_basename = 'SymfonyDoc'
-
-
-# -- Options for LaTeX output --------------------------------------------------
-
-latex_elements = {
-# The paper size ('letterpaper' or 'a4paper').
-#'papersize': 'letterpaper',
-
-# The font size ('10pt', '11pt' or '12pt').
-#'pointsize': '10pt',
-
-# Additional stuff for the LaTeX preamble.
-#'preamble': '',
-}
-
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, documentclass [howto/manual]).
-latex_documents = [
- ('index', 'Symfony.tex', u'Symfony Documentation',
- u'Symfony community', 'manual'),
-]
-
-# The name of an image file (relative to this directory) to place at the top of
-# the title page.
-#latex_logo = None
-
-# For "manual" documents, if this is true, then toplevel headings are parts,
-# not chapters.
-#latex_use_parts = False
-
-# If true, show page references after internal links.
-#latex_show_pagerefs = False
-
-# If true, show URL addresses after external links.
-#latex_show_urls = False
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-#latex_domain_indices = True
-
-
-# -- Options for manual page output --------------------------------------------
-
-# One entry per manual page. List of tuples
-# (source start file, name, description, authors, manual section).
-man_pages = [
- ('index', 'symfony', u'Symfony Documentation',
- [u'Symfony community'], 1)
-]
-
-# If true, show URL addresses after external links.
-#man_show_urls = False
-
-
-# -- Options for Texinfo output ------------------------------------------------
-
-# Grouping the document tree into Texinfo files. List of tuples
-# (source start file, target name, title, author,
-# dir menu entry, description, category)
-texinfo_documents = [
- ('index', 'Symfony', u'Symfony Documentation',
- u'Symfony community', 'Symfony', 'One line description of project.',
- 'Miscellaneous'),
-]
-
-# Documents to append as an appendix to all manuals.
-#texinfo_appendices = []
-
-# If false, no module index is generated.
-#texinfo_domain_indices = True
-
-# How to display URL addresses: 'footnote', 'no', or 'inline'.
-#texinfo_show_urls = 'footnote'
-
-# Use PHP syntax highlighting in code examples by default
-highlight_language='php'
diff --git a/_build/maintainer_guide.rst b/_build/maintainer_guide.rst
index fd3de4f3f3b..9758b4e7397 100644
--- a/_build/maintainer_guide.rst
+++ b/_build/maintainer_guide.rst
@@ -39,14 +39,14 @@ contributes again, it's OK to mention some of the minor issues to educate them.
$ gh merge 11059
- Working on symfony/symfony-docs (branch master)
+ Working on symfony/symfony-docs (branch 6.2)
Merging Pull Request 11059: dmaicher/patch-3
...
# This is important!! Say NO to push the changes now
Push the changes now? (Y/n) n
- Now, push with: git push gh "master" refs/notes/github-comments
+ Now, push with: git push gh "6.2" refs/notes/github-comments
# Now, open your editor and make the needed changes ...
@@ -54,7 +54,7 @@ contributes again, it's OK to mention some of the minor issues to educate them.
# Use "Minor reword", "Minor tweak", etc. as the commit message
# now run the 'push' command shown above by 'gh' (it's different each time)
- $ git push gh "master" refs/notes/github-comments
+ $ git push gh "6.2" refs/notes/github-comments
Merging Pull Requests
---------------------
@@ -134,9 +134,9 @@ original contributor.
$ cd symfony-docs/
# make sure that your local branch is updated
- $ git checkout 3.4
+ $ git checkout 4.4
$ git fetch upstream
- $ git merge upstream/3.4
+ $ git merge upstream/4.4
# merge any PR passing its GitHub number as argument
$ gh merge 11159
@@ -153,20 +153,20 @@ the ``-s`` option:
.. code-block:: terminal
- # e.g. this PR was sent against 'master', but it's merged in '3.4'
- $ gh merge 11160 -s 3.4
+ # e.g. this PR was sent against 'master', but it's merged in '4.4'
+ $ gh merge 11160 -s 4.4
Sometimes, when changing the branch, you may face rebase issues, but they are
usually simple to fix:
.. code-block:: terminal
- $ gh merge 11160 -s 3.4
+ $ gh merge 11160 -s 4.4
...
Unable to rebase the patch for pull/11183
- The command "'git' 'rebase' '--onto' '3.4' '4.2' 'pull/11160'" failed.
+ The command "'git' 'rebase' '--onto' '4.4' '5.0' 'pull/11160'" failed.
Exit Code: 128(Invalid exit argument)
[...]
@@ -183,7 +183,7 @@ usually simple to fix:
# Lastly, re-run the exact same original command that resulted in a conflict
# There's no need to change the branch or do anything else.
- $ gh merge 11160 -s 3.4
+ $ gh merge 11160 -s 4.4
The previous run had some conflicts. Do you want to resume the merge? (Y/n)
@@ -195,29 +195,29 @@ Step 3: Merge it into the other branches
If a PR has not been merged in ``master``, you must merge it up into all the
maintained branches until ``master``. Imagine that you are merging a PR against
-``3.4`` and the maintained branches are ``3.4``, ``4.2`` and ``master``:
+``4.4`` and the maintained branches are ``4.4``, ``5.0`` and ``master``:
.. code-block:: terminal
$ git fetch upstream
- $ git checkout 3.4
- $ git merge upstream/3.4
+ $ git checkout 4.4
+ $ git merge upstream/4.4
$ gh merge 11159
$ git push origin
$ git push upstream
- $ git checkout 4.2
- $ git merge upstream/4.2
- $ git merge --log 3.4
+ $ git checkout 5.0
+ $ git merge upstream/5.0
+ $ git merge --log 4.4
# here you can face several errors explained later
$ git push origin
$ git push upstream
$ git checkout master
$ git merge upstream/master
- $ git merge --log 4.2
+ $ git merge --log 5.0
$ git push origin
$ git push upstream
@@ -247,8 +247,8 @@ When updating your local branches before merging:
.. code-block:: terminal
$ git fetch upstream
- $ git checkout 3.4
- $ git merge upstream/3.4
+ $ git checkout 4.4
+ $ git merge upstream/4.4
It's possible that you merge a wrong upstream branch unawarely. It's usually
easy to spot because you'll see lots of conflicts:
@@ -256,8 +256,8 @@ easy to spot because you'll see lots of conflicts:
.. code-block:: terminal
# DON'T DO THIS! It's a wrong branch merge
- $ git checkout 3.4
- $ git merge upstream/4.2
+ $ git checkout 4.4
+ $ git merge upstream/5.0
As long as you don't push this wrong merge, there's no problem. Delete your
local branch and check it out again:
@@ -265,8 +265,8 @@ local branch and check it out again:
.. code-block:: terminal
$ git checkout master
- $ git branch -D 3.4
- $ git checkout 3.4 upstream/3.4
+ $ git branch -D 4.4
+ $ git checkout 4.4 upstream/4.4
If you did push the wrong branch merge, ask for help in the documentation
mergers chat and we'll help solve the problem.
@@ -278,9 +278,9 @@ When merging things to upper branches, most of the times you'll see conflicts:
.. code-block:: terminal
- $ git checkout 4.2
- $ git merge upstream/4.2
- $ git merge --log 3.4
+ $ git checkout 5.0
+ $ git merge upstream/5.0
+ $ git merge --log 4.4
Auto-merging security/entity_provider.rst
Auto-merging logging/monolog_console.rst
@@ -314,13 +314,13 @@ were modified by the PR but no longer exist in newer branches:
.. code-block:: terminal
- $ git checkout 4.2
- $ git merge upstream/4.2
- $ git merge --log 3.4
+ $ git checkout 5.0
+ $ git merge upstream/5.0
+ $ git merge --log 4.4
Auto-merging translation/debug.rst
CONFLICT (modify/delete): service_container/scopes.rst deleted in HEAD and
- modified in 3.4. Version 3.4 of service_container/scopes.rst left in tree.
+ modified in 4.4. Version 4.4 of service_container/scopes.rst left in tree.
Auto-merging service_container.rst
If the contents of the deleted file were moved to a different file in newer
@@ -335,6 +335,43 @@ in the tree as follows:
$ git push origin
$ git push upstream
+Merging in the wrong branch
+...........................
+
+A Pull Request was made against ``5.x`` but it should be merged in ``5.1`` and you
+forgot to merge as ``gh merge NNNNN -s 5.1`` to change the merge branch. Solution:
+
+.. code-block:: terminal
+
+ $ git checkout 5.1
+ $ git cherry-pick -m 1
+ $ git checkout 5.x
+ $ git revert -m 1
+ # now continue with the normal "upmerging"
+ $ git checkout 5.2
+ $ git merge 5.1
+ $ ...
+
+Merging while the target branch changed
+.......................................
+
+Sometimes, someone else merges a PR in ``5.x`` at the same time as you are
+doing it. In these cases, ``gh merge ...`` fails to push. Solve this by
+resetting your local branch and restarting the merge:
+
+.. code-block:: terminal
+
+ $ gh merge ...
+ # this failed
+
+ # fetch the updated 5.x branch from GitHub
+ $ git fetch upstream
+ $ git checkout 5.x
+ $ git reset --hard upstream/5.x
+
+ # restart the merge
+ $ gh merge ...
+
.. _`symfony/symfony-docs`: https://github.com/symfony/symfony-docs
.. _`Symfony Docs team`: https://github.com/orgs/symfony/teams/team-symfony-docs
.. _`Symfony's respectful review comments`: https://symfony.com/doc/current/contributing/community/review-comments.html
diff --git a/_build/make.bat b/_build/make.bat
deleted file mode 100644
index 6d3f205272f..00000000000
--- a/_build/make.bat
+++ /dev/null
@@ -1,263 +0,0 @@
-@ECHO OFF
-
-REM Command file for Sphinx documentation
-
-if "%SPHINXBUILD%" == "" (
- set SPHINXBUILD=sphinx-build
-)
-set BUILDDIR=.
-set ALLSPHINXOPTS=-c %BUILDDIR% -d %BUILDDIR%/doctrees %SPHINXOPTS% ..
-set I18NSPHINXOPTS=%SPHINXOPTS% .
-if NOT "%PAPER%" == "" (
- set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
- set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
-)
-
-if "%1" == "" goto help
-
-if "%1" == "help" (
- :help
- echo.Please use `make ^` where ^ is one of
- echo. html to make standalone HTML files
- echo. dirhtml to make HTML files named index.html in directories
- echo. singlehtml to make a single large HTML file
- echo. pickle to make pickle files
- echo. json to make JSON files
- echo. htmlhelp to make HTML files and a HTML help project
- echo. qthelp to make HTML files and a qthelp project
- echo. devhelp to make HTML files and a Devhelp project
- echo. epub to make an epub
- echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
- echo. text to make text files
- echo. man to make manual pages
- echo. texinfo to make Texinfo files
- echo. gettext to make PO message catalogs
- echo. changes to make an overview over all changed/added/deprecated items
- echo. xml to make Docutils-native XML files
- echo. pseudoxml to make pseudoxml-XML files for display purposes
- echo. linkcheck to check all external links for integrity
- echo. doctest to run all doctests embedded in the documentation if enabled
- echo. coverage to run coverage check of the documentation if enabled
- goto end
-)
-
-if "%1" == "clean" (
- for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
- del /q /s %BUILDDIR%\*
- goto end
-)
-
-
-REM Check if sphinx-build is available and fallback to Python version if any
-%SPHINXBUILD% 2> nul
-if errorlevel 9009 goto sphinx_python
-goto sphinx_ok
-
-:sphinx_python
-
-set SPHINXBUILD=python -m sphinx.__init__
-%SPHINXBUILD% 2> nul
-if errorlevel 9009 (
- echo.
- echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
- echo.installed, then set the SPHINXBUILD environment variable to point
- echo.to the full path of the 'sphinx-build' executable. Alternatively you
- echo.may add the Sphinx directory to PATH.
- echo.
- echo.If you don't have Sphinx installed, grab it from
- echo.http://sphinx-doc.org/
- exit /b 1
-)
-
-:sphinx_ok
-
-
-if "%1" == "html" (
- %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The HTML pages are in %BUILDDIR%/html.
- goto end
-)
-
-if "%1" == "dirhtml" (
- %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
- goto end
-)
-
-if "%1" == "singlehtml" (
- %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
- goto end
-)
-
-if "%1" == "pickle" (
- %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished; now you can process the pickle files.
- goto end
-)
-
-if "%1" == "json" (
- %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished; now you can process the JSON files.
- goto end
-)
-
-if "%1" == "htmlhelp" (
- %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished; now you can run HTML Help Workshop with the ^
-.hhp project file in %BUILDDIR%/htmlhelp.
- goto end
-)
-
-if "%1" == "qthelp" (
- %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished; now you can run "qcollectiongenerator" with the ^
-.qhcp project file in %BUILDDIR%/qthelp, like this:
- echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Symfony.qhcp
- echo.To view the help file:
- echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Symfony.ghc
- goto end
-)
-
-if "%1" == "devhelp" (
- %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished.
- goto end
-)
-
-if "%1" == "epub" (
- %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The epub file is in %BUILDDIR%/epub.
- goto end
-)
-
-if "%1" == "latex" (
- %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
- goto end
-)
-
-if "%1" == "latexpdf" (
- %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
- cd %BUILDDIR%/latex
- make all-pdf
- cd %~dp0
- echo.
- echo.Build finished; the PDF files are in %BUILDDIR%/latex.
- goto end
-)
-
-if "%1" == "latexpdfja" (
- %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
- cd %BUILDDIR%/latex
- make all-pdf-ja
- cd %~dp0
- echo.
- echo.Build finished; the PDF files are in %BUILDDIR%/latex.
- goto end
-)
-
-if "%1" == "text" (
- %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The text files are in %BUILDDIR%/text.
- goto end
-)
-
-if "%1" == "man" (
- %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The manual pages are in %BUILDDIR%/man.
- goto end
-)
-
-if "%1" == "texinfo" (
- %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
- goto end
-)
-
-if "%1" == "gettext" (
- %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
- goto end
-)
-
-if "%1" == "changes" (
- %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
- if errorlevel 1 exit /b 1
- echo.
- echo.The overview file is in %BUILDDIR%/changes.
- goto end
-)
-
-if "%1" == "linkcheck" (
- %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
- if errorlevel 1 exit /b 1
- echo.
- echo.Link check complete; look for any errors in the above output ^
-or in %BUILDDIR%/linkcheck/output.txt.
- goto end
-)
-
-if "%1" == "doctest" (
- %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
- if errorlevel 1 exit /b 1
- echo.
- echo.Testing of doctests in the sources finished, look at the ^
-results in %BUILDDIR%/doctest/output.txt.
- goto end
-)
-
-if "%1" == "coverage" (
- %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
- if errorlevel 1 exit /b 1
- echo.
- echo.Testing of coverage in the sources finished, look at the ^
-results in %BUILDDIR%/coverage/python.txt.
- goto end
-)
-
-if "%1" == "xml" (
- %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The XML files are in %BUILDDIR%/xml.
- goto end
-)
-
-if "%1" == "pseudoxml" (
- %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
- if errorlevel 1 exit /b 1
- echo.
- echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
- goto end
-)
-
-:end
diff --git a/_build/redirection_map b/_build/redirection_map
index 743707e69c1..b38573a0a14 100644
--- a/_build/redirection_map
+++ b/_build/redirection_map
@@ -13,7 +13,7 @@
/cookbook/email /email
/cookbook/gmail /cookbook/email/gmail
/cookbook/console /components/console
-/cookbook/tools/autoloader /components/class_loader
+/cookbook/tools/autoloader https://github.com/symfony/class-loader
/cookbook/tools/finder /components/finder
/cookbook/service_container/parentservices /service_container/parent_services
/cookbook/service_container/factories /service_container/factories
@@ -132,11 +132,6 @@
/cookbook/controller/upload_file /controller/upload_file
/cookbook/debugging /
/debug/debugging /
-/cookbook/deployment/azure-website /cookbook/azure-website
-/cookbook/deployment/fortrabbit /deployment/fortrabbit
-/cookbook/deployment/heroku /deployment/heroku
-/cookbook/deployment/index /deployment
-/cookbook/deployment/platformsh /deployment/platformsh
/cookbook/deployment/tools /deployment/tools
/cookbook/doctrine/common_extensions /doctrine/common_extensions
/cookbook/doctrine/console /doctrine
@@ -161,11 +156,13 @@
/cookbook/email/index /email
/cookbook/email/spool /email/spool
/cookbook/email/testing /email/testing
-/cookbook/event_dispatcher/before_after_filters /event_dispatcher/before_after_filters
+/cookbook/event_dispatcher/before_after_filters /event_dispatcher#event-dispatcher-before-after-filters
+/event_dispatcher/before_after_filters /event_dispatcher#event-dispatcher-before-after-filters
/cookbook/event_dispatcher/class_extension /event_dispatcher/class_extension
/cookbook/event_dispatcher/event_listener /event_dispatcher
/cookbook/event_dispatcher/index /event_dispatcher
/cookbook/event_dispatcher/method_behavior /event_dispatcher/method_behavior
+/event_dispatcher/method_behavior /event_dispatcher#event-dispatcher-method-behavior
/cookbook/expressions /security/expressions
/expressions /security/expressions
/cookbook/form/create_custom_field_type /form/create_custom_field_type
@@ -193,7 +190,8 @@
/cookbook/logging/monolog_console /logging/monolog_console
/cookbook/logging/monolog_email /logging/monolog_email
/cookbook/logging/monolog_regex_based_excludes /logging/monolog_regex_based_excludes
-/cookbook/profiler/data_collector /profiler/data_collector
+/cookbook/profiler/data_collector /profiler#profiler-data-collector
+/profiler/data_collector /profiler#profiler-data-collector
/cookbook/profiler/index /profiler
/cookbook/profiler/matchers /profiler/matchers
/cookbook/profiler/profiling_data /profiler/profiling_data
@@ -253,12 +251,14 @@
/cookbook/session/index /session
/cookbook/session/limit_metadata_writes /reference/configuration/framework
/session/limit_metadata_writes /reference/configuration/framework
-/cookbook/session/locale_sticky_session /session/locale_sticky_session
+/cookbook/session/locale_sticky_session /session#locale-sticky-session
+/cookbook/locale_sticky_session /session#locale-sticky-session
/cookbook/session/php_bridge /session/php_bridge
/cookbook/session/proxy_examples /session/proxy_examples
/cookbook/session/sessions_directory /session/sessions_directory
/cookbook/symfony1 /introduction/symfony1
-/cookbook/templating/global_variables /templating/global_variables
+/cookbook/templating/global_variables /templating#templating-global-variables
+/templating/global_variables /templating#templating-global-variables
/cookbook/templating/index /templating
/cookbook/templating/namespaced_paths /templating/namespaced_paths
/cookbook/templating/PHP /templating/PHP
@@ -295,15 +295,15 @@
/components/asset/introduction /components/asset
/components/browser_kit/index /components/browser_kit
/components/browser_kit/introduction /components/browser_kit
-/components/class_loader/introduction /components/class_loader
-/components/class_loader/index /components/class_loader
-/components/class_loader/cache_class_loader /components/class_loader
-/components/class_loader/class_loader /components/class_loader
-/components/class_loader/class_map_generator /components/class_loader
-/components/class_loader/debug_class_loader /components/class_loader
-/components/class_loader/map_class_loader /components/class_loader
-/components/class_loader/map_class_loader /components/class_loader
-/components/class_loader/psr4_class_loader /components/class_loader
+/components/class_loader/introduction https://github.com/symfony/class-loader
+/components/class_loader/index https://github.com/symfony/class-loader
+/components/class_loader/cache_class_loader https://github.com/symfony/class-loader
+/components/class_loader/class_loader https://github.com/symfony/class-loader
+/components/class_loader/class_map_generator https://github.com/symfony/class-loader
+/components/class_loader/debug_class_loader https://github.com/symfony/class-loader
+/components/class_loader/map_class_loader https://github.com/symfony/class-loader
+/components/class_loader/map_class_loader https://github.com/symfony/class-loader
+/components/class_loader/psr4_class_loader https://github.com/symfony/class-loader
/components/config/introduction /components/config
/components/config/index /components/config
/components/console/helpers/tablehelper /components/console/helpers/table
@@ -345,15 +345,15 @@
/components/http_kernel/index /components/http_kernel
/components/property_access/introduction /components/property_access
/components/property_access/index /components/property_access
-/components/routing/index /components/routing
-/components/routing/introduction /components/routing
+/components/routing/index https://github.com/symfony/routing
+/components/routing/introduction https://github.com/symfony/routing
/components/routing/hostname_pattern /routing/hostname_pattern
/components/security/introduction /components/security
/components/security/index /components/security
-/components/templating/introduction /components/templating
-/components/templating/index /components/templating
-/components/templating/helpers/assetshelper /components/templating/assetshelper
-/components/templating/helpers/slotshelper /components/templating/slotshelper
+/components/templating/introduction https://github.com/symfony/templating
+/components/templating/index https://github.com/symfony/templating
+/components/templating/helpers/assetshelper https://github.com/symfony/templating
+/components/templating/helpers/slotshelper https://github.com/symfony/templating
/components/translation/introduction /components/translation
/components/translation/index /components/translation
/components/var_dumper/introduction /components/var_dumper
@@ -390,6 +390,9 @@
/quick_tour/the_view /quick_tour/flex_recipes
/service_container/service_locators /service_container/service_subscribers_locators
/templating/overriding /bundles/override
+/templating/twig_extension /templates#templates-twig-extension
+/templating/hinclude /templates#templates-hinclude
+/templating/PHP /templates
/security/custom_provider /security/user_provider
/security/multiple_user_providers /security/user_provider
/security/custom_password_authenticator /security/guard_authentication
@@ -399,7 +402,7 @@
/security/acl_advanced /security/acl
/security/password_encoding /security
/weblink /web_link
-/components/weblink /components/web_link
+/components/weblink https://github.com/symfony/web-link
/frontend/encore/installation-no-flex /frontend/encore/installation
/http_cache/form_csrf_caching /security/csrf
/console/logging /console
@@ -411,6 +414,7 @@
/security/entity_provider /security/user_provider
/session/avoid_session_start /session
/session/sessions_directory /session
+/session/configuring_ttl /session#session-configure-ttl
/frontend/encore/legacy-apps /frontend/encore/legacy-applications
/configuration/external_parameters /configuration/environment_variables
/contributing/code/patches /contributing/code/pull_requests
@@ -426,6 +430,7 @@
/email/spool /mailer
/email/testing /mailer
/contributing/community/other /contributing/community
+/contributing/code/core_team /contributing/core_team
/profiler/storage /profiler
/setup/composer /setup
/security/security_checker /setup
@@ -449,16 +454,20 @@
/reference/requirements /setup
/bundles/inheritance /bundles/override
/templating /templates
-/templating/escaping /templates
-/templating/syntax /templates
-/templating/debug /templates
-/templating/render_without_controller /templates
-/templating/app_variable /templates
+/templating/escaping /templates#output-escaping
+/templating/syntax /templates#linting-twig-templates
+/templating/debug /templates#the-dump-twig-utilities
+/templating/render_without_controller /templates#rendering-a-template-directly-from-a-route
+/templating/app_variable /templates#the-app-global-variable
/templating/formats /templates
-/templating/namespaced_paths /templates
-/templating/embedding_controllers /templates
-/templating/inheritance /templates
+/templating/namespaced_paths /templates#template-namespaces
+/templating/embedding_controllers /templates#embedding-controllers
+/templating/inheritance /templates#template-inheritance-and-layouts
/testing/doctrine /testing/database
+/translation/templates /translation#translation-in-templates
+/translation/debug /translation#translation-debug
+/translation/lint /translation#translation-lint
+/translation/locale /translation#translation-locale
/doctrine/lifecycle_callbacks /doctrine/events
/doctrine/event_listeners_subscribers /doctrine/events
/doctrine/common_extensions /doctrine
@@ -475,3 +484,94 @@
/best_practices/web-assets /best_practices
/best_practices/tests /best_practices
/components/debug https://github.com/symfony/debug
+/components/translation https://github.com/symfony/translation
+/components/translation/usage /translation
+/components/translation/custom_formats https://github.com/symfony/translation
+/components/translation/custom_message_formatter https://github.com/symfony/translation
+/components/notifier https://github.com/symfony/notifier
+/components/routing https://github.com/symfony/routing
+/session/database /session#session-database
+/doctrine/pdo_session_storage /session#session-database-pdo
+/doctrine/mongodb_session_storage /session#session-database-mongodb
+/components/dotenv https://github.com/symfony/dotenv
+/components/mercure /mercure
+/components/polyfill_apcu https://github.com/symfony/polyfill-apcu
+/components/polyfill_ctype https://github.com/symfony/polyfill-ctype
+/components/polyfill_iconv https://github.com/symfony/polyfill-iconv
+/components/polyfill_intl_grapheme https://github.com/symfony/polyfill_intl-grapheme
+/components/polyfill_intl_icu https://github.com/symfony/polyfill_intl-icu
+/components/polyfill_intl_idn https://github.com/symfony/polyfill_intl-idn
+/components/polyfill_intl_normalizer https://github.com/symfony/polyfill_intl-normalizer
+/components/polyfill_mbstring https://github.com/symfony/polyfill-mbstring
+/components/polyfill_php54 https://github.com/symfony/polyfill-php54
+/components/polyfill_php55 https://github.com/symfony/polyfill-php55
+/components/polyfill_php56 https://github.com/symfony/polyfill-php56
+/components/polyfill_php70 https://github.com/symfony/polyfill-php70
+/components/polyfill_php71 https://github.com/symfony/polyfill-php71
+/components/polyfill_php72 https://github.com/symfony/polyfill-php72
+/components/polyfill_php73 https://github.com/symfony/polyfill-php73
+/components/polyfill_uuid https://github.com/symfony/polyfill-uuid
+/components/web_link https://github.com/symfony/web-link
+/components/templating https://github.com/symfony/templating
+/components/error_handler https://github.com/symfony/error-handler
+/components/class_loader https://github.com/symfony/class-loader
+/frontend/encore/versus-assetic /frontend
+/components/http_client /http_client
+/components/mailer /mailer
+/messenger/message-recorder /messenger/dispatch_after_current_bus
+/components/stopwatch https://github.com/symfony/stopwatch
+/service_container/3.3-di-changes https://symfony.com/doc/3.4/service_container/3.3-di-changes.html
+/frontend/encore/shared-entry /frontend/encore/split-chunks
+/frontend/encore/page-specific-assets /frontend/encore/simple-example#page-specific-javascript-or-css
+/testing/functional_tests_assertions /testing#testing-application-assertions
+/components https://symfony.com/components
+/components/index https://symfony.com/components
+/serializer/normalizers /serializer#serializer-built-in-normalizers
+/logging/monolog_regex_based_excludes /logging/monolog_exclude_http_codes
+/security/named_encoders /security/named_hashers
+/components/inflector /string#inflector
+/security/experimental_authenticators /security
+/security/user_provider /security/user_providers
+/security/reset_password /security/passwords#reset-password
+/security/auth_providers /security#security-authenticators
+/security/form_login /security#form-login
+/security/form_login_setup /security#form-login
+/security/json_login_setup /security#json-login
+/security/named_hashers /security/passwords#named-password-hashers
+/security/password_migration /security/passwords#security-password-migration
+/security/acl https://github.com/symfony/acl-bundle/blob/main/src/Resources/doc/index.rst
+/security/securing_services /security#securing-other-services
+/security/authenticator_manager /security
+/security/multiple_guard_authenticators /security/entry_point
+/security/guard_authentication /security/custom_authenticator
+/components/security/authentication /security#authenticating-users
+/components/security/authorization /security#access-control-authorization
+/components/security/firewall /security#the-firewall
+/components/security/secure_tools /security/passwords
+/components/security /security
+/components/var_dumper/advanced /components/var_dumper#advanced-usage
+/components/yaml/yaml_format /reference/formats/yaml
+/components/expression_language/syntax /reference/formats/expression_language
+/components/expression_language/ast /components/expression_language#expression-language-ast
+/components/expression_language/caching /components/expression_language#expression-language-caching
+/components/expression_language/extending /components/expression_language#expression-language-extending
+/notifier/chatters /notifier#sending-chat-messages
+/notifier/texters /notifier#sending-sms
+/notifier/events /notifier#notifier-events
+/email /mailer
+/frontend/assetic /frontend
+/frontend/assetic/index /frontend
+/controller/argument_value_resolver /controller/value_resolver
+/frontend/ux https://symfony.com/bundles/StimulusBundle/current/index.html
+/messenger/handler_results /messenger#messenger-getting-handler-results
+/messenger/dispatch_after_current_bus /messenger#messenger-transactional-messages
+/messenger/multiple_buses /messenger#messenger-multiple-buses
+/frontend/encore/server-data /frontend/server-data
+/components/string /string
+/testing/http_authentication /testing#testing_logging_in_users
+/doctrine/registration_form /security#security-make-registration-form
+/form/form_dependencies /form/create_custom_field_type
+/doctrine/reverse_engineering /doctrine#doctrine-adding-mapping
+/components/serializer /serializer
+/serializer/custom_encoder /serializer/encoders#serializer-custom-encoder
+/components/string /string
diff --git a/_images/components/console/completion.gif b/_images/components/console/completion.gif
new file mode 100644
index 00000000000..18b3f5475c8
Binary files /dev/null and b/_images/components/console/completion.gif differ
diff --git a/_images/components/console/cursor.gif b/_images/components/console/cursor.gif
new file mode 100644
index 00000000000..71a74dd8637
Binary files /dev/null and b/_images/components/console/cursor.gif differ
diff --git a/_images/components/console/debug_formatter.png b/_images/components/console/debug_formatter.png
index 7482f39851f..4ba2c0c2b57 100644
Binary files a/_images/components/console/debug_formatter.png and b/_images/components/console/debug_formatter.png differ
diff --git a/_images/components/console/process-helper-debug.png b/_images/components/console/process-helper-debug.png
index 282e1336389..96c5c316739 100644
Binary files a/_images/components/console/process-helper-debug.png and b/_images/components/console/process-helper-debug.png differ
diff --git a/_images/components/console/process-helper-error-debug.png b/_images/components/console/process-helper-error-debug.png
index 8d1145478f2..48f6c7258d4 100644
Binary files a/_images/components/console/process-helper-error-debug.png and b/_images/components/console/process-helper-error-debug.png differ
diff --git a/_images/components/console/process-helper-verbose.png b/_images/components/console/process-helper-verbose.png
index c4c912e1433..abdff9812b0 100644
Binary files a/_images/components/console/process-helper-verbose.png and b/_images/components/console/process-helper-verbose.png differ
diff --git a/_images/components/console/progress.png b/_images/components/console/progress.png
deleted file mode 100644
index c126bff5252..00000000000
Binary files a/_images/components/console/progress.png and /dev/null differ
diff --git a/_images/components/console/progressbar.gif b/_images/components/console/progressbar.gif
index 6c80e6e897f..0746e399354 100644
Binary files a/_images/components/console/progressbar.gif and b/_images/components/console/progressbar.gif differ
diff --git a/_images/components/form/general_flow.png b/_images/components/form/general_flow.png
deleted file mode 100644
index 31650e52af6..00000000000
Binary files a/_images/components/form/general_flow.png and /dev/null differ
diff --git a/_images/components/form/set_data_flow.png b/_images/components/form/set_data_flow.png
deleted file mode 100644
index 3cd4b1e2f7b..00000000000
Binary files a/_images/components/form/set_data_flow.png and /dev/null differ
diff --git a/_images/components/form/submission_flow.png b/_images/components/form/submission_flow.png
deleted file mode 100644
index a3c6e9cfb90..00000000000
Binary files a/_images/components/form/submission_flow.png and /dev/null differ
diff --git a/_images/components/messenger/basic_cycle.png b/_images/components/messenger/basic_cycle.png
new file mode 100644
index 00000000000..a0558968cbb
Binary files /dev/null and b/_images/components/messenger/basic_cycle.png differ
diff --git a/_images/components/messenger/overview.svg b/_images/components/messenger/overview.svg
index 94737e7a6da..4b82c203756 100644
--- a/_images/components/messenger/overview.svg
+++ b/_images/components/messenger/overview.svg
@@ -1 +1 @@
-
+
diff --git a/_images/components/scheduler/generate_consume.png b/_images/components/scheduler/generate_consume.png
new file mode 100644
index 00000000000..269281266a5
Binary files /dev/null and b/_images/components/scheduler/generate_consume.png differ
diff --git a/_images/components/scheduler/scheduler_cycle.png b/_images/components/scheduler/scheduler_cycle.png
new file mode 100644
index 00000000000..18addb37d91
Binary files /dev/null and b/_images/components/scheduler/scheduler_cycle.png differ
diff --git a/_images/components/serializer/serializer_workflow.svg b/_images/components/serializer/serializer_workflow.svg
deleted file mode 100644
index f3906506878..00000000000
--- a/_images/components/serializer/serializer_workflow.svg
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/_images/components/var_dumper/10-uninitialized.png b/_images/components/var_dumper/10-uninitialized.png
new file mode 100644
index 00000000000..735731b83b5
Binary files /dev/null and b/_images/components/var_dumper/10-uninitialized.png differ
diff --git a/_images/components/workflow/blogpost.png b/_images/components/workflow/blogpost.png
index 38e29250eb1..b7f51eabb43 100644
Binary files a/_images/components/workflow/blogpost.png and b/_images/components/workflow/blogpost.png differ
diff --git a/_images/components/workflow/blogpost_mermaid.png b/_images/components/workflow/blogpost_mermaid.png
new file mode 100644
index 00000000000..7a4d3a57cfe
Binary files /dev/null and b/_images/components/workflow/blogpost_mermaid.png differ
diff --git a/_images/components/workflow/blogpost_metadata.png b/_images/components/workflow/blogpost_metadata.png
new file mode 100644
index 00000000000..783f51c6ccf
Binary files /dev/null and b/_images/components/workflow/blogpost_metadata.png differ
diff --git a/_images/components/workflow/blogpost_puml.png b/_images/components/workflow/blogpost_puml.png
index 14d45c8b40f..efe543a6f8e 100644
Binary files a/_images/components/workflow/blogpost_puml.png and b/_images/components/workflow/blogpost_puml.png differ
diff --git a/_images/components/workflow/states_transitions.png b/_images/components/workflow/states_transitions.png
index 1e68f9ca597..d1f54391afd 100644
Binary files a/_images/components/workflow/states_transitions.png and b/_images/components/workflow/states_transitions.png differ
diff --git a/_images/contributing/code/stack-trace.gif b/_images/contributing/code/stack-trace.gif
new file mode 100644
index 00000000000..97a2043448d
Binary files /dev/null and b/_images/contributing/code/stack-trace.gif differ
diff --git a/_images/contributing/docs-github-create-pr.png b/_images/contributing/docs-github-create-pr.png
index 29fe22f5dbd..43b6842ffc2 100644
Binary files a/_images/contributing/docs-github-create-pr.png and b/_images/contributing/docs-github-create-pr.png differ
diff --git a/_images/contributing/docs-github-edit-page.png b/_images/contributing/docs-github-edit-page.png
index c34f13f0889..b739497f70f 100644
Binary files a/_images/contributing/docs-github-edit-page.png and b/_images/contributing/docs-github-edit-page.png differ
diff --git a/_images/contributing/docs-pull-request-change-base.png b/_images/contributing/docs-pull-request-change-base.png
index d824e8ef1bc..791901b8ec6 100644
Binary files a/_images/contributing/docs-pull-request-change-base.png and b/_images/contributing/docs-pull-request-change-base.png differ
diff --git a/_images/contributing/docs-pull-request-symfonycloud.png b/_images/contributing/docs-pull-request-symfonycloud.png
deleted file mode 100644
index 0c485c1491c..00000000000
Binary files a/_images/contributing/docs-pull-request-symfonycloud.png and /dev/null differ
diff --git a/_images/controller/error_pages/exceptions-in-dev-environment.png b/_images/controller/error_pages/exceptions-in-dev-environment.png
index 74128990e57..e1fba2bebf9 100644
Binary files a/_images/controller/error_pages/exceptions-in-dev-environment.png and b/_images/controller/error_pages/exceptions-in-dev-environment.png differ
diff --git a/_images/docs-pull-request-change-base.png b/_images/docs-pull-request-change-base.png
deleted file mode 100644
index d824e8ef1bc..00000000000
Binary files a/_images/docs-pull-request-change-base.png and /dev/null differ
diff --git a/_images/doctrine/mapping_relations.png b/_images/doctrine/mapping_relations.png
deleted file mode 100644
index a679f9cb317..00000000000
Binary files a/_images/doctrine/mapping_relations.png and /dev/null differ
diff --git a/_images/doctrine/mapping_relations.svg b/_images/doctrine/mapping_relations.svg
new file mode 100644
index 00000000000..7dc8979cb1a
--- /dev/null
+++ b/_images/doctrine/mapping_relations.svg
@@ -0,0 +1,602 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/doctrine/mapping_relations_proxy.png b/_images/doctrine/mapping_relations_proxy.png
deleted file mode 100644
index 935153291d4..00000000000
Binary files a/_images/doctrine/mapping_relations_proxy.png and /dev/null differ
diff --git a/_images/doctrine/mapping_relations_proxy.svg b/_images/doctrine/mapping_relations_proxy.svg
new file mode 100644
index 00000000000..634d1b0add2
--- /dev/null
+++ b/_images/doctrine/mapping_relations_proxy.svg
@@ -0,0 +1,926 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/doctrine/mapping_single_entity.png b/_images/doctrine/mapping_single_entity.png
deleted file mode 100644
index 6f88c6cacfa..00000000000
Binary files a/_images/doctrine/mapping_single_entity.png and /dev/null differ
diff --git a/_images/doctrine/mapping_single_entity.svg b/_images/doctrine/mapping_single_entity.svg
new file mode 100644
index 00000000000..5d517c85fb1
--- /dev/null
+++ b/_images/doctrine/mapping_single_entity.svg
@@ -0,0 +1,469 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/form/data-transformer-types.png b/_images/form/data-transformer-types.png
deleted file mode 100644
index 950acd39ea7..00000000000
Binary files a/_images/form/data-transformer-types.png and /dev/null differ
diff --git a/_images/form/data-transformer-types.svg b/_images/form/data-transformer-types.svg
new file mode 100644
index 00000000000..9393b224f89
--- /dev/null
+++ b/_images/form/data-transformer-types.svg
@@ -0,0 +1,178 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/form/form-custom-type-postal-address-fragment-names.svg b/_images/form/form-custom-type-postal-address-fragment-names.svg
index 9b6092c9808..db9463b8327 100644
--- a/_images/form/form-custom-type-postal-address-fragment-names.svg
+++ b/_images/form/form-custom-type-postal-address-fragment-names.svg
@@ -1 +1 @@
-
+
diff --git a/_images/form/form-custom-type-postal-address.svg b/_images/form/form-custom-type-postal-address.svg
index ab0fde8af3a..42ffce4067f 100644
--- a/_images/form/form-custom-type-postal-address.svg
+++ b/_images/form/form-custom-type-postal-address.svg
@@ -1 +1 @@
-
+
diff --git a/_images/form/form_prepopulation_workflow.svg b/_images/form/form_prepopulation_workflow.svg
new file mode 100644
index 00000000000..c908f5c5a76
--- /dev/null
+++ b/_images/form/form_prepopulation_workflow.svg
@@ -0,0 +1,253 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/form/form_submission_workflow.svg b/_images/form/form_submission_workflow.svg
new file mode 100644
index 00000000000..d6d138ee61a
--- /dev/null
+++ b/_images/form/form_submission_workflow.svg
@@ -0,0 +1,334 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/form/form_workflow.svg b/_images/form/form_workflow.svg
new file mode 100644
index 00000000000..2dbacbbf096
--- /dev/null
+++ b/_images/form/form_workflow.svg
@@ -0,0 +1,263 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/form/tailwindcss-form.png b/_images/form/tailwindcss-form.png
new file mode 100644
index 00000000000..8a290749149
Binary files /dev/null and b/_images/form/tailwindcss-form.png differ
diff --git a/_images/http/xkcd-full.png b/_images/http/xkcd-full.png
deleted file mode 100644
index d5b01ea32b9..00000000000
Binary files a/_images/http/xkcd-full.png and /dev/null differ
diff --git a/_images/http/xkcd-full.svg b/_images/http/xkcd-full.svg
new file mode 100644
index 00000000000..da590c2b97e
--- /dev/null
+++ b/_images/http/xkcd-full.svg
@@ -0,0 +1,324 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/http/xkcd-request.png b/_images/http/xkcd-request.png
deleted file mode 100644
index 310713d304c..00000000000
Binary files a/_images/http/xkcd-request.png and /dev/null differ
diff --git a/_images/http/xkcd-request.svg b/_images/http/xkcd-request.svg
new file mode 100644
index 00000000000..6a21280ca34
--- /dev/null
+++ b/_images/http/xkcd-request.svg
@@ -0,0 +1,191 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/install/deprecations-in-profiler.png b/_images/install/deprecations-in-profiler.png
index a8abcae32b7..3d3f9a98a4a 100644
Binary files a/_images/install/deprecations-in-profiler.png and b/_images/install/deprecations-in-profiler.png differ
diff --git a/_images/mercure/discovery.png b/_images/mercure/discovery.png
deleted file mode 100644
index 0ef38271de6..00000000000
Binary files a/_images/mercure/discovery.png and /dev/null differ
diff --git a/_images/mercure/discovery.svg b/_images/mercure/discovery.svg
new file mode 100644
index 00000000000..ed18381068a
--- /dev/null
+++ b/_images/mercure/discovery.svg
@@ -0,0 +1,294 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/mercure/hub.svg b/_images/mercure/hub.svg
new file mode 100644
index 00000000000..6b5e496e3c6
--- /dev/null
+++ b/_images/mercure/hub.svg
@@ -0,0 +1,196 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/mercure/schema.png b/_images/mercure/schema.png
deleted file mode 100644
index 4616046e5cc..00000000000
Binary files a/_images/mercure/schema.png and /dev/null differ
diff --git a/_images/notifier/microsoft_teams/message-card.png b/_images/notifier/microsoft_teams/message-card.png
new file mode 100644
index 00000000000..05f505fb3e0
Binary files /dev/null and b/_images/notifier/microsoft_teams/message-card.png differ
diff --git a/_images/notifier/microsoft_teams/message.png b/_images/notifier/microsoft_teams/message.png
new file mode 100644
index 00000000000..5c4c7f11ed1
Binary files /dev/null and b/_images/notifier/microsoft_teams/message.png differ
diff --git a/_images/notifier/slack/field-method.png b/_images/notifier/slack/field-method.png
new file mode 100644
index 00000000000..d77a60e6a2e
Binary files /dev/null and b/_images/notifier/slack/field-method.png differ
diff --git a/_images/notifier/slack/message-reply.png b/_images/notifier/slack/message-reply.png
new file mode 100644
index 00000000000..9a60e4573ab
Binary files /dev/null and b/_images/notifier/slack/message-reply.png differ
diff --git a/_images/notifier/slack/slack-footer.png b/_images/notifier/slack/slack-footer.png
new file mode 100644
index 00000000000..a53952c78f6
Binary files /dev/null and b/_images/notifier/slack/slack-footer.png differ
diff --git a/_images/notifier/slack/slack-header.png b/_images/notifier/slack/slack-header.png
new file mode 100644
index 00000000000..a7caf915d8f
Binary files /dev/null and b/_images/notifier/slack/slack-header.png differ
diff --git a/_images/profiler/web-interface.png b/_images/profiler/web-interface.png
index 2e6c6061892..b107f6427d7 100644
Binary files a/_images/profiler/web-interface.png and b/_images/profiler/web-interface.png differ
diff --git a/_images/quick_tour/no_routes_page.png b/_images/quick_tour/no_routes_page.png
index 382950b6ef5..030953a17b1 100644
Binary files a/_images/quick_tour/no_routes_page.png and b/_images/quick_tour/no_routes_page.png differ
diff --git a/_images/quick_tour/web_debug_toolbar.png b/_images/quick_tour/web_debug_toolbar.png
deleted file mode 100644
index 465020380cb..00000000000
Binary files a/_images/quick_tour/web_debug_toolbar.png and /dev/null differ
diff --git a/_images/rate_limiter/fixed_window.svg b/_images/rate_limiter/fixed_window.svg
new file mode 100644
index 00000000000..83d5f6e79ac
--- /dev/null
+++ b/_images/rate_limiter/fixed_window.svg
@@ -0,0 +1,84 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 10:00
+
+
+ 10:30
+
+
+ 11:00
+
+
+ 11:30
+
+
+ 12:00
+
+
+
+
+
+
+
+ 12:30
+
+
+ 13:00
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 1 hour window
+
+
+ 1 hour window
+
+
+
+
+
+ 1 hour window
+
+
+
+
+ 13:15
+
+
+
diff --git a/_images/rate_limiter/sliding_window.svg b/_images/rate_limiter/sliding_window.svg
new file mode 100644
index 00000000000..2c565615441
--- /dev/null
+++ b/_images/rate_limiter/sliding_window.svg
@@ -0,0 +1,65 @@
+
+
+
+
+
+
+
+
+
+ 10:00
+
+
+ 10:30
+
+
+ 11:00
+
+
+ 11:30
+
+
+ 12:00
+
+
+
+
+
+ 12:30
+
+
+ 13:00
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 1 hour window
+
+
+
+
+
+ 13:15
+
+
+
+
+
+
diff --git a/_images/rate_limiter/token_bucket.svg b/_images/rate_limiter/token_bucket.svg
new file mode 100644
index 00000000000..29d6fc8f103
--- /dev/null
+++ b/_images/rate_limiter/token_bucket.svg
@@ -0,0 +1,83 @@
+
+
+
+ 10:00
+
+
+ 10:30
+
+
+ 11:00
+
+
+ 11:30
+
+
+ 12:00
+
+
+
+
+
+
+
+ 12:30
+
+
+ 13:00
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 13:15
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/release-process.jpg b/_images/release-process.jpg
deleted file mode 100644
index 9868404b07f..00000000000
Binary files a/_images/release-process.jpg and /dev/null differ
diff --git a/_images/security/anonymous_wdt.png b/_images/security/anonymous_wdt.png
index 8dbf1cd8298..80736afce39 100644
Binary files a/_images/security/anonymous_wdt.png and b/_images/security/anonymous_wdt.png differ
diff --git a/_images/security/login_link_email.png b/_images/security/login_link_email.png
new file mode 100644
index 00000000000..8331b878f68
Binary files /dev/null and b/_images/security/login_link_email.png differ
diff --git a/_images/security/profiler-badges.png b/_images/security/profiler-badges.png
new file mode 100644
index 00000000000..a19f8539581
Binary files /dev/null and b/_images/security/profiler-badges.png differ
diff --git a/_images/security/security_events.svg b/_images/security/security_events.svg
new file mode 100644
index 00000000000..f1b93923da6
--- /dev/null
+++ b/_images/security/security_events.svg
@@ -0,0 +1,338 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/serializer/serializer_workflow.svg b/_images/serializer/serializer_workflow.svg
new file mode 100644
index 00000000000..b6e9c254778
--- /dev/null
+++ b/_images/serializer/serializer_workflow.svg
@@ -0,0 +1,283 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/_images/sources/README.md b/_images/sources/README.md
index 9e40e0ac884..84810a9783d 100644
--- a/_images/sources/README.md
+++ b/_images/sources/README.md
@@ -1,8 +1,8 @@
-How to Create Symfony Diagrams
-==============================
+How to Create Symfony Images
+============================
-Creating the Diagram
---------------------
+Creating Diagrams
+-----------------
* Use [Dia][1] as the diagramming application;
* Use [PT Sans Narrow][2] as the only font in all diagrams (if possible, use
@@ -21,38 +21,82 @@ Creating the Diagram
In case of doubt, check the existing diagrams or ask to the
[Symfony Documentation Team][3].
-Saving and Exporting the Diagram
---------------------------------
+### Saving and Exporting the Diagram
* Save the original diagram in `*.dia` format in `_images/sources/`;
* Export the diagram to SVG format and save it in `_images/`.
-Including the Diagram in the Symfony Docs
------------------------------------------
+Important: choose "Cairo Scalable Vector Graphics (.svg)" format instead of
+plain " Scalable Vector Graphics (.svg)" because the former is the only format
+that transforms text into vector shapes (resulting file is larger in size, but
+it's truly portable because text is displayed the same even if you don't have
+some fonts installed).
+
+### Including the Diagram in the Symfony Docs
Use the following snippet to embed the diagram in the docs:
```
.. raw:: html
-
+
```
-Reasoning
----------
+### Reasoning
* Dia was chosen because it's one of the few applications which are free, open
source and compatible with Linux, macOS and Windows.
* Font, colors and line widths were chosen to be similar to the diagrams used
in the best tech books.
-Troubleshooting
----------------
+### Troubleshooting
* On some macOS systems, Dia cannot be executed as a regular application and
you must run the following console command instead:
`export DISPLAY=:0 && /Applications/Dia.app/Contents/Resources/bin/dia`
+Creating Console Screenshots
+----------------------------
+
+* Use [Asciinema][4] to record the console session locally:
+
+ ```
+ $ asciinema rec -c bash recording.cast
+ ```
+* Use `$ ` as the prompt in recordings. E.g. if you're using Bash, add the
+ following lines to your ``.bashrc``:
+
+ ```
+ if [ "$ASCIINEMA_REC" = "1" ]; then
+ PS1="\e[37m$ \e[0m"
+ fi
+ ```
+* Save the generated asciicast in `_images/sources/`.
+
+### Rendering the Recording
+
+Rendering the recording can be a difficult task. The [documentation team][3]
+is always ready to help you with this task (e.g. you can open a PR with
+only the asciicast file).
+
+* Use [agg][5] to generated a GIF file from the recording;
+* Install the [JetBrains Mono][6] font;
+* Use the ``_images/sources/ascii-render.sh`` file to call agg:
+
+ ```
+ AGG_PATH=/path/to/agg ./_images/sources/ascii-render.sh recording.cast --cols 45 --rows 20
+ ```
+
+ This utility configures a predefined theme;
+* Always configure `--cols`` (width) and ``--rows`` (height), try to use as
+ low as possible numbers. Do not exceed 70 columns;
+* Save the generated GIF file in `_images/`.
+
[1]: http://dia-installer.de/
[2]: https://fonts.google.com/specimen/PT+Sans+Narrow
-[3]: https://symfony.com/doc/current/contributing/code/core_team.html
+[3]: https://symfony.com/doc/current/contributing/core_team.html
+[4]: https://github.com/asciinema/asciinema
+[5]: https://github.com/asciinema/agg
+[6]: https://www.jetbrains.com/lp/mono/
diff --git a/_images/sources/ascii-render.sh b/_images/sources/ascii-render.sh
new file mode 100755
index 00000000000..e72be572390
--- /dev/null
+++ b/_images/sources/ascii-render.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env sh
+case "$1" in
+ ''|help|-h)
+ echo "ansi-render.sh RECORDING [options]"
+ echo ""
+ echo " RECORDING: path to the .cast file generated by asciinema"
+ echo " [options]: optional options to be passed to agg"
+ ;;
+ *)
+ recording=$1
+ extra_options=
+ if [ $# -gt 1 ]; then
+ shift
+ extra_options=$@
+ fi
+
+ # optionally, use this green color: 1f4631
+ ${AGG_PATH:-agg} \
+ --theme 18202a,f9fafb,f9fafb,ff7b72,7ee787,ffa657,79c0ff,d2a8ff,a5d6ff,f9fafb,8b949e,ff7b72,00c300,ffa657,79c0ff,d2a8ff,a5d6ff,f9fafb --line-height 1.6 \
+ --font-family 'JetBrains Mono' \
+ $extra_options \
+ $recording $(echo $recording | sed "s/cast/gif/")
+ ;;
+esac
diff --git a/_images/sources/components/console/completion.cast b/_images/sources/components/console/completion.cast
new file mode 100644
index 00000000000..c268863e9b0
--- /dev/null
+++ b/_images/sources/components/console/completion.cast
@@ -0,0 +1,37 @@
+{"version": 2, "width": 76, "height": 30, "timestamp": 1663253713, "env": {"SHELL": "/usr/bin/fish", "TERM": "st-256color"}}
+[0.00798, "o", "\u001b[?2004h\u001b[90m$ \u001b[0m"]
+[0.614685, "o", "b"]
+[0.776549, "o", "i"]
+[0.86682, "o", "n"]
+[1.092426, "o", "/"]
+[1.332671, "o", "c"]
+[1.55068, "o", "o"]
+[1.630651, "o", "n"]
+[1.784584, "o", "s"]
+[1.873108, "o", "o"]
+[2.074652, "o", "l"]
+[2.180433, "o", "e"]
+[2.260475, "o", " "]
+[2.696628, "o", "\u0007"]
+[2.947263, "o", "\r\nabout debug:event-dispatcher\r\nassets:install debug:router\r\ncache:clear help\r\ncache:pool:clear lint:container\r\ncache:pool:delete lint:yaml\r\ncache:pool:list list\r\ncache:pool:prune router:match\r\ncache:warmup secrets:decrypt-to-local\r\ncompletion secrets:encrypt-from-local\r\nconfig:dump-reference secrets:generate-keys\r\ndebug:autowiring secrets:list\r\ndebug:config secrets:remove\r\ndebug:container secrets:set\r\ndebug:dotenv \r\n\u001b[37m$ \u001b[0mbin/console "]
+[3.614479, "o", "s"]
+[3.802449, "o", "e"]
+[4.205631, "o", "\u0007crets:"]
+[4.520435, "o", "r"]
+[4.598031, "o", "e"]
+[5.026287, "o", "move "]
+[5.47041, "o", "\u0007SOME_"]
+[5.673941, "o", "\u0007"]
+[6.024086, "o", "\r\nSOME_OTHER_SECRET SOME_SECRET \r\n\u001b[37m$ \u001b[0mbin/console secrets:remove SOME_"]
+[6.770627, "o", "O"]
+[7.14335, "o", "THER_SECRET "]
+[7.724482, "o", "\r\n\u001b[?2004l\r"]
+[7.776657, "o", "\r\n"]
+[7.779108, "o", "\u001b[30;42m \u001b[39;49m\r\n\u001b[30;42m [OK] Secret \"SOME_OTHER_SECRET\" removed from \"config/secrets/dev/\". \u001b[39;49m\r\n\u001b[30;42m \u001b[39;49m\r\n\r\n"]
+[7.782993, "o", "\u001b[?2004h\u001b[37m$ \u001b[0m"]
+[9.214537, "o", "e"]
+[9.522429, "o", "x"]
+[9.690371, "o", "i"]
+[9.85446, "o", "t"]
+[10.292412, "o", "\r\n\u001b[?2004l\r"]
+[10.292526, "o", "exit\r\n"]
diff --git a/_images/sources/components/console/cursor.cast b/_images/sources/components/console/cursor.cast
new file mode 100644
index 00000000000..be2f2f6c351
--- /dev/null
+++ b/_images/sources/components/console/cursor.cast
@@ -0,0 +1,49 @@
+{"version": 2, "width": 191, "height": 30, "timestamp": 1663251833, "env": {"SHELL": "/usr/bin/fish", "TERM": "st-256color"}}
+[0.007941, "o", "\u001b[?2004h\u001b[90m$ \u001b[0m"]
+[0.566363, "o", "c"]
+[0.643353, "o", "l"]
+[0.762325, "o", "e"]
+[0.952363, "o", "a"]
+[0.995878, "o", "r"]
+[1.107784, "o", "\r\n\u001b[?2004l\r"]
+[1.109766, "o", "\u001b[H\u001b[2J"]
+[1.109946, "o", "\u001b[?2004h\u001b[30m$ \u001b[0m"]
+[1.653461, "o", "p"]
+[1.772323, "o", "h"]
+[1.856444, "o", "p"]
+[1.980339, "o", " "]
+[2.15827, "o", "c"]
+[2.273242, "o", "u"]
+[2.402231, "o", "r"]
+[2.563066, "o", "s"]
+[2.760266, "o", "o"]
+[2.900252, "o", "r"]
+[3.020537, "o", "."]
+[3.316404, "o", "p"]
+[3.403213, "o", "h"]
+[3.483391, "o", "p"]
+[3.820273, "o", "\r\n\u001b[?2004l\r"]
+[3.845697, "o", "\u001b[6;9H#"]
+[4.045942, "o", "\u001b[8;9H#"]
+[4.246327, "o", "\u001b[8;2H#####"]
+[4.446737, "o", "\u001b[2;9H#######"]
+[4.647128, "o", "\u001b[7;7H#"]
+[4.84749, "o", "\u001b[3;9H#"]
+[5.047857, "o", "\u001b[7;9H#"]
+[5.248246, "o", "\u001b[4;9H#"]
+[5.448622, "o", "\u001b[2;2H#####"]
+[5.648999, "o", "\u001b[3;7H#"]
+[5.849378, "o", "\u001b[5;9H#####"]
+[6.049711, "o", "\u001b[3;1H#"]
+[6.250118, "o", "\u001b[7;1H#"]
+[6.45056, "o", "\u001b[5;2H#####"]
+[6.650897, "o", "\u001b[4;1H#"]
+[6.851281, "o", "\u001b[6;7H#"]
+[7.051644, "o", "\u001b[9;1H"]
+[7.058802, "o", "\u001b[?2004h\u001b[30m$ \u001b[0m"]
+[7.657612, "o", "e"]
+[7.846956, "o", "x"]
+[7.949451, "o", "i"]
+[8.0893, "o", "t"]
+[8.201144, "o", "\r\n\u001b[?2004l\r"]
+[8.201227, "o", "exit\r\n"]
diff --git a/_images/sources/components/console/progress.cast b/_images/sources/components/console/progress.cast
new file mode 100644
index 00000000000..9c5244b37e2
--- /dev/null
+++ b/_images/sources/components/console/progress.cast
@@ -0,0 +1,57 @@
+{"version": 2, "width": 191, "height": 17, "timestamp": 1663423221, "env": {"SHELL": "/usr/bin/fish", "TERM": "st-256color"}}
+[0.008171, "o", "\u001b[?2004h\u001b[90m$ \u001b[0m"]
+[0.385858, "o", "p"]
+[0.577979, "o", "h"]
+[0.768282, "o", "p"]
+[0.96433, "o", " "]
+[1.133645, "o", "p"]
+[1.262693, "o", "r"]
+[1.385832, "o", "o"]
+[1.476876, "o", "g"]
+[1.652322, "o", "r"]
+[1.722357, "o", "e"]
+[1.935395, "o", "s"]
+[2.083915, "o", "s"]
+[2.200109, "o", "."]
+[2.403686, "o", "p"]
+[2.510201, "o", "h"]
+[2.602756, "o", "p"]
+[2.909974, "o", "\r\n\u001b[?2004l\r"]
+[2.935647, "o", "\u001b[34m Starting the demo... fingers crossed \u001b[39m\r\n 0/15 \u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 0%\r\n < 1 sec 4.0 MiB"]
+[3.418022, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K"]
+[3.419196, "o", "\u001b[34m Starting the demo... fingers crossed \u001b[39m\r\n 2/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 13%\r\n < 1 sec 6.0 MiB"]
+[3.66102, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G"]
+[3.661071, "o", "\u001b[2K"]
+[3.661731, "o", "\u001b[34m Starting the demo... fingers crossed \u001b[39m\r\n 3/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 20%\r\n 5 secs 6.0 MiB"]
+[4.143554, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K"]
+[4.14385, "o", "\u001b[34m Starting the demo... fingers crossed \u001b[39m\r\n 5/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 33%\r\n 3 secs 6.5 MiB"]
+[4.385367, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K"]
+[4.38612, "o", "\u001b[34m Looks good to me... \u001b[39m\r\n 6/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 40%\r\n 3 secs 7.1 MiB"]
+[4.868053, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K"]
+[4.86852, "o", "\u001b[34m Looks good to me... \u001b[39m\r\n 8/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 53%\r\n 4 secs 8.1 MiB"]
+[5.110341, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K"]
+[5.11133, "o", "\u001b[34m Looks good to me... \u001b[39m\r\n 9/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 60%\r\n 3 secs 8.6 MiB"]
+[5.593851, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G"]
+[5.593924, "o", "\u001b[2K"]
+[5.594818, "o", "\u001b[34m Looks good to me... \u001b[39m\r\n11/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 73%\r\n 4 secs 9.6 MiB"]
+[5.836301, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K"]
+[5.836831, "o", "\u001b[34m Looks good to me... \u001b[39m\r\n12/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m\u001b[41m \u001b[49m 80%\r\n 4 secs 10.1 MiB"]
+[6.31877, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K\u001b[1A"]
+[6.318814, "o", "\u001b[1G\u001b[2K"]
+[6.319403, "o", "\u001b[34m Looks good to me... \u001b[39m\r\n14/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[32;41m\u001b[39;49m\u001b[41m \u001b[49m 93%\r\n 3 secs 11.1 MiB"]
+[6.561359, "o", "\u001b[1G\u001b[2K\u001b[1A"]
+[6.561561, "o", "\u001b[1G\u001b[2K\u001b[1A\u001b[1G\u001b[2K"]
+[6.562504, "o", "\u001b[34m Looks good to me... \u001b[39m\r\n15/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m 100%\r\n 4 secs 11.6 MiB"]
+[6.563772, "o", "\u001b[1G"]
+[6.563824, "o", "\u001b[2K\u001b[1A"]
+[6.563875, "o", "\u001b[1G\u001b[2K"]
+[6.563926, "o", "\u001b[1A\u001b[1G\u001b[2K"]
+[6.564766, "o", "\u001b[34m Thanks bye! \u001b[39m\r\n15/15 \u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m\u001b[42m \u001b[49m 100%\r\n 4 secs 11.6 MiB"]
+[6.564805, "o", "\r\n\r\n"]
+[6.570516, "o", "\u001b[?2004h"]
+[6.570537, "o", "\u001b[90m$ \u001b[0m"]
+[8.441927, "o", "e"]
+[8.646449, "o", "x"]
+[8.76668, "o", "i"]
+[8.897799, "o", "t"]
+[9.091614, "o", "\r\n\u001b[?2004l\rexit\r\n"]
diff --git a/_images/sources/components/messenger/overview.dia b/_images/sources/components/messenger/overview.dia
index 55ee153439e..b0e2edaeab2 100644
Binary files a/_images/sources/components/messenger/overview.dia and b/_images/sources/components/messenger/overview.dia differ
diff --git a/_images/sources/components/serializer/serializer_workflow.dia b/_images/sources/components/serializer/serializer_workflow.dia
deleted file mode 100644
index 6cb44280d0d..00000000000
Binary files a/_images/sources/components/serializer/serializer_workflow.dia and /dev/null differ
diff --git a/_images/sources/doctrine/mapping_relations.dia b/_images/sources/doctrine/mapping_relations.dia
new file mode 100644
index 00000000000..5703e1b781c
Binary files /dev/null and b/_images/sources/doctrine/mapping_relations.dia differ
diff --git a/_images/sources/doctrine/mapping_relations_proxy.dia b/_images/sources/doctrine/mapping_relations_proxy.dia
new file mode 100644
index 00000000000..1f491e9e2ef
Binary files /dev/null and b/_images/sources/doctrine/mapping_relations_proxy.dia differ
diff --git a/_images/sources/doctrine/mapping_single_entity.dia b/_images/sources/doctrine/mapping_single_entity.dia
new file mode 100644
index 00000000000..5a9dc21889c
Binary files /dev/null and b/_images/sources/doctrine/mapping_single_entity.dia differ
diff --git a/_images/sources/form/data-transformer-types.dia b/_images/sources/form/data-transformer-types.dia
new file mode 100644
index 00000000000..972b973a36d
Binary files /dev/null and b/_images/sources/form/data-transformer-types.dia differ
diff --git a/_images/sources/form/form-custom-type-postal-address-fragment-names.dia b/_images/sources/form/form-custom-type-postal-address-fragment-names.dia
index aebdadb4170..ca12fcdeadc 100644
Binary files a/_images/sources/form/form-custom-type-postal-address-fragment-names.dia and b/_images/sources/form/form-custom-type-postal-address-fragment-names.dia differ
diff --git a/_images/sources/form/form-custom-type-postal-address.dia b/_images/sources/form/form-custom-type-postal-address.dia
index 35a1eaebfd6..1b7c6226315 100644
Binary files a/_images/sources/form/form-custom-type-postal-address.dia and b/_images/sources/form/form-custom-type-postal-address.dia differ
diff --git a/_images/sources/form/form_events.dia b/_images/sources/form/form_events.dia
new file mode 100644
index 00000000000..8e7afb1cb83
Binary files /dev/null and b/_images/sources/form/form_events.dia differ
diff --git a/_images/sources/form/form_prepopulation_workflow.dia b/_images/sources/form/form_prepopulation_workflow.dia
new file mode 100644
index 00000000000..1d6d450fed1
Binary files /dev/null and b/_images/sources/form/form_prepopulation_workflow.dia differ
diff --git a/_images/sources/form/form_submission_workflow.dia b/_images/sources/form/form_submission_workflow.dia
new file mode 100644
index 00000000000..cc08f117878
Binary files /dev/null and b/_images/sources/form/form_submission_workflow.dia differ
diff --git a/_images/sources/form/form_workflow.dia b/_images/sources/form/form_workflow.dia
new file mode 100644
index 00000000000..30f9acabe2b
Binary files /dev/null and b/_images/sources/form/form_workflow.dia differ
diff --git a/_images/sources/http/xkcd-full.dia b/_images/sources/http/xkcd-full.dia
new file mode 100644
index 00000000000..a730d01c3ef
Binary files /dev/null and b/_images/sources/http/xkcd-full.dia differ
diff --git a/_images/sources/http/xkcd-request.dia b/_images/sources/http/xkcd-request.dia
new file mode 100644
index 00000000000..3796228bf1d
Binary files /dev/null and b/_images/sources/http/xkcd-request.dia differ
diff --git a/_images/sources/mercure/discovery.dia b/_images/sources/mercure/discovery.dia
new file mode 100644
index 00000000000..3db5c86f020
Binary files /dev/null and b/_images/sources/mercure/discovery.dia differ
diff --git a/_images/sources/mercure/hub.dia b/_images/sources/mercure/hub.dia
new file mode 100644
index 00000000000..b0dfb9d88d2
Binary files /dev/null and b/_images/sources/mercure/hub.dia differ
diff --git a/_images/sources/rate_limiter/fixed_window.dia b/_images/sources/rate_limiter/fixed_window.dia
new file mode 100644
index 00000000000..16282a2dcce
Binary files /dev/null and b/_images/sources/rate_limiter/fixed_window.dia differ
diff --git a/_images/sources/rate_limiter/sliding_window.dia b/_images/sources/rate_limiter/sliding_window.dia
new file mode 100644
index 00000000000..e16275d8995
Binary files /dev/null and b/_images/sources/rate_limiter/sliding_window.dia differ
diff --git a/_images/sources/rate_limiter/token_bucket.dia b/_images/sources/rate_limiter/token_bucket.dia
new file mode 100644
index 00000000000..16761971337
Binary files /dev/null and b/_images/sources/rate_limiter/token_bucket.dia differ
diff --git a/_images/sources/security/security_events.dia b/_images/sources/security/security_events.dia
new file mode 100644
index 00000000000..0a8afa73179
Binary files /dev/null and b/_images/sources/security/security_events.dia differ
diff --git a/_images/sources/serializer/serializer_workflow.dia b/_images/sources/serializer/serializer_workflow.dia
new file mode 100644
index 00000000000..3e2ea62558f
Binary files /dev/null and b/_images/sources/serializer/serializer_workflow.dia differ
diff --git a/_images/translation/pseudolocalization-interface-original.png b/_images/translation/pseudolocalization-interface-original.png
new file mode 100644
index 00000000000..d89f4e63a24
Binary files /dev/null and b/_images/translation/pseudolocalization-interface-original.png differ
diff --git a/_images/translation/pseudolocalization-interface-translated.png b/_images/translation/pseudolocalization-interface-translated.png
new file mode 100644
index 00000000000..496d5a0f86f
Binary files /dev/null and b/_images/translation/pseudolocalization-interface-translated.png differ
diff --git a/_images/translation/pseudolocalization-symfony-demo-disabled.png b/_images/translation/pseudolocalization-symfony-demo-disabled.png
new file mode 100644
index 00000000000..1a7472bd41f
Binary files /dev/null and b/_images/translation/pseudolocalization-symfony-demo-disabled.png differ
diff --git a/_images/translation/pseudolocalization-symfony-demo-enabled.png b/_images/translation/pseudolocalization-symfony-demo-enabled.png
new file mode 100644
index 00000000000..a23300a7271
Binary files /dev/null and b/_images/translation/pseudolocalization-symfony-demo-enabled.png differ
diff --git a/_includes/_annotation_loader_tip.rst.inc b/_includes/_annotation_loader_tip.rst.inc
deleted file mode 100644
index 0f4267b07f5..00000000000
--- a/_includes/_annotation_loader_tip.rst.inc
+++ /dev/null
@@ -1,19 +0,0 @@
-.. note::
-
- In order to use the annotation loader, you should have installed the
- ``doctrine/annotations`` and ``doctrine/cache`` packages with Composer.
-
-.. tip::
-
- Annotation classes aren't loaded automatically, so you must load them
- using a class loader like this::
-
- use Composer\Autoload\ClassLoader;
- use Doctrine\Common\Annotations\AnnotationRegistry;
-
- /** @var ClassLoader $loader */
- $loader = require __DIR__.'/../vendor/autoload.php';
-
- AnnotationRegistry::registerLoader([$loader, 'loadClass']);
-
- return $loader;
diff --git a/_includes/service_container/_my_mailer.rst.inc b/_includes/service_container/_my_mailer.rst.inc
deleted file mode 100644
index 01eafdfe87a..00000000000
--- a/_includes/service_container/_my_mailer.rst.inc
+++ /dev/null
@@ -1,33 +0,0 @@
-.. configuration-block::
-
- .. code-block:: yaml
-
- # config/services.yaml
- services:
- app.mailer:
- class: App\Mailer
- arguments: [sendmail]
-
- .. code-block:: xml
-
-
-
-
-
-
-
- sendmail
-
-
-
-
- .. code-block:: php
-
- // config/services.php
- use App\Mailer;
-
- $container->register('app.mailer', Mailer::class)
- ->addArgument('sendmail');
diff --git a/best_practices.rst b/best_practices.rst
index a249ea74d4c..6211d042f0b 100644
--- a/best_practices.rst
+++ b/best_practices.rst
@@ -10,7 +10,8 @@ You can even ignore them completely and continue using your own best practices
and methodologies. Symfony is flexible enough to adapt to your needs.
This article assumes that you already have experience developing Symfony
-applications. If you don't, read first the rest of the `Symfony documentation`_.
+applications. If you don't, read first the :doc:`Getting Started `
+section of the documentation.
.. tip::
@@ -29,7 +30,7 @@ to create new Symfony applications:
.. code-block:: terminal
- $ symfony new my_project_name
+ $ symfony new my_project_directory
Under the hood, this Symfony binary command executes the needed `Composer`_
command to :ref:`create a new Symfony application `
@@ -50,8 +51,10 @@ self-explanatory and not coupled to Symfony:
│ └─ console
├─ config/
│ ├─ packages/
+ │ ├─ routes/
│ └─ services.yaml
- └─ public/
+ ├─ migrations/
+ ├─ public/
│ ├─ build/
│ └─ index.php
├─ src/
@@ -62,7 +65,6 @@ self-explanatory and not coupled to Symfony:
│ ├─ Entity/
│ ├─ EventSubscriber/
│ ├─ Form/
- │ ├─ Migrations/
│ ├─ Repository/
│ ├─ Security/
│ └─ Twig/
@@ -80,13 +82,21 @@ Configuration
Use Environment Variables for Infrastructure Configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-These are the options that change from one machine to another (e.g. from your
-development machine to the production server) but which don't change the
+The values of these options change from one machine to another (e.g. from your
+development machine to the production server), but they don't modify the
application behavior.
:ref:`Use env vars in your project ` to define these options
and create multiple ``.env`` files to :ref:`configure env vars per environment `.
+.. _use-secret-for-sensitive-information:
+
+Use Secrets for Sensitive Information
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+When your application has sensitive configuration, like an API key, you should
+store those securely via :doc:`Symfony's secrets management system `.
+
Use Parameters for Application Configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -99,6 +109,10 @@ Define these options as :ref:`parameters ` in the
:ref:`environment ` in the ``config/services_dev.yaml``
and ``config/services_prod.yaml`` files.
+Unless the application configuration is reused multiple times and needs
+rigid validation, do *not* use the :doc:`Config component `
+to define the options.
+
Use Short and Prefixed Parameter Names
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -110,7 +124,7 @@ Then, use just one or two words to describe the purpose of the parameter:
# config/services.yaml
parameters:
- # don't do this: 'dir' is too generic and it doesn't convey any meaning
+ # don't do this: 'dir' is too generic, and it doesn't convey any meaning
app.dir: '...'
# do this: short but easy to understand names
app.contents_dir: '...'
@@ -123,7 +137,7 @@ Use Constants to Define Options that Rarely Change
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Configuration options like the number of items to display in some listing rarely
-change. Instead of defining them as :ref:`service container parameters `,
+change. Instead of defining them as :ref:`configuration parameters `,
define them as PHP constants in the related classes. Example::
// src/Entity/Post.php
@@ -146,6 +160,8 @@ values is that it's complicated to redefine their values in your tests.
Business Logic
--------------
+.. _best-practice-no-application-bundles:
+
Don't Create any Bundle to Organize your Application Logic
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -155,7 +171,7 @@ InvoiceBundle, etc. However, a bundle is meant to be something that can be
reused as a stand-alone piece of software.
If you need to reuse some feature in your projects, create a bundle for it (in a
-private repository, to not make it publicly available). For the rest of your
+private repository, do not make it publicly available). For the rest of your
application code, use PHP namespaces to organize code instead of bundles.
Use Autowiring to Automate the Configuration of Application Services
@@ -163,7 +179,7 @@ Use Autowiring to Automate the Configuration of Application Services
:doc:`Service autowiring ` is a feature that
reads the type-hints on your constructor (or other methods) and automatically
-passes the correct services to each method, making unnecessary to configure
+passes the correct services to each method, making it unnecessary to configure
services explicitly and simplifying the application maintenance.
Use it in combination with :ref:`service autoconfiguration `
@@ -177,25 +193,25 @@ Services Should be Private Whenever Possible
those services via ``$container->get()``. Instead, you will need to use proper
dependency injection.
-Use the YAML Format to Configure your Own Services
+Use the YAML Format to Configure your own Services
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you use the :ref:`default services.yaml configuration `,
most services will be configured automatically. However, in some edge cases
you'll need to configure services (or parts of them) manually.
-YAML is the format recommended to configure services because it's friendly to
+YAML is the format recommended configuring services because it's friendly to
newcomers and concise, but Symfony also supports XML and PHP configuration.
-Use Annotations to Define the Doctrine Entity Mapping
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Use Attributes to Define the Doctrine Entity Mapping
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Doctrine entities are plain PHP objects that you store in some "database".
Doctrine only knows about your entities through the mapping metadata configured
for your model classes.
-Doctrine supports several metadata formats, but it's recommended to use
-annotations because they are by far the most convenient and agile way of setting
+Doctrine supports several metadata formats, but it's recommended to use PHP
+attributes because they are by far the most convenient and agile way of setting
up and looking for mapping information.
Controllers
@@ -215,42 +231,37 @@ nothing more than a few lines of *glue-code*, so you are not coupling the
important parts of your application.
.. _best-practice-controller-annotations:
+.. _best-practice-controller-attributes:
-Use Annotations to Configure Routing, Caching and Security
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Using annotations for routing, caching and security simplifies configuration.
-You don't need to browse several files created with different formats (YAML, XML,
-PHP): all the configuration is just where you need it and it only uses one format.
-
-Don't Use Annotations to Configure the Controller Template
+Use Attributes to Configure Routing, Caching, and Security
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The ``@Template`` annotation is useful, but also involves some *magic*.
-Moreover, most of the time ``@Template`` is used without any parameters, which
-makes it more difficult to know which template is being rendered. It also hides
-the fact that a controller should always return a ``Response`` object.
+Using attributes for routing, caching, and security simplifies
+configuration. You don't need to browse several files created with different
+formats (YAML, XML, PHP): all the configuration is just where you require it,
+and it only uses one format.
Use Dependency Injection to Get Services
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-If you extend the base ``AbstractController``, you can only access to the most
+If you extend the base ``AbstractController``, you can only get access to the most
common services (e.g ``twig``, ``router``, ``doctrine``, etc.), directly from the
-container via ``$this->container->get()`` or ``$this->get()``.
+container via ``$this->container->get()``.
Instead, you must use dependency injection to fetch services by
:ref:`type-hinting action method arguments ` or
constructor arguments.
-Use ParamConverters If They Are Convenient
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Use Entity Value Resolvers If They Are Convenient
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-If you're using :doc:`Doctrine `, then you can *optionally* use the
-`ParamConverter`_ to automatically query for an entity and pass it as an argument
-to your controller. It will also show a 404 page if no entity can be found.
+If you're using :doc:`Doctrine `, then you can *optionally* use
+the :ref:`EntityValueResolver ` to
+automatically query for an entity and pass it as an argument to your
+controller. It will also show a 404 page if no entity can be found.
If the logic to get an entity from a route variable is more complex, instead of
-configuring the ParamConverter, it's better to make the Doctrine query inside
-the controller (e.g. by calling to a :doc:`Doctrine repository method `).
+configuring the EntityValueResolver, it's better to make the Doctrine query
+inside the controller (e.g. by calling to a :doc:`Doctrine repository method `).
Templates
---------
@@ -258,7 +269,7 @@ Templates
Use Snake Case for Template Names and Variables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Use lowercased snake_case for template names, directories and variables (e.g.
+Use lowercase snake_case for template names, directories, and variables (e.g.
``user_profile`` instead of ``userProfile`` and ``product/edit_form.html.twig``
instead of ``Product/EditForm.html.twig``).
@@ -276,9 +287,9 @@ Forms
Define your Forms as PHP Classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Creating :ref:`forms in classes ` allows to reuse
+Creating :ref:`forms in classes ` allows reusing
them in different parts of the application. Besides, not creating forms in
-controllers simplify the code and maintenance of the controllers.
+controllers simplifies the code and maintenance of the controllers.
Add Form Buttons in Templates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -288,10 +299,14 @@ button of a form used to both create and edit items should change from "Add new"
to "Save changes" depending on where it's used.
Instead of adding buttons in form classes or the controllers, it's recommended
-to add buttons in the templates. This also improves the separation of concerns,
+to add buttons in the templates. This also improves the separation of concerns
because the button styling (CSS class and other attributes) is defined in the
template instead of in a PHP class.
+However, if you create a :doc:`form with multiple submit buttons `
+you should define them in the controller instead of the template. Otherwise, you
+won't be able to check which button was clicked when handling the form in the controller.
+
Define Validation Constraints on the Underlying Object
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -306,8 +321,10 @@ Use a Single Action to Render and Process the Form
:ref:`Rendering forms ` and :ref:`processing forms `
are two of the main tasks when handling forms. Both are too similar (most of the
-times, almost identical), so it's much simpler to let a single controller action
-handle everything.
+time, almost identical), so it's much simpler to let a single controller action
+handle both.
+
+.. _best-practice-internationalization:
Internationalization
--------------------
@@ -316,8 +333,8 @@ Use the XLIFF Format for Your Translation Files
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Of all the translation formats supported by Symfony (PHP, Qt, ``.po``, ``.mo``,
-JSON, CSV, INI, etc.) XLIFF and gettext have the best support in the tools used
-by professional translators. And since it's based on XML, you can validate XLIFF
+JSON, CSV, INI, etc.), ``XLIFF`` and ``gettext`` have the best support in the tools used
+by professional translators. And since it's based on XML, you can validate ``XLIFF``
file contents as you write them.
Symfony also supports notes in XLIFF files, making them more user-friendly for
@@ -328,8 +345,8 @@ Use Keys for Translations Instead of Content Strings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using keys simplifies the management of the translation files because you can
-change the original contents in templates, controllers and services without
-having to update all of the translation files.
+change the original contents in templates, controllers, and services without
+having to update all the translation files.
Keys should always describe their *purpose* and *not* their location. For
example, if a form has a field with the label "Username", then a nice key
@@ -345,38 +362,32 @@ Unless you have two legitimately different authentication systems and users
(e.g. form login for the main site and a token system for your API only), it's
recommended to have only one firewall to keep things simple.
-Additionally, you should use the ``anonymous`` key under your firewall. If you
-require users to be logged in for different sections of your site, use the
-:doc:`access_control ` option.
-
Use the ``auto`` Password Hasher
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :ref:`auto password hasher ` automatically
selects the best possible encoder/hasher depending on your PHP installation.
-Currently, it tries to use ``sodium`` by default and falls back to ``bcrypt``.
+Currently, the default auto hasher is ``bcrypt``.
Use Voters to Implement Fine-grained Security Restrictions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If your security logic is complex, you should create custom
:doc:`security voters ` instead of defining long expressions
-inside the ``@Security`` annotation.
+inside the ``#[Security]`` attribute.
Web Assets
----------
-Use Webpack Encore to Process Web Assets
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. _use-webpack-encore-to-process-web-assets:
-Web assets are things like CSS, JavaScript and image files that make the
-frontend of your site look and work great. `Webpack`_ is the leading JavaScript
-module bundler that compiles, transforms and packages assets for usage in a browser.
+Use AssetMapper to Manage Web Assets
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-:doc:`Webpack Encore ` is a JavaScript library that gets rid of most
-of Webpack complexity without hiding any of its features or distorting its usage
-and philosophy. It was originally created for Symfony applications, but it works
-for any application using any technology.
+Web assets are the CSS, JavaScript, and image files that make the frontend of
+your site look and work great. :doc:`AssetMapper ` lets
+you write modern JavaScript and CSS without the complexity of using a bundler
+such as `Webpack`_ (directly or via :doc:`Webpack Encore `).
Tests
-----
@@ -386,8 +397,8 @@ Smoke Test your URLs
In software engineering, `smoke testing`_ consists of *"preliminary testing to
reveal simple failures severe enough to reject a prospective software release"*.
-Using :ref:`PHPUnit data providers ` you can define a
-functional test that checks that all application URLs load successfully::
+Using `PHPUnit data providers`_ you can define a functional test that
+checks that all application URLs load successfully::
// tests/ApplicationAvailabilityFunctionalTest.php
namespace App\Tests;
@@ -399,7 +410,7 @@ functional test that checks that all application URLs load successfully::
/**
* @dataProvider urlProvider
*/
- public function testPageIsSuccessful($url)
+ public function testPageIsSuccessful($url): void
{
$client = self::createClient();
$client->request('GET', $url);
@@ -407,7 +418,7 @@ functional test that checks that all application URLs load successfully::
$this->assertResponseIsSuccessful();
}
- public function urlProvider()
+ public function urlProvider(): \Generator
{
yield ['/'];
yield ['/posts'];
@@ -419,26 +430,27 @@ functional test that checks that all application URLs load successfully::
}
Add this test while creating your application because it requires little effort
-and checks that none of your pages returns an error. Later you'll add more
+and checks that none of your pages returns an error. Later, you'll add more
specific tests for each page.
-Hardcode URLs in a Functional Test
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. _hardcode-urls-in-a-functional-test:
+
+Hard-code URLs in a Functional Test
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-In Symfony applications it's recommended to :ref:`generate URLs `
+In Symfony applications, it's recommended to :ref:`generate URLs `
using routes to automatically update all links when a URL changes. However, if a
public URL changes, users won't be able to browse it unless you set up a
redirection to the new URL.
That's why it's recommended to use raw URLs in tests instead of generating them
-from routes. Whenever a route changes, tests will break and you'll know that
+from routes. Whenever a route changes, tests will fail, and you'll know that
you must set up a redirection.
-.. _`Symfony documentation`: https://symfony.com/doc
.. _`Symfony Demo`: https://github.com/symfony/demo
.. _`download Symfony`: https://symfony.com/download
.. _`Composer`: https://getcomposer.org/
-.. _`ParamConverter`: https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
.. _`feature toggles`: https://en.wikipedia.org/wiki/Feature_toggle
.. _`smoke testing`: https://en.wikipedia.org/wiki/Smoke_testing_(software)
.. _`Webpack`: https://webpack.js.org/
+.. _`PHPUnit data providers`: https://docs.phpunit.de/en/9.6/writing-tests-for-phpunit.html#data-providers
diff --git a/bundles.rst b/bundles.rst
index c3b8b8bbe69..878bee3af4a 100644
--- a/bundles.rst
+++ b/bundles.rst
@@ -1,15 +1,12 @@
-.. index::
- single: Bundles
-
.. _page-creation-bundles:
The Bundle System
=================
-.. caution::
+.. warning::
In Symfony versions prior to 4.0, it was recommended to organize your own
- application code using bundles. This is no longer recommended and bundles
+ application code using bundles. This is :ref:`no longer recommended ` and bundles
should only be used to share code and features between multiple applications.
A bundle is similar to a plugin in other software, but even better. The core
@@ -25,14 +22,15 @@ file::
return [
// 'all' means that the bundle is enabled for any Symfony environment
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
- Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
- Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
- Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
- Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class => ['all' => true],
- Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
- Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
- // this bundle is enabled only in 'dev' and 'test', so you can't use it in 'prod'
+ // ...
+
+ // this bundle is enabled only in 'dev'
+ Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true],
+ // ...
+
+ // this bundle is enabled only in 'dev' and 'test', so you can't use it in 'prod'
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
+ // ...
];
.. tip::
@@ -45,28 +43,32 @@ Creating a Bundle
-----------------
This section creates and enables a new bundle to show there are only a few steps required.
-The new bundle is called AcmeTestBundle, where the ``Acme`` portion is just a
-dummy name that should be replaced by some "vendor" name that represents you or
-your organization (e.g. ABCTestBundle for some company named ``ABC``).
+The new bundle is called AcmeBlogBundle, where the ``Acme`` portion is an example
+name that should be replaced by some "vendor" name that represents you or your
+organization (e.g. AbcBlogBundle for some company named ``Abc``).
-Start by creating a ``src/Acme/TestBundle/`` directory and adding a new file
-called ``AcmeTestBundle.php``::
+Start by creating a new class called ``AcmeBlogBundle``::
- // src/Acme/TestBundle/AcmeTestBundle.php
- namespace App\Acme\TestBundle;
+ // src/AcmeBlogBundle.php
+ namespace Acme\BlogBundle;
- use Symfony\Component\HttpKernel\Bundle\Bundle;
+ use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
- class AcmeTestBundle extends Bundle
+ class AcmeBlogBundle extends AbstractBundle
{
}
+.. warning::
+
+ If your bundle must be compatible with previous Symfony versions you have to
+ extend from the :class:`Symfony\\Component\\HttpKernel\\Bundle\\Bundle` instead.
+
.. tip::
- The name AcmeTestBundle follows the standard
+ The name AcmeBlogBundle follows the standard
:ref:`Bundle naming conventions `. You could
- also choose to shorten the name of the bundle to simply TestBundle by naming
- this class TestBundle (and naming the file ``TestBundle.php``).
+ also choose to shorten the name of the bundle to simply BlogBundle by naming
+ this class BlogBundle (and naming the file ``BlogBundle.php``).
This empty class is the only piece you need to create the new bundle. Though
commonly empty, this class is powerful and can be used to customize the behavior
@@ -75,10 +77,12 @@ of the bundle. Now that you've created the bundle, enable it::
// config/bundles.php
return [
// ...
- App\Acme\TestBundle\AcmeTestBundle::class => ['all' => true],
+ Acme\BlogBundle\AcmeBlogBundle::class => ['all' => true],
];
-And while it doesn't do anything yet, AcmeTestBundle is now ready to be used.
+And while it doesn't do anything yet, AcmeBlogBundle is now ready to be used.
+
+.. _bundles-directory-structure:
Bundle Directory Structure
--------------------------
@@ -87,60 +91,71 @@ The directory structure of a bundle is meant to help to keep code consistent
between all Symfony bundles. It follows a set of conventions, but is flexible
to be adjusted if needed:
-``Controller/``
- Contains the controllers of the bundle (e.g. ``RandomController.php``).
+``assets/``
+ Contains the web asset sources like JavaScript and TypeScript files, CSS and
+ Sass files, but also images and other assets related to the bundle that are
+ not in ``public/`` (e.g. Stimulus controllers).
-``DependencyInjection/``
- Holds certain Dependency Injection Extension classes, which may import service
- configuration, register compiler passes or more (this directory is not
- necessary).
+``config/``
+ Houses configuration, including routing configuration (e.g. ``routes.php``).
-``Resources/config/``
- Houses configuration, including routing configuration (e.g. ``routing.yaml``).
+``public/``
+ Contains web assets (images, compiled CSS and JavaScript files, etc.) and is
+ copied or symbolically linked into the project ``public/`` directory via the
+ ``assets:install`` console command.
-``Resources/views/``
- Holds templates organized by controller name (e.g. ``Random/index.html.twig``).
+``src/``
+ Contains all PHP classes related to the bundle logic (e.g. ``Controller/CategoryController.php``).
-``Resources/public/``
- Contains web assets (images, stylesheets, etc) and is copied or symbolically
- linked into the project ``public/`` directory via the ``assets:install`` console
- command.
+``templates/``
+ Holds templates organized by controller name (e.g. ``category/show.html.twig``).
-``Tests/``
+``tests/``
Holds all tests for the bundle.
-A bundle can be as small or large as the feature it implements. It contains
-only the files you need and nothing else.
+``translations/``
+ Holds translations organized by domain and locale (e.g. ``AcmeBlogBundle.en.xlf``).
-As you move through the guides, you'll learn how to persist objects to a
-database, create and validate forms, create translations for your application,
-write tests and much more. Each of these has their own place and role within
-the bundle.
+.. _bundles-legacy-directory-structure:
-Overridding the Bundle Directory Structure
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. warning::
-Some of the bundle directories are conventions that can be overridden if needed.
-For example, the **public directory**, which by default is located at
-``/Resources/public/``, can be changed by defining the
-``getPublicDir()`` method in the bundle class::
+ The recommended bundle structure was changed in Symfony 5, read the
+ `Symfony 4.4 bundle documentation`_ for information about the old
+ structure.
- // src/Acme/TestBundle/AcmeTestBundle.php
- namespace App\Acme\TestBundle;
+ When using the new ``AbstractBundle`` class, the bundle defaults to the
+ new structure. Override the ``Bundle::getPath()`` method to change to
+ the old structure::
- use Symfony\Component\HttpKernel\Bundle\Bundle;
+ class AcmeBlogBundle extends AbstractBundle
+ {
+ public function getPath(): string
+ {
+ return __DIR__;
+ }
+ }
- class AcmeTestBundle extends Bundle
- {
- // ...
+.. tip::
+
+ It's recommended to use the `PSR-4`_ autoload standard: use the namespace as key,
+ and the location of the bundle's main class (relative to ``composer.json``)
+ as value. As the main class is located in the ``src/`` directory of the bundle:
+
+ .. code-block:: json
- // the returned value must be relative to the bundle root directory
- // (public dir is now /public/ instead of /Resources/public/)
- public function getPublicDir(): string
{
- return 'public/';
+ "autoload": {
+ "psr-4": {
+ "Acme\\BlogBundle\\": "src/"
+ }
+ },
+ "autoload-dev": {
+ "psr-4": {
+ "Acme\\BlogBundle\\Tests\\": "tests/"
+ }
+ }
}
- }
Learn more
----------
@@ -152,3 +167,5 @@ Learn more
* :doc:`/bundles/prepend_extension`
.. _`third-party bundles`: https://github.com/search?q=topic%3Asymfony-bundle&type=Repositories
+.. _`Symfony 4.4 bundle documentation`: https://symfony.com/doc/4.4/bundles.html#bundle-directory-structure
+.. _`PSR-4`: https://www.php-fig.org/psr/psr-4/
diff --git a/bundles/best_practices.rst b/bundles/best_practices.rst
index 2b5fefeeb41..8049ebb9a1c 100644
--- a/bundles/best_practices.rst
+++ b/bundles/best_practices.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Bundle; Best practices
-
Best Practices for Reusable Bundles
===================================
@@ -9,9 +6,6 @@ configurable and extendable. Reusable bundles are those meant to be shared
privately across many company projects or publicly so any Symfony project can
install them.
-.. index::
- pair: Bundle; Naming conventions
-
.. _bundles-naming-conventions:
Bundle Name
@@ -22,8 +16,9 @@ interoperability standard for PHP namespaces and class names: it starts with a
vendor segment, followed by zero or more category segments, and it ends with the
namespace short name, which must end with ``Bundle``.
-A namespace becomes a bundle as soon as you add a bundle class to it. The
-bundle class name must follow these rules:
+A namespace becomes a bundle as soon as you add "a bundle class" to it (which is
+a class that extends :class:`Symfony\\Component\\HttpKernel\\Bundle\\Bundle`).
+The bundle class name must follow these rules:
* Use only alphanumeric characters and underscores;
* Use a StudlyCaps name (i.e. camelCase with an uppercase first letter);
@@ -63,35 +58,54 @@ configuration options (see below for some usage examples).
Directory Structure
-------------------
-The basic directory structure of an AcmeBlogBundle must read as follows:
+The following is the recommended directory structure of an AcmeBlogBundle:
.. code-block:: text
/
- ├─ AcmeBlogBundle.php
- ├─ Controller/
- ├─ README.md
- ├─ LICENSE
- ├─ Resources/
- │ ├─ config/
- │ ├─ doc/
- │ │ └─ index.rst
- │ ├─ translations/
- │ ├─ views/
- │ └─ public/
- └─ Tests/
+ ├── assets/
+ ├── config/
+ ├── docs/
+ │ └─ index.md
+ ├── public/
+ ├── src/
+ │ ├── Controller/
+ │ ├── DependencyInjection/
+ │ └── AcmeBlogBundle.php
+ ├── templates/
+ ├── tests/
+ ├── translations/
+ ├── LICENSE
+ └── README.md
+
+.. note::
+
+ This directory structure is used by default when your bundle class extends
+ the recommended :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle`.
+ If your bundle extends the :class:`Symfony\\Component\\HttpKernel\\Bundle\\Bundle`
+ class, you have to override the ``getPath()`` method as follows::
+
+ use Symfony\Component\HttpKernel\Bundle\Bundle;
+
+ class AcmeBlogBundle extends Bundle
+ {
+ public function getPath(): string
+ {
+ return \dirname(__DIR__);
+ }
+ }
**The following files are mandatory**, because they ensure a structure convention
that automated tools can rely on:
-* ``AcmeBlogBundle.php``: This is the class that transforms a plain directory
+* ``src/AcmeBlogBundle.php``: This is the class that transforms a plain directory
into a Symfony bundle (change this to your bundle's name);
* ``README.md``: This file contains the basic description of the bundle and it
usually shows some basic examples and links to its full documentation (it
can use any of the markup formats supported by GitHub, such as ``README.rst``);
* ``LICENSE``: The full contents of the license used by the code. Most third-party
bundles are published under the MIT license, but you can `choose any license`_;
-* ``Resources/doc/index.rst``: The root file for the Bundle documentation.
+* ``docs/index.md``: The root file for the Bundle documentation.
The depth of subdirectories should be kept to a minimum for the most used
classes and files. Two levels is the maximum.
@@ -107,19 +121,20 @@ and others are just conventions followed by most developers):
=================================================== ========================================
Type Directory
=================================================== ========================================
-Commands ``Command/``
-Controllers ``Controller/``
-Service Container Extensions ``DependencyInjection/``
-Doctrine ORM entities (when not using annotations) ``Entity/``
-Doctrine ODM documents (when not using annotations) ``Document/``
-Event Listeners ``EventListener/``
-Configuration (routes, services, etc.) ``Resources/config/``
-Web Assets (CSS, JS, images) ``Resources/public/``
-Translation files ``Resources/translations/``
-Validation (when not using annotations) ``Resources/config/validation/``
-Serialization (when not using annotations) ``Resources/config/serialization/``
-Templates ``Resources/views/``
-Unit and Functional Tests ``Tests/``
+Commands ``src/Command/``
+Controllers ``src/Controller/``
+Service Container Extensions ``src/DependencyInjection/``
+Doctrine ORM entities ``src/Entity/``
+Doctrine ODM documents ``src/Document/``
+Event Listeners ``src/EventListener/``
+Configuration (routes, services, etc.) ``config/``
+Web Assets (compiled CSS and JS, images) ``public/``
+Web Asset sources (``.scss``, ``.ts``, Stimulus) ``assets/``
+Translation files ``translations/``
+Validation (when not using attributes) ``config/validation/``
+Serialization (when not using attributes) ``config/serialization/``
+Templates ``templates/``
+Unit and Functional Tests ``tests/``
=================================================== ========================================
Classes
@@ -127,7 +142,7 @@ Classes
The bundle directory structure is used as the namespace hierarchy. For
instance, a ``ContentController`` controller which is stored in
-``Acme/BlogBundle/Controller/ContentController.php`` would have the fully
+``src/Controller/ContentController.php`` would have the fully
qualified class name of ``Acme\BlogBundle\Controller\ContentController``.
All classes and files must follow the :doc:`Symfony coding standards `.
@@ -149,11 +164,20 @@ standard Symfony autoloading instead.
A bundle should also not embed third-party libraries written in JavaScript,
CSS or any other language.
+Doctrine Entities/Documents
+---------------------------
+
+If the bundle includes Doctrine ORM entities and/or ODM documents, it's
+recommended to define their mapping using XML files stored in
+``config/doctrine/``. This allows to override that mapping using the
+:doc:`standard Symfony mechanism to override bundle parts `.
+This is not possible when using attributes to define the mapping.
+
Tests
-----
A bundle should come with a test suite written with PHPUnit and stored under
-the ``Tests/`` directory. Tests should follow the following principles:
+the ``tests/`` directory. Tests should follow the following principles:
* The test suite must be executable with a simple ``phpunit`` command run from
a sample application;
@@ -171,75 +195,61 @@ Continuous Integration
Testing bundle code continuously, including all its commits and pull requests,
is a good practice called Continuous Integration. There are several services
-providing this feature for free for open source projects. The most popular
-service for Symfony bundles is called `Travis CI`_.
-
-Here is the recommended configuration file (``.travis.yml``) for Symfony bundles,
-which test the two latest :doc:`LTS versions `
-of Symfony and the latest beta release:
-
-.. code-block:: yaml
-
- language: php
- sudo: false
- cache:
- directories:
- - $HOME/.composer/cache/files
- - $HOME/symfony-bridge/.phpunit
-
- env:
- global:
- - PHPUNIT_FLAGS="-v"
- - SYMFONY_PHPUNIT_DIR="$HOME/symfony-bridge/.phpunit"
-
- matrix:
- fast_finish: true
- include:
- # Minimum supported dependencies with the latest and oldest PHP version
- - php: 7.2
- env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" SYMFONY_DEPRECATIONS_HELPER="max[self]=0"
- - php: 7.1
- env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" SYMFONY_DEPRECATIONS_HELPER="max[self]=0"
-
- # Test the latest stable release
- - php: 7.1
- - php: 7.2
- env: COVERAGE=true PHPUNIT_FLAGS="-v --coverage-text"
-
- # Test LTS versions. This makes sure we do not use Symfony packages with version greater
- # than 2 or 3 respectively. Read more at https://github.com/symfony/lts
- - php: 7.2
- env: DEPENDENCIES="symfony/lts:^2"
- - php: 7.2
- env: DEPENDENCIES="symfony/lts:^3"
-
- # Latest commit to master
- - php: 7.2
- env: STABILITY="dev"
-
- allow_failures:
- # Dev-master is allowed to fail.
- - env: STABILITY="dev"
-
- before_install:
- - if [[ $COVERAGE != true ]]; then phpenv config-rm xdebug.ini || true; fi
- - if ! [ -z "$STABILITY" ]; then composer config minimum-stability ${STABILITY}; fi;
- - if ! [ -v "$DEPENDENCIES" ]; then composer require --no-update ${DEPENDENCIES}; fi;
-
- install:
- # To be removed when this issue will be resolved: https://github.com/composer/composer/issues/5355
- - if [[ "$COMPOSER_FLAGS" == *"--prefer-lowest"* ]]; then composer update --prefer-dist --no-interaction --prefer-stable --quiet; fi
- - composer update ${COMPOSER_FLAGS} --prefer-dist --no-interaction
- - ./vendor/bin/simple-phpunit install
-
- script:
- - composer validate --strict --no-check-lock
- # simple-phpunit is the PHPUnit wrapper provided by the PHPUnit Bridge component and
- # it helps with testing legacy code and deprecations (composer require symfony/phpunit-bridge)
- - ./vendor/bin/simple-phpunit $PHPUNIT_FLAGS
-
-Consider using the `Travis cron`_ tool to make sure your project is built even if
-there are no new pull requests or commits.
+providing this feature for free for open source projects, like `GitHub Actions`_.
+
+A bundle should at least test:
+
+* The lower bound of their dependencies (by running ``composer update --prefer-lowest``);
+* The supported PHP versions;
+* All supported major Symfony versions (e.g. both ``6.4`` and ``7.x`` if
+ support is claimed for both).
+
+Thus, a bundle supporting PHP 7.4, 8.3 and 8.4, and Symfony 6.4 and 7.x should
+have at least this test matrix:
+
+=========== =============== ===================
+PHP version Symfony version Composer flags
+=========== =============== ===================
+7.4 ``6.4`` ``--prefer-lowest``
+8.3 ``7.*``
+8.4 ``7.*``
+=========== =============== ===================
+
+.. tip::
+
+ The tests should be run with the ``SYMFONY_DEPRECATIONS_HELPER``
+ env variable set to ``max[direct]=0``. This ensures no code in the
+ bundle uses deprecated features directly.
+
+ The lowest dependency tests can be run with this variable set to
+ ``disabled=1``.
+
+Require a Specific Symfony Version
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You can use the special ``SYMFONY_REQUIRE`` environment variable together
+with Symfony Flex to install a specific Symfony version:
+
+.. code-block:: bash
+
+ # this requires Symfony 7.x for all Symfony packages
+ export SYMFONY_REQUIRE=7.*
+ # alternatively you can run this command to update composer.json config
+ # composer config extra.symfony.require "7.*"
+
+ # install Symfony Flex in the CI environment
+ composer global config --no-plugins allow-plugins.symfony/flex true
+ composer global require --no-progress --no-scripts --no-plugins symfony/flex
+
+ # install the dependencies (using --prefer-dist and --no-progress is
+ # recommended to have a better output and faster download time)
+ composer update --prefer-dist --no-progress
+
+.. warning::
+
+ If you want to cache your Composer dependencies, **do not** cache the
+ ``vendor/`` directory as this has side-effects. Instead cache
+ ``$HOME/.composer/cache/files``.
Installation
------------
@@ -256,13 +266,13 @@ Documentation
All classes and functions must come with full PHPDoc.
-Extensive documentation should also be provided in the ``Resources/doc/``
+Extensive documentation should also be provided in the ``docs/``
directory.
-The index file (for example ``Resources/doc/index.rst`` or
-``Resources/doc/index.md``) is the only mandatory file and must be the entry
+The index file (for example ``docs/index.rst`` or
+``docs/index.md``) is the only mandatory file and must be the entry
point for the documentation. The
:doc:`reStructuredText (rST) ` is the format
-used to render the documentation on symfony.com.
+used to render the documentation on the Symfony website.
Installation Instructions
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -287,7 +297,7 @@ following standardized instructions in your ``README.md`` file.
Open a command console, enter your project directory and execute:
```console
- $ composer require
+ composer require
```
Applications that don't use Symfony Flex
@@ -299,7 +309,7 @@ following standardized instructions in your ``README.md`` file.
following command to download the latest stable version of this bundle:
```console
- $ composer require
+ composer require
```
### Step 2: Enable the Bundle
@@ -328,9 +338,9 @@ following standardized instructions in your ``README.md`` file.
Open a command console, enter your project directory and execute:
- .. code-block:: bash
+ .. code-block:: terminal
- $ composer require
+ composer require
Applications that don't use Symfony Flex
----------------------------------------
@@ -343,7 +353,7 @@ following standardized instructions in your ``README.md`` file.
.. code-block:: terminal
- $ composer require
+ composer require
Step 2: Enable the Bundle
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -386,10 +396,14 @@ Translation Files
-----------------
If a bundle provides message translations, they must be defined in the XLIFF
-format; the domain should be named after the bundle name (``acme_blog``).
+format; the domain should be named after the bundle name (``AcmeBlog``).
A bundle must not override existing messages from another bundle.
+The translation domain must match the translation file names. For example,
+if the translation domain is ``AcmeBlog``, the English translation file name
+should be ``AcmeBlog.en.xlf``.
+
Configuration
-------------
@@ -420,8 +434,8 @@ The end user can provide values in any configuration file:
-
+ https://symfony.com/schema/dic/services/services-1.0.xsd"
+ >
fabien@example.com
@@ -431,7 +445,13 @@ The end user can provide values in any configuration file:
.. code-block:: php
// config/services.php
- $container->setParameter('acme_blog.author.email', 'fabien@example.com');
+ namespace Symfony\Component\DependencyInjection\Loader\Configurator;
+
+ return static function (ContainerConfigurator $container): void {
+ $container->parameters()
+ ->set('acme_blog.author.email', 'fabien@example.com')
+ ;
+ };
Retrieve the configuration parameters in your code from the container::
@@ -465,6 +485,13 @@ can be used for autowiring.
Services should not use autowiring or autoconfiguration. Instead, all services should
be defined explicitly.
+.. tip::
+
+ If there is no intention for the service id to be used by the end user, you can
+ mark it as *hidden* by prefixing it with a dot (e.g. ``.acme_blog.logger``).
+ This prevents the service from being listed in the default ``debug:container``
+ command output.
+
.. seealso::
You can learn much more about service loading in bundles reading this article:
@@ -479,7 +506,7 @@ The ``composer.json`` file should include at least the following metadata:
Consists of the vendor and the short bundle name. If you are releasing the
bundle on your own instead of on behalf of a company, use your personal name
(e.g. ``johnsmith/blog-bundle``). Exclude the vendor name from the bundle
- short name and separate each word with an hyphen. For example: AcmeBlogBundle
+ short name and separate each word with a hyphen. For example: AcmeBlogBundle
is transformed into ``blog-bundle`` and AcmeSocialConnectBundle is
transformed into ``social-connect-bundle``.
@@ -496,10 +523,22 @@ The ``composer.json`` file should include at least the following metadata:
This information is used by Symfony to load the classes of the bundle. It's
recommended to use the `PSR-4`_ autoload standard: use the namespace as key,
and the location of the bundle's main class (relative to ``composer.json``)
- as value. For example, if the main class is located in the bundle root
- directory: ``"autoload": { "psr-4": { "SomeVendor\\BlogBundle\\": "" } }``.
- If the main class is located in the ``src/`` directory of the bundle:
- ``"autoload": { "psr-4": { "SomeVendor\\BlogBundle\\": "src/" } }``.
+ as value. As the main class is located in the ``src/`` directory of the bundle:
+
+ .. code-block:: json
+
+ {
+ "autoload": {
+ "psr-4": {
+ "Acme\\BlogBundle\\": "src/"
+ }
+ },
+ "autoload-dev": {
+ "psr-4": {
+ "Acme\\BlogBundle\\Tests\\": "tests/"
+ }
+ }
+ }
In order to make it easier for developers to find your bundle, register it on
`Packagist`_, the official repository for Composer packages.
@@ -508,22 +547,19 @@ Resources
---------
If the bundle references any resources (config files, translation files, etc.),
-don't use physical paths (e.g. ``__DIR__/config/services.xml``) but logical
-paths (e.g. ``@FooBundle/Resources/config/services.xml``).
-
-The logical paths are required because of the bundle overriding mechanism that
-lets you override any resource/file of any bundle. See :ref:`http-kernel-resource-locator`
-for more details about transforming physical paths into logical paths.
+you can use physical paths (e.g. ``__DIR__/config/services.xml``).
-Beware that templates use a simplified version of the logical path shown above.
-For example, an ``index.html.twig`` template located in the ``Resources/views/Default/``
-directory of the FooBundle, is referenced as ``@Foo/Default/index.html.twig``.
+In the past, we recommended to only use logical paths (e.g.
+``@AcmeBlogBundle/config/services.xml``) and resolve them with the
+:ref:`resource locator ` provided by the Symfony
+kernel, but this is no longer a recommended practice.
Learn more
----------
* :doc:`/bundles/extension`
* :doc:`/bundles/configuration`
+* :doc:`/frontend/create_ux_bundle`
.. _`PSR-4`: https://www.php-fig.org/psr/psr-4/
.. _`Symfony Flex recipe`: https://github.com/symfony/recipes
@@ -531,5 +567,4 @@ Learn more
.. _`Packagist`: https://packagist.org/
.. _`choose any license`: https://choosealicense.com/
.. _`valid license identifier`: https://spdx.org/licenses/
-.. _`Travis CI`: https://travis-ci.org/
-.. _`Travis cron`: https://docs.travis-ci.com/user/cron-jobs/
+.. _`GitHub Actions`: https://docs.github.com/en/free-pro-team@latest/actions
diff --git a/bundles/configuration.rst b/bundles/configuration.rst
index 9da8c884370..dedfada2ea2 100644
--- a/bundles/configuration.rst
+++ b/bundles/configuration.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Configuration; Semantic
- single: Bundle; Extension configuration
-
How to Create Friendly Configuration for a Bundle
=================================================
@@ -20,19 +16,22 @@ as integration of other related components:
.. code-block:: yaml
+ # config/packages/framework.yaml
framework:
form: true
.. code-block:: xml
+
-
+ https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"
+ >
@@ -40,15 +39,117 @@ as integration of other related components:
.. code-block:: php
- $container->loadFromExtension('framework', [
- 'form' => true,
- ]);
+ // config/packages/framework.php
+ use Symfony\Config\FrameworkConfig;
+
+ return static function (FrameworkConfig $framework): void {
+ $framework->form()->enabled(true);
+ };
+
+There are two different ways of creating friendly configuration for a bundle:
+
+#. :ref:`Using the main bundle class `:
+ this is recommended for new bundles and for bundles following the
+ :ref:`recommended directory structure `;
+#. :ref:`Using the Bundle extension class `:
+ this was the traditional way of doing it, but nowadays it's only recommended for
+ bundles following the :ref:`legacy directory structure `.
+
+.. _using-the-bundle-class:
+.. _bundle-friendly-config-bundle-class:
+
+Using the AbstractBundle Class
+------------------------------
+
+In bundles extending the :class:`Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle`
+class, you can add all the logic related to processing the configuration in that class::
+
+ // src/AcmeSocialBundle.php
+ namespace Acme\SocialBundle;
+
+ use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
+ use Symfony\Component\DependencyInjection\ContainerBuilder;
+ use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
+ use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
+
+ class AcmeSocialBundle extends AbstractBundle
+ {
+ public function configure(DefinitionConfigurator $definition): void
+ {
+ $definition->rootNode()
+ ->children()
+ ->arrayNode('twitter')
+ ->children()
+ ->integerNode('client_id')->end()
+ ->scalarNode('client_secret')->end()
+ ->end()
+ ->end() // twitter
+ ->end()
+ ;
+ }
+
+ public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
+ {
+ // the "$config" variable is already merged and processed so you can
+ // use it directly to configure the service container (when defining an
+ // extension class, you also have to do this merging and processing)
+ $container->services()
+ ->get('acme_social.twitter_client')
+ ->arg(0, $config['twitter']['client_id'])
+ ->arg(1, $config['twitter']['client_secret'])
+ ;
+ }
+ }
+
+.. note::
+
+ The ``configure()`` and ``loadExtension()`` methods are called only at compile time.
+
+.. tip::
+
+ The ``AbstractBundle::configure()`` method also allows to import the
+ configuration definition from one or more files::
+
+ // src/AcmeSocialBundle.php
+ namespace Acme\SocialBundle;
+
+ // ...
+ class AcmeSocialBundle extends AbstractBundle
+ {
+ public function configure(DefinitionConfigurator $definition): void
+ {
+ $definition->import('../config/definition.php');
+ // you can also use glob patterns
+ //$definition->import('../config/definition/*.php');
+ }
+
+ // ...
+ }
+
+ .. code-block:: php
+
+ // config/definition.php
+ use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
+
+ return static function (DefinitionConfigurator $definition): void {
+ $definition->rootNode()
+ ->children()
+ ->scalarNode('foo')->defaultValue('bar')->end()
+ ->end()
+ ;
+ };
+
+.. _bundle-friendly-config-extension:
Using the Bundle Extension
--------------------------
+This is the traditional way of creating friendly configuration for bundles. For new
+bundles it's recommended to :ref:`use the main bundle class `,
+but the traditional way of creating an extension class still works.
+
Imagine you are creating a new bundle - AcmeSocialBundle - which provides
-integration with Twitter. To make your bundle configurable to the user, you
+integration with X/Twitter. To make your bundle configurable to the user, you
can add some configuration that looks like this:
.. configuration-block::
@@ -64,29 +165,30 @@ can add some configuration that looks like this:
.. code-block:: xml
-
+
-
+ https://symfony.com/schema/dic/services/services-1.0.xsd"
+ >
-
+
-
-
.. code-block:: php
// config/packages/acme_social.php
- $container->loadFromExtension('acme_social', [
- 'twitter' => [
- 'client_id' => 123,
- 'client_secret' => 'your_secret',
- ],
- ]);
+ use Symfony\Config\AcmeSocialConfig;
+
+ return static function (AcmeSocialConfig $acmeSocial): void {
+ $acmeSocial->twitter()
+ ->clientId(123)
+ ->clientSecret('your_secret');
+ };
The basic idea is that instead of having the user override individual
parameters, you let the user configure just a few, specifically created,
@@ -97,7 +199,7 @@ load correct services and parameters inside an "Extension" class.
The root key of your bundle configuration (``acme_social`` in the previous
example) is automatically determined from your bundle name (it's the
- `snake case`_ of the bundle name without the ``Bundle`` suffix ).
+ `snake case`_ of the bundle name without the ``Bundle`` suffix).
.. seealso::
@@ -107,7 +209,7 @@ load correct services and parameters inside an "Extension" class.
If a bundle provides an Extension class, then you should *not* generally
override any service container parameters from that bundle. The idea
- is that if an Extension class is present, every setting that should be
+ is that if an extension class is present, every setting that should be
configurable should be present in the configuration made available by
that class. In other words, the extension class defines all the public
configuration settings for which backward compatibility will be maintained.
@@ -172,7 +274,7 @@ of your bundle's configuration.
The ``Configuration`` class to handle the sample configuration looks like::
- // src/Acme/SocialBundle/DependencyInjection/Configuration.php
+ // src/DependencyInjection/Configuration.php
namespace Acme\SocialBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
@@ -180,7 +282,7 @@ The ``Configuration`` class to handle the sample configuration looks like::
class Configuration implements ConfigurationInterface
{
- public function getConfigTreeBuilder()
+ public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('acme_social');
@@ -213,8 +315,8 @@ This class can now be used in your ``load()`` method to merge configurations and
force validation (e.g. if an additional option was passed, an exception will be
thrown)::
- // src/Acme/SocialBundle/DependencyInjection/AcmeSocialExtension.php
- public function load(array $configs, ContainerBuilder $container)
+ // src/DependencyInjection/AcmeSocialExtension.php
+ public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
@@ -233,15 +335,15 @@ For example, imagine your bundle has the following example config:
.. code-block:: xml
-
+
-
+ https://symfony.com/schema/dic/services/services-1.0.xsd"
+ >
-
@@ -155,23 +162,26 @@ will create pool with service id of ``cache.[type]``
.. code-block:: php
// config/packages/cache.php
- $container->loadFromExtension('framework', [
- 'cache' => [
+ use Symfony\Config\FrameworkConfig;
+
+ return static function (FrameworkConfig $framework): void {
+ $framework->cache()
// Only used with cache.adapter.filesystem
- 'directory' => '%kernel.cache_dir%/pools',
-
- // Service: cache.doctrine
- 'default_doctrine_provider' => 'app.doctrine_cache',
- // Service: cache.psr6
- 'default_psr6_provider' => 'app.my_psr6_service',
- // Service: cache.redis
- 'default_redis_provider' => 'redis://localhost',
- // Service: cache.memcached
- 'default_memcached_provider' => 'memcached://localhost',
- // Service: cache.pdo
- 'default_pdo_provider' => 'doctrine.dbal.default_connection',
- ],
- ]);
+ ->directory('%kernel.cache_dir%/pools')
+
+ ->defaultDoctrineDbalProvider('doctrine.dbal.default_connection')
+ ->defaultPsr6Provider('app.my_psr6_service')
+ ->defaultRedisProvider('redis://localhost')
+ ->defaultMemcachedProvider('memcached://localhost')
+ ->defaultPdoProvider('pgsql:host=localhost')
+ ;
+ };
+
+.. versionadded:: 7.1
+
+ Using a DSN as the provider for the PDO adapter was introduced in Symfony 7.1.
+
+.. _cache-create-pools:
Creating Custom (Namespaced) Pools
----------------------------------
@@ -197,7 +207,7 @@ You can also create more customized pools:
# creates a "my_cache_pool" service
# autowireable via "CacheInterface $myCachePool"
my_cache_pool:
- adapter: cache.adapter.array
+ adapter: cache.adapter.filesystem
# uses the default_memcached_provider from above
acme.cache:
@@ -222,14 +232,31 @@ You can also create more customized pools:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services
- https://symfony.com/schema/dic/services/services-1.0.xsd">
-
+ 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"
+ >
-
+
+
-
+
+
+
+
+
-
+
+
+
+
+
@@ -238,38 +265,44 @@ You can also create more customized pools:
.. code-block:: php
// config/packages/cache.php
- $container->loadFromExtension('framework', [
- 'cache' => [
- 'default_memcached_provider' => 'memcached://localhost',
- 'pools' => [
- 'custom_thing.cache' => [
- 'adapter' => 'cache.app',
- ],
- 'my_cache_pool' => [
- 'adapter' => 'cache.adapter.array',
- ],
- 'acme.cache' => [
- 'adapter' => 'cache.adapter.memcached',
- ],
- 'foobar.cache' => [
- 'adapter' => 'cache.adapter.memcached',
- 'provider' => 'memcached://user:password@example.com',
- ],
- 'short_cache' => [
- 'adapter' => 'foobar.cache',
- 'default_lifetime' => 60,
- ],
- ],
- ],
- ]);
-
-Each pool manages a set of independent cache keys: keys of different pools
+ use Symfony\Config\FrameworkConfig;
+
+ return static function (FrameworkConfig $framework): void {
+ $cache = $framework->cache();
+ $cache->defaultMemcachedProvider('memcached://localhost');
+
+ // creates a "custom_thing.cache" service
+ // autowireable via "CacheInterface $customThingCache"
+ // uses the "app" cache configuration
+ $cache->pool('custom_thing.cache')
+ ->adapters(['cache.app']);
+
+ // creates a "my_cache_pool" service
+ // autowireable via "CacheInterface $myCachePool"
+ $cache->pool('my_cache_pool')
+ ->adapters(['cache.adapter.filesystem']);
+
+ // uses the default_memcached_provider from above
+ $cache->pool('acme.cache')
+ ->adapters(['cache.adapter.memcached']);
+
+ // control adapter's configuration
+ $cache->pool('foobar.cache')
+ ->adapters(['cache.adapter.memcached'])
+ ->provider('memcached://user:password@example.com');
+
+ $cache->pool('short_cache')
+ ->adapters(['foobar.cache'])
+ ->defaultLifetime(60);
+ };
+
+Each pool manages a set of independent cache keys: keys from different pools
*never* collide, even if they share the same backend. This is achieved by prefixing
keys with a namespace that's generated by hashing the name of the pool, the name
-of the compiled container class and a :ref:`configurable seed`
-that defaults to the project directory.
+of the cache adapter class and a :ref:`configurable seed `
+that defaults to the project directory and compiled container class.
-Each custom pool becomes a service where the service id is the name of the pool
+Each custom pool becomes a service whose service ID is the name of the pool
(e.g. ``custom_thing.cache``). An autowiring alias is also created for each pool
using the camel case version of its name - e.g. ``custom_thing.cache`` can be
injected automatically by naming the argument ``$customThingCache`` and type-hinting it
@@ -277,25 +310,79 @@ with either :class:`Symfony\\Contracts\\Cache\\CacheInterface` or
``Psr\Cache\CacheItemPoolInterface``::
use Symfony\Contracts\Cache\CacheInterface;
+ // ...
// from a controller method
- public function listProducts(CacheInterface $customThingCache)
+ public function listProducts(CacheInterface $customThingCache): Response
{
// ...
}
// in a service
- public function __construct(CacheInterface $customThingCache)
+ public function __construct(private CacheInterface $customThingCache)
{
// ...
}
+.. tip::
+
+ If you need the namespace to be interoperable with a third-party app,
+ you can take control over auto-generation by setting the ``namespace``
+ attribute of the ``cache.pool`` service tag. For example, you can
+ override the service definition of the adapter:
+
+ .. configuration-block::
+
+ .. code-block:: yaml
+
+ # config/services.yaml
+ services:
+ # ...
+
+ app.cache.adapter.redis:
+ parent: 'cache.adapter.redis'
+ tags:
+ - { name: 'cache.pool', namespace: 'my_custom_namespace' }
+
+ .. code-block:: xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+ .. code-block:: php
+
+ // config/services.php
+ namespace Symfony\Component\DependencyInjection\Loader\Configurator;
+
+ return function(ContainerConfigurator $container): void {
+ $container->services()
+ // ...
+
+ ->set('app.cache.adapter.redis')
+ ->parent('cache.adapter.redis')
+ ->tag('cache.pool', ['namespace' => 'my_custom_namespace'])
+ ;
+ };
+
Custom Provider Options
-----------------------
Some providers have specific options that can be configured. The
:doc:`RedisAdapter ` allows you to
-create providers with option ``timeout``, ``retry_interval``. etc. To use these
+create providers with the options ``timeout``, ``retry_interval``. etc. To use these
options with non-default values you need to create your own ``\Redis`` provider
and use that when configuring the pool.
@@ -327,16 +414,22 @@ and use that when configuring the pool.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services
- https://symfony.com/schema/dic/services/services-1.0.xsd">
-
+ 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"
+ >
-
+
+
redis://localhost
2
@@ -349,32 +442,46 @@ and use that when configuring the pool.
.. code-block:: php
// config/packages/cache.php
- $container->loadFromExtension('framework', [
- 'cache' => [
- 'pools' => [
- 'cache.my_redis' => [
- 'adapter' => 'cache.adapter.redis',
- 'provider' => 'app.my_custom_redis_provider',
- ],
- ],
- ],
- ]);
-
- $container->getDefinition('app.my_custom_redis_provider', \Redis::class)
- ->addArgument('redis://localhost')
- ->addArgument([
- 'retry_interval' => 2,
- 'timeout' => 10
- ]);
+ namespace Symfony\Component\DependencyInjection\Loader\Configurator;
+
+ use Symfony\Component\Cache\Adapter\RedisAdapter;
+ use Symfony\Component\DependencyInjection\ContainerBuilder;
+ use Symfony\Config\FrameworkConfig;
+
+ return static function (ContainerBuilder $container, FrameworkConfig $framework): void {
+ $framework->cache()
+ ->pool('cache.my_redis')
+ ->adapters(['cache.adapter.redis'])
+ ->provider('app.my_custom_redis_provider');
+
+ $container->register('app.my_custom_redis_provider', \Redis::class)
+ ->setFactory([RedisAdapter::class, 'createConnection'])
+ ->addArgument('redis://localhost')
+ ->addArgument([
+ 'retry_interval' => 2,
+ 'timeout' => 10
+ ])
+ ;
+ };
Creating a Cache Chain
----------------------
-Different cache adapters have different strengths and weaknesses. Some might be really
-quick but small and some may be able to contain a lot of data but are quite slow.
-To get the best of both worlds you may use a chain of adapters. The idea is to
-first look at the quick adapter and then move on to slower adapters. In the worst
-case the value needs to be recalculated.
+Different cache adapters have different strengths and weaknesses. Some might be
+really quick but optimized to store small items and some may be able to contain
+a lot of data but are quite slow. To get the best of both worlds you may use a
+chain of adapters.
+
+A cache chain combines several cache pools into a single one. When storing an
+item in a cache chain, Symfony stores it in all pools sequentially. When
+retrieving an item, Symfony tries to get it from the first pool. If it's not
+found, it tries the next pools until the item is found or an exception is thrown.
+Because of this behavior, it's recommended to define the adapters in the chain
+in order from fastest to slowest.
+
+If an error happens when storing an item in a pool, Symfony stores it in the
+other pools and no exception is thrown. Later, when the item is retrieved,
+Symfony stores the item automatically in all the missing pools.
.. configuration-block::
@@ -399,11 +506,14 @@ case the value needs to be recalculated.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services
- https://symfony.com/schema/dic/services/services-1.0.xsd">
-
+ 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"
+ >
-
+
@@ -415,51 +525,50 @@ case the value needs to be recalculated.
.. code-block:: php
// config/packages/cache.php
- $container->loadFromExtension('framework', [
- 'cache' => [
- 'pools' => [
- 'my_cache_pool' => [
- 'default_lifetime' => 31536000, // One year
- 'adapters' => [
- 'cache.adapter.array',
- 'cache.adapter.apcu',
- ['name' => 'cache.adapter.redis', 'provider' => 'redis://user:password@example.com'],
- ],
- ],
- ],
- ],
- ]);
+ use Symfony\Config\FrameworkConfig;
+
+ return static function (FrameworkConfig $framework): void {
+ $framework->cache()
+ ->pool('my_cache_pool')
+ ->defaultLifetime(31536000) // One year
+ ->adapters([
+ 'cache.adapter.array',
+ 'cache.adapter.apcu',
+ ['name' => 'cache.adapter.redis', 'provider' => 'redis://user:password@example.com'],
+ ])
+ ;
+ };
+
+.. _cache-using-cache-tags:
Using Cache Tags
----------------
In applications with many cache keys it could be useful to organize the data stored
-to be able to invalidate the cache more efficient. One way to achieve that is to
+to be able to invalidate the cache more efficiently. One way to achieve that is to
use cache tags. One or more tags could be added to the cache item. All items with
-the same key could be invalidate with one function call::
+the same tag could be invalidated with one function call::
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
class SomeClass
{
- private $myCachePool;
-
// using autowiring to inject the cache pool
- public function __construct(TagAwareCacheInterface $myCachePool)
- {
- $this->myCachePool = $myCachePool;
+ public function __construct(
+ private TagAwareCacheInterface $myCachePool,
+ ) {
}
- public function someMethod()
+ public function someMethod(): void
{
- $value0 = $this->myCachePool->get('item_0', function (ItemInterface $item) {
+ $value0 = $this->myCachePool->get('item_0', function (ItemInterface $item): string {
$item->tag(['foo', 'bar']);
return 'debug';
});
- $value1 = $this->myCachePool->get('item_1', function (ItemInterface $item) {
+ $value1 = $this->myCachePool->get('item_1', function (ItemInterface $item): string {
$item->tag('foo');
return 'debug';
@@ -470,7 +579,7 @@ the same key could be invalidate with one function call::
}
}
-The cache adapter needs to implement :class:`Symfony\\Contracts\\Cache\\TagAwareCacheInterface``
+The cache adapter needs to implement :class:`Symfony\\Contracts\\Cache\\TagAwareCacheInterface`
to enable this feature. This could be added by using the following configuration.
.. configuration-block::
@@ -482,7 +591,7 @@ to enable this feature. This could be added by using the following configuration
cache:
pools:
my_cache_pool:
- adapter: cache.adapter.redis
+ adapter: cache.adapter.redis_tag_aware
tags: true
.. code-block:: xml
@@ -493,11 +602,16 @@ to enable this feature. This could be added by using the following configuration
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services
- https://symfony.com/schema/dic/services/services-1.0.xsd">
-
+ 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"
+ >
-
+
@@ -505,16 +619,15 @@ to enable this feature. This could be added by using the following configuration
.. code-block:: php
// config/packages/cache.php
- $container->loadFromExtension('framework', [
- 'cache' => [
- 'pools' => [
- 'my_cache_pool' => [
- 'adapter' => 'cache.adapter.redis',
- 'tags' => true,
- ],
- ],
- ],
- ]);
+ use Symfony\Config\FrameworkConfig;
+
+ return static function (FrameworkConfig $framework): void {
+ $framework->cache()
+ ->pool('my_cache_pool')
+ ->tags(true)
+ ->adapters(['cache.adapter.redis_tag_aware'])
+ ;
+ };
Tags are stored in the same pool by default. This is good in most scenarios. But
sometimes it might be better to store the tags in a different pool. That could be
@@ -542,12 +655,17 @@ achieved by specifying the adapter.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services
- https://symfony.com/schema/dic/services/services-1.0.xsd">
-
+ 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"
+ >
-
-
+
+
@@ -555,19 +673,20 @@ achieved by specifying the adapter.
.. code-block:: php
// config/packages/cache.php
- $container->loadFromExtension('framework', [
- 'cache' => [
- 'pools' => [
- 'my_cache_pool' => [
- 'adapter' => 'cache.adapter.redis',
- 'tags' => 'tag_pool',
- ],
- 'tag_pool' => [
- 'adapter' => 'cache.adapter.apcu',
- ],
- ],
- ],
- ]);
+ use Symfony\Config\FrameworkConfig;
+
+ return static function (FrameworkConfig $framework): void {
+ $framework->cache()
+ ->pool('my_cache_pool')
+ ->tags('tag_pool')
+ ->adapters(['cache.adapter.redis'])
+ ;
+
+ $framework->cache()
+ ->pool('tag_pool')
+ ->adapters(['cache.adapter.apcu'])
+ ;
+ };
.. note::
@@ -579,14 +698,14 @@ Clearing the Cache
To clear the cache you can use the ``bin/console cache:pool:clear [pool]`` command.
That will remove all the entries from your storage and you will have to recalculate
-all values. You can also group your pools into "cache clearers". There are 3 cache
+all the values. You can also group your pools into "cache clearers". There are 3 cache
clearers by default:
* ``cache.global_clearer``
* ``cache.system_clearer``
* ``cache.app_clearer``
-The global clearer clears all the cache in every pool. The system cache clearer
+The global clearer clears all the cache items in every pool. The system cache clearer
is used in the ``bin/console cache:clear`` command. The app clearer is the default
clearer.
@@ -608,8 +727,256 @@ Clear all custom pools:
$ php bin/console cache:pool:clear cache.app_clearer
+Clear all cache pools:
+
+.. code-block:: terminal
+
+ $ php bin/console cache:pool:clear --all
+
+Clear all cache pools except some:
+
+.. code-block:: terminal
+
+ $ php bin/console cache:pool:clear --all --exclude=my_cache_pool --exclude=another_cache_pool
+
Clear all caches everywhere:
.. code-block:: terminal
$ php bin/console cache:pool:clear cache.global_clearer
+
+Clear cache by tag(s):
+
+.. code-block:: terminal
+
+ # invalidate tag1 from all taggable pools
+ $ php bin/console cache:pool:invalidate-tags tag1
+
+ # invalidate tag1 & tag2 from all taggable pools
+ $ php bin/console cache:pool:invalidate-tags tag1 tag2
+
+ # invalidate tag1 & tag2 from cache.app pool
+ $ php bin/console cache:pool:invalidate-tags tag1 tag2 --pool=cache.app
+
+ # invalidate tag1 & tag2 from cache1 & cache2 pools
+ $ php bin/console cache:pool:invalidate-tags tag1 tag2 -p cache1 -p cache2
+
+Encrypting the Cache
+--------------------
+
+To encrypt the cache using ``libsodium``, you can use the
+:class:`Symfony\\Component\\Cache\\Marshaller\\SodiumMarshaller`.
+
+First, you need to generate a secure key and add it to your :doc:`secret
+store ` as ``CACHE_DECRYPTION_KEY``:
+
+.. code-block:: terminal
+
+ $ php -r 'echo base64_encode(sodium_crypto_box_keypair());'
+
+Then, register the ``SodiumMarshaller`` service using this key:
+
+.. configuration-block::
+
+ .. code-block:: yaml
+
+ # config/packages/cache.yaml
+
+ # ...
+ services:
+ Symfony\Component\Cache\Marshaller\SodiumMarshaller:
+ decorates: cache.default_marshaller
+ arguments:
+ - ['%env(base64:CACHE_DECRYPTION_KEY)%']
+ # use multiple keys in order to rotate them
+ #- ['%env(base64:CACHE_DECRYPTION_KEY)%', '%env(base64:OLD_CACHE_DECRYPTION_KEY)%']
+ - '@.inner'
+
+ .. code-block:: xml
+
+
+
+
+
+
+
+
+
+
+ env(base64:CACHE_DECRYPTION_KEY)
+
+
+
+
+
+
+
+
+ .. code-block:: php
+
+ // config/packages/cache.php
+ use Symfony\Component\Cache\Marshaller\SodiumMarshaller;
+ use Symfony\Component\DependencyInjection\ChildDefinition;
+ use Symfony\Component\DependencyInjection\Reference;
+
+ // ...
+ $container->setDefinition(SodiumMarshaller::class, new ChildDefinition('cache.default_marshaller'))
+ ->addArgument(['env(base64:CACHE_DECRYPTION_KEY)'])
+ // use multiple keys in order to rotate them
+ //->addArgument(['env(base64:CACHE_DECRYPTION_KEY)', 'env(base64:OLD_CACHE_DECRYPTION_KEY)'])
+ ->addArgument(new Reference('.inner'));
+
+.. danger::
+
+ This will encrypt the values of the cache items, but not the cache keys. Be
+ careful not to leak sensitive data in the keys.
+
+When configuring multiple keys, the first key will be used for reading and
+writing, and the additional key(s) will only be used for reading. Once all
+cache items encrypted with the old key have expired, you can completely remove
+``OLD_CACHE_DECRYPTION_KEY``.
+
+Computing Cache Values Asynchronously
+-------------------------------------
+
+The Cache component uses the `probabilistic early expiration`_ algorithm to
+protect against the :ref:`cache stampede ` problem.
+This means that some cache items are elected for early-expiration while they are
+still fresh.
+
+By default, expired cache items are computed synchronously. However, you can
+compute them asynchronously by delegating the value computation to a background
+worker using the :doc:`Messenger component `. In this case,
+when an item is queried, its cached value is immediately returned and a
+:class:`Symfony\\Component\\Cache\\Messenger\\EarlyExpirationMessage` is
+dispatched through a Messenger bus.
+
+When this message is handled by a message consumer, the refreshed cache value is
+computed asynchronously. The next time the item is queried, the refreshed value
+will be fresh and returned.
+
+First, create a service that will compute the item's value::
+
+ // src/Cache/CacheComputation.php
+ namespace App\Cache;
+
+ use Symfony\Contracts\Cache\ItemInterface;
+
+ class CacheComputation
+ {
+ public function compute(ItemInterface $item): string
+ {
+ $item->expiresAfter(5);
+
+ // this is just a random example; here you must do your own calculation
+ return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
+ }
+ }
+
+This cache value will be requested from a controller, another service, etc.
+In the following example, the value is requested from a controller::
+
+ // src/Controller/CacheController.php
+ namespace App\Controller;
+
+ use App\Cache\CacheComputation;
+ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+ use Symfony\Component\Routing\Attribute\Route;
+ use Symfony\Contracts\Cache\CacheInterface;
+ use Symfony\Contracts\Cache\ItemInterface;
+
+ class CacheController extends AbstractController
+ {
+ #[Route('/cache', name: 'cache')]
+ public function index(CacheInterface $asyncCache): Response
+ {
+ // pass to the cache the service method that refreshes the item
+ $cachedValue = $asyncCache->get('my_value', [CacheComputation::class, 'compute'])
+
+ // ...
+ }
+ }
+
+Finally, configure a new cache pool (e.g. called ``async.cache``) that will use
+a message bus to compute values in a worker:
+
+.. configuration-block::
+
+ .. code-block:: yaml
+
+ # config/packages/framework.yaml
+ framework:
+ cache:
+ pools:
+ async.cache:
+ early_expiration_message_bus: messenger.default_bus
+
+ messenger:
+ transports:
+ async_bus: '%env(MESSENGER_TRANSPORT_DSN)%'
+ routing:
+ 'Symfony\Component\Cache\Messenger\EarlyExpirationMessage': async_bus
+
+ .. code-block:: xml
+
+
+
+
+
+
+
+
+
+
+ %env(MESSENGER_TRANSPORT_DSN)%
+
+
+
+
+
+
+
+ .. code-block:: php
+
+ // config/framework/framework.php
+ use Symfony\Component\Cache\Messenger\EarlyExpirationMessage;
+ use Symfony\Config\FrameworkConfig;
+ use function Symfony\Component\DependencyInjection\Loader\Configurator\env;
+
+ return static function (FrameworkConfig $framework): void {
+ $framework->cache()
+ ->pool('async.cache')
+ ->earlyExpirationMessageBus('messenger.default_bus');
+
+ $framework->messenger()
+ ->transport('async_bus')
+ ->dsn(env('MESSENGER_TRANSPORT_DSN'))
+ ->routing(EarlyExpirationMessage::class)
+ ->senders(['async_bus']);
+ };
+
+You can now start the consumer:
+
+.. code-block:: terminal
+
+ $ php bin/console messenger:consume async_bus
+
+That's it! Now, whenever an item is queried from this cache pool, its cached
+value will be returned immediately. If it is elected for early-expiration, a
+message will be sent through to bus to schedule a background computation to refresh
+the value.
+
+.. _`probabilistic early expiration`: https://en.wikipedia.org/wiki/Cache_stampede#Probabilistic_early_expiration
diff --git a/components/asset.rst b/components/asset.rst
index 71b2aa13027..d6d3f485859 100644
--- a/components/asset.rst
+++ b/components/asset.rst
@@ -1,14 +1,10 @@
-.. index::
- single: Asset
- single: Components; Asset
-
The Asset Component
===================
The Asset component manages URL generation and versioning of web assets such
as CSS stylesheets, JavaScript files and image files.
-In the past, it was common for web applications to hardcode URLs of web assets.
+In the past, it was common for web applications to hard-code the URLs of web assets.
For example:
.. code-block:: html
@@ -17,7 +13,7 @@ For example:
-
+
This practice is no longer recommended unless the web application is extremely
simple. Hardcoding URLs can be a disadvantage because:
@@ -51,6 +47,8 @@ Installation
Usage
-----
+.. _asset-packages:
+
Asset Packages
~~~~~~~~~~~~~~
@@ -147,7 +145,6 @@ corresponding output file:
.. code-block:: json
- // rev-manifest.json
{
"css/app.css": "build/css/app.b916426ea1d10021f3f17ce8031f93c2.css",
"js/app.js": "build/js/app.13630905267b809161e71d0f8a0c017b.js",
@@ -160,11 +157,40 @@ In those cases, use the
use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\VersionStrategy\JsonManifestVersionStrategy;
+ // assumes the JSON file above is called "rev-manifest.json"
$package = new Package(new JsonManifestVersionStrategy(__DIR__.'/rev-manifest.json'));
echo $package->getUrl('css/app.css');
// result: build/css/app.b916426ea1d10021f3f17ce8031f93c2.css
+If you request an asset that is *not found* in the ``rev-manifest.json`` file,
+the original - *unmodified* - asset path will be returned. The ``$strictMode``
+argument helps debug issues because it throws an exception when the asset is not
+listed in the manifest::
+
+ use Symfony\Component\Asset\Package;
+ use Symfony\Component\Asset\VersionStrategy\JsonManifestVersionStrategy;
+
+ // The value of $strictMode can be specific per environment "true" for debugging and "false" for stability.
+ $strictMode = true;
+ // assumes the JSON file above is called "rev-manifest.json"
+ $package = new Package(new JsonManifestVersionStrategy(__DIR__.'/rev-manifest.json', null, $strictMode));
+
+ echo $package->getUrl('not-found.css');
+ // error:
+
+If your JSON file is not on your local filesystem but is accessible over HTTP,
+use the :class:`Symfony\\Component\\Asset\\VersionStrategy\\JsonManifestVersionStrategy`
+with the :doc:`HttpClient component `::
+
+ use Symfony\Component\Asset\Package;
+ use Symfony\Component\Asset\VersionStrategy\JsonManifestVersionStrategy;
+ use Symfony\Component\HttpClient\HttpClient;
+
+ $httpClient = HttpClient::create();
+ $manifestUrl = 'https://cdn.example.com/rev-manifest.json';
+ $package = new Package(new JsonManifestVersionStrategy($manifestUrl, $httpClient));
+
Custom Version Strategies
.........................
@@ -177,19 +203,19 @@ every day::
class DateVersionStrategy implements VersionStrategyInterface
{
- private $version;
+ private string $version;
public function __construct()
{
$this->version = date('Ymd');
}
- public function getVersion($path)
+ public function getVersion(string $path): string
{
return $this->version;
}
- public function applyVersion($path)
+ public function applyVersion(string $path): string
{
return sprintf('%s?v=%s', $path, $this->getVersion($path));
}
@@ -260,12 +286,12 @@ class to generate absolute URLs for their assets::
// ...
$urlPackage = new UrlPackage(
- 'http://static.example.com/images/',
+ 'https://static.example.com/images/',
new StaticVersionStrategy('v1')
);
echo $urlPackage->getUrl('/logo.png');
- // result: http://static.example.com/images/logo.png?v1
+ // result: https://static.example.com/images/logo.png?v1
You can also pass a schema-agnostic URL::
@@ -292,15 +318,15 @@ constructor::
// ...
$urls = [
- '//static1.example.com/images/',
- '//static2.example.com/images/',
+ 'https://static1.example.com/images/',
+ 'https://static2.example.com/images/',
];
$urlPackage = new UrlPackage($urls, new StaticVersionStrategy('v1'));
echo $urlPackage->getUrl('/logo.png');
- // result: http://static1.example.com/images/logo.png?v1
+ // result: https://static1.example.com/images/logo.png?v1
echo $urlPackage->getUrl('/icon.png');
- // result: http://static2.example.com/images/icon.png?v1
+ // result: https://static2.example.com/images/icon.png?v1
For each asset, one of the URLs will be randomly used. But, the selection
is deterministic, meaning that each asset will always be served by the same
@@ -350,14 +376,14 @@ they all have different base paths::
$defaultPackage = new Package($versionStrategy);
$namedPackages = [
- 'img' => new UrlPackage('http://img.example.com/', $versionStrategy),
+ 'img' => new UrlPackage('https://img.example.com/', $versionStrategy),
'doc' => new PathPackage('/somewhere/deep/for/documents', $versionStrategy),
];
$packages = new Packages($defaultPackage, $namedPackages);
The ``Packages`` class allows to define a default package, which will be applied
-to assets that don't define the name of package to use. In addition, this
+to assets that don't define the name of the package to use. In addition, this
application defines a package named ``img`` to serve images from an external
domain and a ``doc`` package to avoid repeating long paths when linking to a
document inside a template::
@@ -366,7 +392,7 @@ document inside a template::
// result: /main.css?v1
echo $packages->getUrl('/logo.png', 'img');
- // result: http://img.example.com/logo.png?v1
+ // result: https://img.example.com/logo.png?v1
echo $packages->getUrl('resume.pdf', 'doc');
// result: /somewhere/deep/for/documents/resume.pdf?v1
@@ -401,6 +427,6 @@ Learn more
----------
* :doc:`How to manage CSS and JavaScript assets in Symfony applications `
-* :doc:`WebLink component ` to preload assets using HTTP/2.
+* :doc:`WebLink component ` to preload assets using HTTP/2.
.. _`Webpack`: https://webpack.js.org/
diff --git a/components/browser_kit.rst b/components/browser_kit.rst
index 33b5a10ea4b..8cf0772298c 100644
--- a/components/browser_kit.rst
+++ b/components/browser_kit.rst
@@ -1,20 +1,9 @@
-.. index::
- single: BrowserKit
- single: Components; BrowserKit
-
The BrowserKit Component
========================
The BrowserKit component simulates the behavior of a web browser, allowing
you to make requests, click on links and submit forms programmatically.
-.. note::
-
- In Symfony versions prior to 4.3, the BrowserKit component could only make
- internal requests to your application. Starting from Symfony 4.3, this
- component can also :ref:`make HTTP requests to any public site `
- when using it in combination with the :doc:`HttpClient component `.
-
Installation
------------
@@ -37,20 +26,19 @@ Creating a Client
~~~~~~~~~~~~~~~~~
The component only provides an abstract client and does not provide any backend
-ready to use for the HTTP layer.
-
-To create your own client, you must extend the abstract ``Client`` class and
-implement the :method:`Symfony\\Component\\BrowserKit\\Client::doRequest` method.
+ready to use for the HTTP layer. To create your own client, you must extend the
+``AbstractBrowser`` class and implement the
+:method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::doRequest` method.
This method accepts a request and should return a response::
namespace Acme;
- use Symfony\Component\BrowserKit\Client as BaseClient;
+ use Symfony\Component\BrowserKit\AbstractBrowser;
use Symfony\Component\BrowserKit\Response;
- class Client extends BaseClient
+ class Client extends AbstractBrowser
{
- protected function doRequest($request)
+ protected function doRequest($request): Response
{
// ... convert request into a response
@@ -59,14 +47,15 @@ This method accepts a request and should return a response::
}
For a simple implementation of a browser based on the HTTP layer, have a look
-at `Goutte`_. For an implementation based on ``HttpKernelInterface``, have
-a look at the :class:`Symfony\\Component\\HttpKernel\\Client` provided by
-the :doc:`HttpKernel component `.
+at the :class:`Symfony\\Component\\BrowserKit\\HttpBrowser` provided by
+:ref:`this component `. For an implementation based
+on ``HttpKernelInterface``, have a look at the :class:`Symfony\\Component\\HttpKernel\\HttpClientKernel`
+provided by the :doc:`HttpKernel component `.
Making Requests
~~~~~~~~~~~~~~~
-Use the :method:`Symfony\\Component\\BrowserKit\\Client::request` method to
+Use the :method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::request` method to
make HTTP requests. The first two arguments are the HTTP method and the requested
URL::
@@ -80,7 +69,17 @@ The value returned by the ``request()`` method is an instance of the
:doc:`DomCrawler component `, which allows accessing
and traversing HTML elements programmatically.
-The :method:`Symfony\\Component\\BrowserKit\\Client::xmlHttpRequest` method,
+The :method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::jsonRequest` method,
+which defines the same arguments as the ``request()`` method, is a shortcut to
+convert the request parameters into a JSON string and set the needed HTTP headers::
+
+ use Acme\Client;
+
+ $client = new Client();
+ // this encodes parameters as JSON and sets the required CONTENT_TYPE and HTTP_ACCEPT headers
+ $crawler = $client->jsonRequest('GET', '/', ['some_parameter' => 'some_value']);
+
+The :method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::xmlHttpRequest` method,
which defines the same arguments as the ``request()`` method, is a shortcut to
make AJAX requests::
@@ -93,7 +92,7 @@ make AJAX requests::
Clicking Links
~~~~~~~~~~~~~~
-The ``Client`` object is capable of simulating link clicks. Pass the text
+The ``AbstractBrowser`` is capable of simulating link clicks. Pass the text
content of the link and the client will perform the needed HTTP GET request to
simulate the link click::
@@ -113,10 +112,28 @@ provides access to the link properties (e.g. ``$link->getMethod()``,
$link = $crawler->selectLink('Go elsewhere...')->link();
$client->click($link);
+The :method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::click` and
+:method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::clickLink` methods
+can take an optional ``serverParameters`` argument. This
+parameter allows to send additional information like headers when clicking
+on a link::
+
+ use Acme\Client;
+
+ $client = new Client();
+ $client->request('GET', '/product/123');
+
+ // works both with `click()`...
+ $link = $crawler->selectLink('Go elsewhere...')->link();
+ $client->click($link, ['X-Custom-Header' => 'Some data']);
+
+ // ... and `clickLink()`
+ $crawler = $client->clickLink('Go elsewhere...', ['X-Custom-Header' => 'Some data']);
+
Submitting Forms
~~~~~~~~~~~~~~~~
-The ``Client`` object is also capable of submitting forms. First, select the
+The ``AbstractBrowser`` is also capable of submitting forms. First, select the
form using any of its buttons and then override any of its properties (method,
field values, etc.) before submitting it::
@@ -126,7 +143,7 @@ field values, etc.) before submitting it::
$crawler = $client->request('GET', 'https://github.com/login');
// find the form with the 'Log in' button and submit it
- // 'Log in' can be the text content, id, value or name of a or
+ // 'Log in' can be the text content, id or name of a or
$client->submitForm('Log in');
// the second optional argument lets you override the default form field values
@@ -161,13 +178,35 @@ provides access to the form properties (e.g. ``$form->getUri()``,
// submit that form
$crawler = $client->submit($form);
+Custom Header Handling
+~~~~~~~~~~~~~~~~~~~~~~
+
+The optional HTTP headers passed to the ``request()`` method follow the FastCGI
+request format (uppercase, underscores instead of dashes and prefixed with ``HTTP_``).
+Before saving those headers to the request, they are lower-cased, with ``HTTP_``
+stripped, and underscores converted into dashes.
+
+If you're making a request to an application that has special rules about header
+capitalization or punctuation, override the ``getHeaders()`` method, which must
+return an associative array of headers::
+
+ protected function getHeaders(Request $request): array
+ {
+ $headers = parent::getHeaders($request);
+ if (isset($request->getServer()['api_key'])) {
+ $headers['api_key'] = $request->getServer()['api_key'];
+ }
+
+ return $headers;
+ }
+
Cookies
-------
Retrieving Cookies
~~~~~~~~~~~~~~~~~~
-The ``Client`` implementation exposes cookies (if any) through a
+The ``AbstractBrowser`` implementation exposes cookies (if any) through a
:class:`Symfony\\Component\\BrowserKit\\CookieJar`, which allows you to store and
retrieve any cookie while making requests with the client::
@@ -248,6 +287,27 @@ into the client constructor::
$client = new Client([], null, $cookieJar);
// ...
+.. _component-browserkit-sending-cookies:
+
+Sending Cookies
+~~~~~~~~~~~~~~~
+
+Requests can include cookies. To do so, use the ``serverParameters`` argument of
+the :method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::request` method
+to set the ``Cookie`` header value::
+
+ $client->request('GET', '/', [], [], [
+ 'HTTP_COOKIE' => new Cookie('flavor', 'chocolate', strtotime('+1 day')),
+
+ // you can also pass the cookie contents as a string
+ 'HTTP_COOKIE' => 'flavor=chocolate; expires=Sat, 11 Feb 2023 12:18:13 GMT; Max-Age=86400; path=/'
+ ]);
+
+.. note::
+
+ All HTTP headers set with the ``serverParameters`` argument must be
+ prefixed by ``HTTP_``.
+
History
-------
@@ -289,7 +349,7 @@ So far, all the examples in this article have assumed that you are making
internal requests to your own application. However, you can run the exact same
examples when making HTTP requests to external web sites and applications.
-First, install and configure the :doc:`HttpClient component `.
+First, install and configure the :doc:`HttpClient component `.
Then, use the :class:`Symfony\\Component\\BrowserKit\\HttpBrowser` to create
the client that will make the external HTTP requests::
@@ -311,6 +371,34 @@ dedicated web crawler or scraper such as `Goutte`_::
'.table-list-header-toggle a:nth-child(1)'
)->text());
+.. tip::
+
+ You can also use HTTP client options like ``ciphers``, ``auth_basic`` and
+ ``query``. They have to be passed as the default options argument to the
+ client which is used by the HTTP browser.
+
+Dealing with HTTP responses
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+When using the BrowserKit component, you may need to deal with responses of
+the requests you made. To do so, call the ``getResponse()`` method of the
+``HttpBrowser`` object. This method returns the last response the browser received::
+
+ $browser = new HttpBrowser(HttpClient::create());
+
+ $browser->request('GET', 'https://foo.com');
+ $response = $browser->getResponse();
+
+If you're making requests that result in a JSON response, you may use the
+``toArray()`` method to turn the JSON document into a PHP array without having
+to call ``json_decode()`` explicitly::
+
+ $browser = new HttpBrowser(HttpClient::create());
+
+ $browser->request('GET', 'https://api.foo.com');
+ $response = $browser->getResponse()->toArray();
+ // $response is a PHP array of the decoded JSON contents
+
Learn more
----------
diff --git a/components/cache.rst b/components/cache.rst
index d323113e9bd..44ba8b5c151 100644
--- a/components/cache.rst
+++ b/components/cache.rst
@@ -1,8 +1,3 @@
-.. index::
- single: Cache
- single: Performance
- single: Components; Cache
-
.. _`cache-component`:
The Cache Component
@@ -16,9 +11,8 @@ The Cache Component
.. tip::
- The component also contains adapters to convert between PSR-6, PSR-16 and
- Doctrine caches. See :doc:`/components/cache/psr6_psr16_adapters` and
- :doc:`/components/cache/adapters/doctrine_adapter`.
+ The component also contains adapters to convert between PSR-6 and PSR-16.
+ See :doc:`/components/cache/psr6_psr16_adapters`.
Installation
------------
@@ -71,7 +65,7 @@ generate and return the value::
use Symfony\Contracts\Cache\ItemInterface;
// The callable will only be executed on a cache miss.
- $value = $cache->get('my_cache_key', function (ItemInterface $item) {
+ $value = $cache->get('my_cache_key', function (ItemInterface $item): string {
$item->expiresAfter(3600);
// ... do some HTTP request or heavy computations
@@ -90,14 +84,82 @@ generate and return the value::
Use cache tags to delete more than one key at the time. Read more at
:doc:`/components/cache/cache_invalidation`.
-The Cache Contracts also comes with built in `Stampede prevention`_. This will
+Creating Sub-Namespaces
+-----------------------
+
+.. versionadded:: 7.3
+
+ Cache sub-namespaces were introduced in Symfony 7.3.
+
+Sometimes you need to create context-dependent variations of data that should be
+cached. For example, the data used to render a dashboard page may be expensive
+to generate and unique per user, so you can't cache the same data for everyone.
+
+In such cases, Symfony allows you to create different cache contexts using
+namespaces. A cache namespace is an arbitrary string that identifies a set of
+related cache items. All cache adapters provided by the component implement the
+:class:`Symfony\\Contracts\\Cache\\NamespacedPoolInterface`, which provides the
+:method:`Symfony\\Contracts\\Cache\\NamespacedPoolInterface::withSubNamespace`
+method.
+
+This method allows you to namespace cached items by transparently prefixing their keys::
+
+ $userCache = $cache->withSubNamespace(sprintf('user-%d', $user->getId()));
+
+ $userCache->get('dashboard_data', function (ItemInterface $item): string {
+ $item->expiresAfter(3600);
+
+ return '...';
+ });
+
+In this example, the cache item uses the ``dashboard_data`` key, but it will be
+stored internally under a namespace based on the current user ID. This is handled
+automatically, so you **don't** need to manually prefix keys like ``user-27.dashboard_data``.
+
+There are no guidelines or restrictions on how to define cache namespaces.
+You can make them as granular or as generic as your application requires::
+
+ $localeCache = $cache->withSubNamespace($request->getLocale());
+
+ $flagCache = $cache->withSubNamespace(
+ $featureToggle->isEnabled('new_checkout') ? 'checkout-v2' : 'checkout-v1'
+ );
+
+ $channel = $request->attributes->get('_route')?->startsWith('api_') ? 'api' : 'web';
+ $channelCache = $cache->withSubNamespace($channel);
+
+.. tip::
+
+ You can combine cache namespaces with :ref:`cache tags `
+ for more advanced needs.
+
+There is no built-in way to invalidate caches by namespace. Instead, the recommended
+approach is to change the namespace itself. For this reason, it's common to include
+static or dynamic versioning data in the cache namespace::
+
+ // for simple applications, an incrementing static version number may be enough
+ $userCache = $cache->withSubNamespace(sprintf('v1-user-%d', $user->getId()));
+
+ // other applications may use dynamic versioning based on the date (e.g. monthly)
+ $userCache = $cache->withSubNamespace(sprintf('%s-user-%d', date('Ym'), $user->getId()));
+
+ // or even invalidate the cache when the user data changes
+ $checksum = hash('xxh128', $user->getUpdatedAt()->format(DATE_ATOM));
+ $userCache = $cache->withSubNamespace(sprintf('user-%d-%s', $user->getId(), $checksum));
+
+.. _cache_stampede-prevention:
+
+Stampede Prevention
+~~~~~~~~~~~~~~~~~~~
+
+The Cache Contracts also come with built in `Stampede prevention`_. This will
remove CPU spikes at the moments when the cache is cold. If an example application
spends 5 seconds to compute data that is cached for 1 hour and this data is accessed
10 times every second, this means that you mostly have cache hits and everything
is fine. But after 1 hour, we get 10 new requests to a cold cache. So the data
is computed again. The next second the same thing happens. So the data is computed
about 50 times before the cache is warm again. This is where you need stampede
-prevention
+prevention.
The first solution is to use locking: only allow one PHP process (on a per-host basis)
to compute a specific key at a time. Locking is built-in by default, so
@@ -118,7 +180,7 @@ recompute::
use Symfony\Contracts\Cache\ItemInterface;
$beta = 1.0;
- $value = $cache->get('my_cache_key', function (ItemInterface $item) {
+ $value = $cache->get('my_cache_key', function (ItemInterface $item): string {
$item->expiresAfter(3600);
$item->tag(['tag_0', 'tag_1']);
@@ -136,7 +198,6 @@ The following cache adapters are available:
cache/adapters/*
-
.. _cache-component-psr6-caching:
Generic Caching (PSR-6)
@@ -156,7 +217,7 @@ concepts:
**Adapter**
It implements the actual caching mechanism to store the information in the
filesystem, in a database, etc. The component provides several ready to use
- adapters for common caching backends (Redis, APCu, Doctrine, PDO, etc.)
+ adapters for common caching backends (Redis, APCu, PDO, etc.)
Basic Usage (PSR-6)
-------------------
@@ -192,6 +253,45 @@ Now you can create, retrieve, update and delete items using this cache pool::
For a list of all of the supported adapters, see :doc:`/components/cache/cache_pools`.
+Marshalling (Serializing) Data
+------------------------------
+
+.. note::
+
+ `Marshalling`_ and `serializing`_ are similar concepts. Serializing is the
+ process of translating an object state into a format that can be stored
+ (e.g. in a file). Marshalling is the process of translating both the object
+ state and its codebase into a format that can be stored or transmitted.
+
+ Unmarshalling an object produces a copy of the original object, possibly by
+ automatically loading the class definitions of the object.
+
+Symfony uses *marshallers* (classes which implement
+:class:`Symfony\\Component\\Cache\\Marshaller\\MarshallerInterface`) to process
+the cache items before storing them.
+
+The :class:`Symfony\\Component\\Cache\\Marshaller\\DefaultMarshaller` uses PHP's
+``serialize()`` function by default, but you can optionally use the ``igbinary_serialize()``
+function from the `Igbinary extension`_::
+
+ use Symfony\Component\Cache\Adapter\RedisAdapter;
+ use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
+ use Symfony\Component\Cache\Marshaller\DeflateMarshaller;
+
+ $marshaller = new DeflateMarshaller(new DefaultMarshaller());
+ // you can optionally use the Igbinary extension if you have it installed
+ // $marshaller = new DeflateMarshaller(new DefaultMarshaller(useIgbinarySerialize: true));
+
+ $cache = new RedisAdapter(new \Redis(), 'namespace', 0, $marshaller);
+
+There are other *marshallers* that can encrypt or compress the data before storing it.
+
+.. versionadded:: 7.2
+
+ In Symfony versions prior to 7.2, the ``igbinary_serialize()`` function was
+ used by default when the Igbinary extension was installed. Starting from
+ Symfony 7.2, you have to enable Igbinary support explicitly.
+
Advanced Usage
--------------
@@ -201,7 +301,10 @@ Advanced Usage
cache/*
-.. _`PSR-6`: http://www.php-fig.org/psr/psr-6/
+.. _`PSR-6`: https://www.php-fig.org/psr/psr-6/
.. _`Cache Contracts`: https://github.com/symfony/contracts/blob/master/Cache/CacheInterface.php
.. _`Stampede prevention`: https://en.wikipedia.org/wiki/Cache_stampede
.. _Probabilistic early expiration: https://en.wikipedia.org/wiki/Cache_stampede#Probabilistic_early_expiration
+.. _`Marshalling`: https://en.wikipedia.org/wiki/Marshalling_(computer_science)
+.. _`serializing`: https://en.wikipedia.org/wiki/Serialization
+.. _`Igbinary extension`: https://github.com/igbinary/igbinary
diff --git a/components/cache/adapters/apcu_adapter.rst b/components/cache/adapters/apcu_adapter.rst
index 17ecd4058e6..f2e92850cd8 100644
--- a/components/cache/adapters/apcu_adapter.rst
+++ b/components/cache/adapters/apcu_adapter.rst
@@ -1,9 +1,3 @@
-.. index::
- single: Cache Pool
- single: APCu Cache
-
-.. _apcu-adapter:
-
APCu Cache Adapter
==================
@@ -11,7 +5,7 @@ This adapter is a high-performance, shared memory cache. It can *significantly*
increase an application's performance, as its cache contents are stored in shared
memory, a component appreciably faster than many others, such as the filesystem.
-.. caution::
+.. warning::
**Requirement:** The `APCu extension`_ must be installed and active to use
this adapter.
@@ -36,7 +30,7 @@ and cache items version string as constructor arguments::
$version = null
);
-.. caution::
+.. warning::
Use of this adapter is discouraged in write/delete heavy workloads, as these
operations cause memory fragmentation that results in significantly degraded performance.
diff --git a/components/cache/adapters/array_cache_adapter.rst b/components/cache/adapters/array_cache_adapter.rst
index ffdc1d60dd0..08f8276db3d 100644
--- a/components/cache/adapters/array_cache_adapter.rst
+++ b/components/cache/adapters/array_cache_adapter.rst
@@ -1,17 +1,10 @@
-.. index::
- single: Cache Pool
- single: Array Cache
-
Array Cache Adapter
===================
Generally, this adapter is useful for testing purposes, as its contents are stored in memory
and not persisted outside the running PHP process in any way. It can also be useful while
warming up caches, due to the :method:`Symfony\\Component\\Cache\\Adapter\\ArrayAdapter::getValues`
-method.
-
-This adapter can be passed a default cache lifetime as its first parameter, and a boolean that
-toggles serialization as its second parameter::
+method::
use Symfony\Component\Cache\Adapter\ArrayAdapter;
@@ -22,6 +15,23 @@ toggles serialization as its second parameter::
// until the current PHP process finishes)
$defaultLifetime = 0,
- // if ``true``, the values saved in the cache are serialized before storing them
- $storeSerialized = true
+ // if true, the values saved in the cache are serialized before storing them
+ $storeSerialized = true,
+
+ // the maximum lifetime (in seconds) of the entire cache (after this time, the
+ // entire cache is deleted to avoid stale data from consuming memory)
+ $maxLifetime = 0,
+
+ // the maximum number of items that can be stored in the cache. When the limit
+ // is reached, cache follows the LRU model (least recently used items are deleted)
+ $maxItems = 0,
+
+ // optional implementation of the Psr\Clock\ClockInterface that will be used
+ // to calculate the lifetime of cache items (for example to get predictable
+ // lifetimes in tests)
+ $clock = null,
);
+
+.. versionadded:: 7.2
+
+ The optional ``$clock`` argument was introduced in Symfony 7.2.
diff --git a/components/cache/adapters/chain_adapter.rst b/components/cache/adapters/chain_adapter.rst
index de7555029d2..586857d2e4d 100644
--- a/components/cache/adapters/chain_adapter.rst
+++ b/components/cache/adapters/chain_adapter.rst
@@ -1,9 +1,3 @@
-.. index::
- single: Cache Pool
- single: Chain Cache
-
-.. _component-cache-chain-adapter:
-
Chain Cache Adapter
===================
@@ -12,7 +6,7 @@ This adapter allows combining any number of the other
fetched from the first adapter containing them and cache items are saved to all the
given adapters. This exposes a simple and efficient method for creating a layered cache.
-The ChainAdapter must be provided an array of adapters and optionally a maximum cache
+The ChainAdapter must be provided an array of adapters and optionally a default cache
lifetime as its constructor arguments::
use Symfony\Component\Cache\Adapter\ChainAdapter;
@@ -21,8 +15,8 @@ lifetime as its constructor arguments::
// The ordered list of adapters used to fetch cached items
array $adapters,
- // The max lifetime of items propagated from lower adapters to upper ones
- $maxLifetime = 0
+ // The default lifetime of items propagated from lower adapters to upper ones
+ $defaultLifetime = 0
);
.. note::
@@ -44,7 +38,7 @@ slowest storage engines, :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter
new FilesystemAdapter(),
]);
-When calling this adapter's :method:`Symfony\\Component\\Cache\\ChainAdapter::prune` method,
+When calling this adapter's :method:`Symfony\\Component\\Cache\\Adapter\\ChainAdapter::prune` method,
the call is delegated to all its compatible cache adapters. It is safe to mix both adapters
that *do* and do *not* implement :class:`Symfony\\Component\\Cache\\PruneableInterface`, as
incompatible adapters are silently ignored::
diff --git a/components/cache/adapters/couchbasebucket_adapter.rst b/components/cache/adapters/couchbasebucket_adapter.rst
new file mode 100644
index 00000000000..29c9e26f83c
--- /dev/null
+++ b/components/cache/adapters/couchbasebucket_adapter.rst
@@ -0,0 +1,144 @@
+Couchbase Bucket Cache Adapter
+==============================
+
+.. deprecated:: 7.1
+
+ The ``CouchbaseBucketAdapter`` is deprecated since Symfony 7.1, use the
+ :doc:`CouchbaseCollectionAdapter `
+ instead.
+
+This adapter stores the values in-memory using one (or more) `Couchbase server`_
+instances. Unlike the :doc:`APCu adapter `, and similarly to the
+:doc:`Memcached adapter `, it is not limited to the current server's
+shared memory; you can store contents independent of your PHP environment.
+The ability to utilize a cluster of servers to provide redundancy and/or fail-over
+is also available.
+
+.. warning::
+
+ **Requirements:** The `Couchbase PHP extension`_ as well as a `Couchbase server`_
+ must be installed, active, and running to use this adapter. Version ``2.6`` or
+ less than 3.0 of the `Couchbase PHP extension`_ is required for this adapter.
+
+This adapter expects a `Couchbase Bucket`_ instance to be passed as the first
+parameter. A namespace and default cache lifetime can optionally be passed as
+the second and third parameters::
+
+ use Symfony\Component\Cache\Adapter\CouchbaseBucketAdapter;
+
+ $cache = new CouchbaseBucketAdapter(
+ // the client object that sets options and adds the server instance(s)
+ $client,
+
+ // the name of bucket
+ $bucket,
+
+ // a string prefixed to the keys of the items stored in this cache
+ $namespace,
+
+ // the default lifetime (in seconds) for cache items that do not define their
+ // own lifetime, with a value 0 causing items to be stored indefinitely
+ $defaultLifetime
+ );
+
+Configure the Connection
+------------------------
+
+The :method:`Symfony\\Component\\Cache\\Adapter\\CouchbaseBucketAdapter::createConnection`
+helper method allows creating and configuring a `Couchbase Bucket`_ class instance using a
+`Data Source Name (DSN)`_ or an array of DSNs::
+
+ use Symfony\Component\Cache\Adapter\CouchbaseBucketAdapter;
+
+ // pass a single DSN string to register a single server with the client
+ $client = CouchbaseBucketAdapter::createConnection(
+ 'couchbase://localhost'
+ // the DSN can include config options (pass them as a query string):
+ // 'couchbase://localhost:11210?operationTimeout=10'
+ // 'couchbase://localhost:11210?operationTimeout=10&configTimeout=20'
+ );
+
+ // pass an array of DSN strings to register multiple servers with the client
+ $client = CouchbaseBucketAdapter::createConnection([
+ 'couchbase://10.0.0.100',
+ 'couchbase://10.0.0.101',
+ 'couchbase://10.0.0.102',
+ // etc...
+ ]);
+
+ // a single DSN can define multiple servers using the following syntax:
+ // host[hostname-or-IP:port] (where port is optional). Sockets must include a trailing ':'
+ $client = CouchbaseBucketAdapter::createConnection(
+ 'couchbase:?host[localhost]&host[localhost:12345]'
+ );
+
+Configure the Options
+---------------------
+
+The :method:`Symfony\\Component\\Cache\\Adapter\\CouchbaseBucketAdapter::createConnection`
+helper method also accepts an array of options as its second argument. The
+expected format is an associative array of ``key => value`` pairs representing
+option names and their respective values::
+
+ use Symfony\Component\Cache\Adapter\CouchbaseBucketAdapter;
+
+ $client = CouchbaseBucketAdapter::createConnection(
+ // a DSN string or an array of DSN strings
+ [],
+
+ // associative array of configuration options
+ [
+ 'username' => 'xxxxxx',
+ 'password' => 'yyyyyy',
+ 'configTimeout' => '100',
+ ]
+ );
+
+Available Options
+~~~~~~~~~~~~~~~~~
+
+``username`` (type: ``string``)
+ Username for connection ``CouchbaseCluster``.
+
+``password`` (type: ``string``)
+ Password of connection ``CouchbaseCluster``.
+
+``operationTimeout`` (type: ``int``, default: ``2500000``)
+ The operation timeout (in microseconds) is the maximum amount of time the library will
+ wait for an operation to receive a response before invoking its callback with a failure status.
+
+``configTimeout`` (type: ``int``, default: ``5000000``)
+ How long (in microseconds) the client will wait to obtain the initial configuration.
+
+``configNodeTimeout`` (type: ``int``, default: ``2000000``)
+ Per-node configuration timeout (in microseconds).
+
+``viewTimeout`` (type: ``int``, default: ``75000000``)
+ The I/O timeout (in microseconds) for HTTP requests to Couchbase Views API.
+
+``httpTimeout`` (type: ``int``, default: ``75000000``)
+ The I/O timeout (in microseconds) for HTTP queries (management API).
+
+``configDelay`` (type: ``int``, default: ``10000``)
+ Config refresh throttling
+ Modify the amount of time (in microseconds) before the configuration error threshold will forcefully be set to its maximum number forcing a configuration refresh.
+
+``htconfigIdleTimeout`` (type: ``int``, default: ``4294967295``)
+ Idling/Persistence for HTTP bootstrap (in microseconds).
+
+``durabilityInterval`` (type: ``int``, default: ``100000``)
+ The time (in microseconds) the client will wait between repeated probes to a given server.
+
+``durabilityTimeout`` (type: ``int``, default: ``5000000``)
+ The time (in microseconds) the client will spend sending repeated probes to a given key's vBucket masters and replicas before they are deemed not to have satisfied the durability requirements.
+
+.. tip::
+
+ Reference the `Couchbase Bucket`_ extension's `predefined constants`_ documentation
+ for additional information about the available options.
+
+.. _`Couchbase PHP extension`: https://docs.couchbase.com/sdk-api/couchbase-php-client-2.6.0/files/couchbase.html
+.. _`predefined constants`: https://docs.couchbase.com/sdk-api/couchbase-php-client-2.6.0/classes/Couchbase.Bucket.html
+.. _`Couchbase server`: https://couchbase.com/
+.. _`Couchbase Bucket`: https://docs.couchbase.com/sdk-api/couchbase-php-client-2.6.0/classes/Couchbase.Bucket.html
+.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name
diff --git a/components/cache/adapters/couchbasecollection_adapter.rst b/components/cache/adapters/couchbasecollection_adapter.rst
new file mode 100644
index 00000000000..ba78cc46eff
--- /dev/null
+++ b/components/cache/adapters/couchbasecollection_adapter.rst
@@ -0,0 +1,135 @@
+Couchbase Collection Cache Adapter
+==================================
+
+This adapter stores the values in-memory using one (or more) `Couchbase server`_
+instances. Unlike the :doc:`APCu adapter `, and similarly to the
+:doc:`Memcached adapter `, it is not limited to the current server's
+shared memory; you can store contents independent of your PHP environment.
+The ability to utilize a cluster of servers to provide redundancy and/or fail-over
+is also available.
+
+.. warning::
+
+ **Requirements:** The `Couchbase PHP extension`_ as well as a `Couchbase server`_
+ must be installed, active, and running to use this adapter. Version ``3.0`` or
+ greater of the `Couchbase PHP extension`_ is required for this adapter.
+
+This adapter expects a `Couchbase Collection`_ instance to be passed as the first
+parameter. A namespace and default cache lifetime can optionally be passed as
+the second and third parameters::
+
+ use Symfony\Component\Cache\Adapter\CouchbaseCollectionAdapter;
+
+ $cache = new CouchbaseCollectionAdapter(
+ // the client object that sets options and adds the server instance(s)
+ $client,
+
+ // a string prefixed to the keys of the items stored in this cache
+ $namespace,
+
+ // the default lifetime (in seconds) for cache items that do not define their
+ // own lifetime, with a value 0 causing items to be stored indefinitely
+ $defaultLifetime
+ );
+
+Configure the Connection
+------------------------
+
+The :method:`Symfony\\Component\\Cache\\Adapter\\CouchbaseCollectionAdapter::createConnection`
+helper method allows creating and configuring a `Couchbase Collection`_ class instance using a
+`Data Source Name (DSN)`_ or an array of DSNs::
+
+ use Symfony\Component\Cache\Adapter\CouchbaseCollectionAdapter;
+
+ // pass a single DSN string to register a single server with the client
+ $client = CouchbaseCollectionAdapter::createConnection(
+ 'couchbase://localhost'
+ // the DSN can include config options (pass them as a query string):
+ // 'couchbase://localhost:11210?operationTimeout=10'
+ // 'couchbase://localhost:11210?operationTimeout=10&configTimout=20'
+ );
+
+ // pass an array of DSN strings to register multiple servers with the client
+ $client = CouchbaseCollectionAdapter::createConnection([
+ 'couchbase://10.0.0.100',
+ 'couchbase://10.0.0.101',
+ 'couchbase://10.0.0.102',
+ // etc...
+ ]);
+
+ // a single DSN can define multiple servers using the following syntax:
+ // host[hostname-or-IP:port] (where port is optional). Sockets must include a trailing ':'
+ $client = CouchbaseCollectionAdapter::createConnection(
+ 'couchbase:?host[localhost]&host[localhost:12345]'
+ );
+
+Configure the Options
+---------------------
+
+The :method:`Symfony\\Component\\Cache\\Adapter\\CouchbaseCollectionAdapter::createConnection`
+helper method also accepts an array of options as its second argument. The
+expected format is an associative array of ``key => value`` pairs representing
+option names and their respective values::
+
+ use Symfony\Component\Cache\Adapter\CouchbaseCollectionAdapter;
+
+ $client = CouchbaseCollectionAdapter::createConnection(
+ // a DSN string or an array of DSN strings
+ [],
+
+ // associative array of configuration options
+ [
+ 'username' => 'xxxxxx',
+ 'password' => 'yyyyyy',
+ 'configTimeout' => '100',
+ ]
+ );
+
+Available Options
+~~~~~~~~~~~~~~~~~
+
+``username`` (type: ``string``)
+ Username for connection ``CouchbaseCluster``.
+
+``password`` (type: ``string``)
+ Password of connection ``CouchbaseCluster``.
+
+``operationTimeout`` (type: ``int``, default: ``2500000``)
+ The operation timeout (in microseconds) is the maximum amount of time the library will
+ wait for an operation to receive a response before invoking its callback with a failure status.
+
+``configTimeout`` (type: ``int``, default: ``5000000``)
+ How long (in microseconds) the client will wait to obtain the initial configuration.
+
+``configNodeTimeout`` (type: ``int``, default: ``2000000``)
+ Per-node configuration timeout (in microseconds).
+
+``viewTimeout`` (type: ``int``, default: ``75000000``)
+ The I/O timeout (in microseconds) for HTTP requests to Couchbase Views API.
+
+``httpTimeout`` (type: ``int``, default: ``75000000``)
+ The I/O timeout (in microseconds) for HTTP queries (management API).
+
+``configDelay`` (type: ``int``, default: ``10000``)
+ Config refresh throttling
+ Modify the amount of time (in microseconds) before the configuration error threshold will forcefully be set to its maximum number forcing a configuration refresh.
+
+``htconfigIdleTimeout`` (type: ``int``, default: ``4294967295``)
+ Idling/Persistence for HTTP bootstrap (in microseconds).
+
+``durabilityInterval`` (type: ``int``, default: ``100000``)
+ The time (in microseconds) the client will wait between repeated probes to a given server.
+
+``durabilityTimeout`` (type: ``int``, default: ``5000000``)
+ The time (in microseconds) the client will spend sending repeated probes to a given key's vBucket masters and replicas before they are deemed not to have satisfied the durability requirements.
+
+.. tip::
+
+ Reference the `Couchbase Collection`_ extension's `predefined constants`_ documentation
+ for additional information about the available options.
+
+.. _`Couchbase PHP extension`: https://docs.couchbase.com/sdk-api/couchbase-php-client/namespaces/couchbase.html
+.. _`predefined constants`: https://docs.couchbase.com/sdk-api/couchbase-php-client/classes/Couchbase-Bucket.html
+.. _`Couchbase server`: https://couchbase.com/
+.. _`Couchbase Collection`: https://docs.couchbase.com/sdk-api/couchbase-php-client/classes/Couchbase-Collection.html
+.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name
diff --git a/components/cache/adapters/doctrine_adapter.rst b/components/cache/adapters/doctrine_adapter.rst
deleted file mode 100644
index 198ae19338c..00000000000
--- a/components/cache/adapters/doctrine_adapter.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-.. index::
- single: Cache Pool
- single: Doctrine Cache
-
-.. _doctrine-adapter:
-
-Doctrine Cache Adapter
-======================
-
-This adapter wraps any class extending the `Doctrine Cache`_ abstract provider, allowing
-you to use these providers in your application as if they were Symfony Cache adapters.
-
-This adapter expects a ``\Doctrine\Common\Cache\CacheProvider`` instance as its first
-parameter, and optionally a namespace and default cache lifetime as its second and
-third parameters::
-
- use Doctrine\Common\Cache\CacheProvider;
- use Doctrine\Common\Cache\SQLite3Cache;
- use Symfony\Component\Cache\Adapter\DoctrineAdapter;
-
- $provider = new SQLite3Cache(new \SQLite3(__DIR__.'/cache/data.sqlite'), 'youTableName');
-
- $cache = new DoctrineAdapter(
-
- // a cache provider instance
- CacheProvider $provider,
-
- // a string prefixed to the keys of the items stored in this cache
- $namespace = '',
-
- // the default lifetime (in seconds) for cache items that do not define their
- // own lifetime, with a value 0 causing items to be stored indefinitely (i.e.
- // until the database table is truncated or its rows are otherwise deleted)
- $defaultLifetime = 0
- );
-
-.. tip::
-
- A :class:`Symfony\\Component\\Cache\\DoctrineProvider` class is also provided by the
- component to use any PSR6-compatible implementations with Doctrine-compatible classes.
-
-.. _`Doctrine Cache`: https://github.com/doctrine/cache
diff --git a/components/cache/adapters/doctrine_dbal_adapter.rst b/components/cache/adapters/doctrine_dbal_adapter.rst
new file mode 100644
index 00000000000..68732ddd3fa
--- /dev/null
+++ b/components/cache/adapters/doctrine_dbal_adapter.rst
@@ -0,0 +1,60 @@
+Doctrine DBAL Cache Adapter
+===========================
+
+The Doctrine DBAL adapters store the cache items in a table of an SQL database.
+
+.. note::
+
+ This adapter implements :class:`Symfony\\Component\\Cache\\PruneableInterface`,
+ allowing for manual :ref:`pruning of expired cache entries `
+ by calling the ``prune()`` method.
+
+The :class:`Symfony\\Component\\Cache\\Adapter\\DoctrineDbalAdapter` requires a
+`Doctrine DBAL Connection`_, or `Doctrine DBAL URL`_ as its first parameter.
+You can pass a namespace, default cache lifetime, and options array as the other
+optional arguments::
+
+ use Symfony\Component\Cache\Adapter\DoctrineDbalAdapter;
+
+ $cache = new DoctrineDbalAdapter(
+
+ // a Doctrine DBAL connection or DBAL URL
+ $databaseConnectionOrURL,
+
+ // the string prefixed to the keys of the items stored in this cache
+ $namespace = '',
+
+ // the default lifetime (in seconds) for cache items that do not define their
+ // own lifetime, with a value 0 causing items to be stored indefinitely (i.e.
+ // until the database table is truncated or its rows are otherwise deleted)
+ $defaultLifetime = 0,
+
+ // an array of options for configuring the database table and connection
+ $options = []
+ );
+
+.. note::
+
+ DBAL Connection are lazy-loaded by default; some additional options may be
+ necessary to detect the database engine and version without opening the
+ connection.
+
+The adapter uses SQL syntax that is optimized for database server that it is connected to.
+The following database servers are known to be compatible:
+
+* MySQL 5.7 and newer
+* MariaDB 10.2 and newer
+* Oracle 10g and newer
+* SQL Server 2012 and newer
+* SQLite 3.24 or later
+* PostgreSQL 9.5 or later
+
+.. note::
+
+ Newer releases of Doctrine DBAL might increase these minimal versions. Check
+ the manual page on `Doctrine DBAL Platforms`_ if your database server is
+ compatible with the installed Doctrine DBAL version.
+
+.. _`Doctrine DBAL Connection`: https://github.com/doctrine/dbal/blob/master/src/Connection.php
+.. _`Doctrine DBAL URL`: https://www.doctrine-project.org/projects/doctrine-dbal/en/current/reference/configuration.html#connecting-using-a-url
+.. _`Doctrine DBAL Platforms`: https://www.doctrine-project.org/projects/doctrine-dbal/en/current/reference/platforms.html
diff --git a/components/cache/adapters/filesystem_adapter.rst b/components/cache/adapters/filesystem_adapter.rst
index 33097fbd202..db877454859 100644
--- a/components/cache/adapters/filesystem_adapter.rst
+++ b/components/cache/adapters/filesystem_adapter.rst
@@ -1,14 +1,8 @@
-.. index::
- single: Cache Pool
- single: Filesystem Cache
-
-.. _component-cache-filesystem-adapter:
-
Filesystem Cache Adapter
========================
This adapter offers improved application performance for those who cannot install
-tools like :ref:`APCu ` or :ref:`Redis ` in their
+tools like :doc:`APCu ` or :doc:`Redis ` in their
environment. It stores the cache item expiration and content as regular files in
a collection of directories on a locally mounted filesystem.
@@ -39,21 +33,35 @@ and cache root path as constructor parameters::
$directory = null
);
-.. caution::
+.. warning::
The overhead of filesystem IO often makes this adapter one of the *slower*
choices. If throughput is paramount, the in-memory adapters
- (:ref:`Apcu `, :ref:`Memcached `, and
- :ref:`Redis `) or the database adapters
- (:ref:`Doctrine ` and :ref:`PDO `)
+ (:doc:`Apcu `, :doc:`Memcached `,
+ and :doc:`Redis `) or the database adapters
+ (:doc:`Doctrine DBAL `, :doc:`PDO `)
are recommended.
.. note::
- Since Symfony 3.4, this adapter implements
- :class:`Symfony\\Component\\Cache\\PruneableInterface`, enabling manual
- :ref:`pruning of expired cache items ` by
- calling its ``prune()`` method.
+ This adapter implements :class:`Symfony\\Component\\Cache\\PruneableInterface`,
+ enabling manual :ref:`pruning of expired cache items `
+ by calling its ``prune()`` method.
+
+.. _filesystem-tag-aware-adapter:
+
+Working with Tags
+-----------------
+
+In order to use tag-based invalidation, you can wrap your adapter in
+:class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapter`, but it's often
+more interesting to use the dedicated :class:`Symfony\\Component\\Cache\\Adapter\\FilesystemTagAwareAdapter`.
+Since tag invalidation logic is implemented using links on filesystem, this
+adapter offers better read performance when using tag-based invalidation::
+
+ use Symfony\Component\Cache\Adapter\FilesystemTagAwareAdapter;
+
+ $cache = new FilesystemTagAwareAdapter();
.. _`tmpfs`: https://wiki.archlinux.org/index.php/tmpfs
.. _`RAM disk solutions`: https://en.wikipedia.org/wiki/List_of_RAM_drive_software
diff --git a/components/cache/adapters/memcached_adapter.rst b/components/cache/adapters/memcached_adapter.rst
index 6ebbe93d36d..64baf0d4702 100644
--- a/components/cache/adapters/memcached_adapter.rst
+++ b/components/cache/adapters/memcached_adapter.rst
@@ -1,20 +1,14 @@
-.. index::
- single: Cache Pool
- single: Memcached Cache
-
-.. _memcached-adapter:
-
Memcached Cache Adapter
=======================
This adapter stores the values in-memory using one (or more) `Memcached server`_
-instances. Unlike the :ref:`APCu adapter `, and similarly to the
-:ref:`Redis adapter `, it is not limited to the current server's
+instances. Unlike the :doc:`APCu adapter `, and similarly to the
+:doc:`Redis adapter `, it is not limited to the current server's
shared memory; you can store contents independent of your PHP environment.
The ability to utilize a cluster of servers to provide redundancy and/or fail-over
is also available.
-.. caution::
+.. warning::
**Requirements:** The `Memcached PHP extension`_ as well as a `Memcached server`_
must be installed, active, and running to use this adapter. Version ``2.2`` or
@@ -120,7 +114,6 @@ option names and their respective values::
// associative array of configuration options
[
- 'compression' => true,
'libketama_compatible' => true,
'serializer' => 'igbinary',
]
@@ -139,17 +132,6 @@ Available Options
server(s). Any action that retrieves data, quits the connection, or closes
down the connection will cause the buffer to be committed.
-``compression`` (type: ``bool``, default: ``true``)
- Enables or disables payload compression, where item values longer than 100
- bytes are compressed during storage and decompressed during retrieval.
-
-``compression_type`` (type: ``string``)
- Specifies the compression method used on value payloads. when the
- **compression** option is enabled.
-
- Valid option values include ``fastlz`` and ``zlib``, with a default value
- that *varies based on flags used at compilation*.
-
``connect_timeout`` (type: ``int``, default: ``1000``)
Specifies the timeout (in milliseconds) of socket connection operations when
the ``no_block`` option is enabled.
@@ -274,7 +256,7 @@ Available Options
executed in a "fire-and-forget" manner; no attempt to ensure the operation
has been received or acted on will be made once the client has executed it.
- .. caution::
+ .. warning::
Not all library operations are tested in this mode. Mixed TCP and UDP
servers are not allowed.
@@ -292,8 +274,8 @@ Available Options
.. _`User Datagram Protocol (UDP)`: https://en.wikipedia.org/wiki/User_Datagram_Protocol
.. _`no-delay`: https://en.wikipedia.org/wiki/TCP_NODELAY
.. _`keep-alive`: https://en.wikipedia.org/wiki/Keepalive
-.. _`Memcached PHP extension`: http://php.net/manual/en/book.memcached.php
-.. _`predefined constants`: http://php.net/manual/en/memcached.constants.php
+.. _`Memcached PHP extension`: https://www.php.net/manual/en/book.memcached.php
+.. _`predefined constants`: https://www.php.net/manual/en/memcached.constants.php
.. _`Memcached server`: https://memcached.org/
-.. _`Memcached`: http://php.net/manual/en/class.memcached.php
+.. _`Memcached`: https://www.php.net/manual/en/class.memcached.php
.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name
diff --git a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst b/components/cache/adapters/pdo_adapter.rst
similarity index 58%
rename from components/cache/adapters/pdo_doctrine_dbal_adapter.rst
rename to components/cache/adapters/pdo_adapter.rst
index cc8c43976c5..3cdeb87427a 100644
--- a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst
+++ b/components/cache/adapters/pdo_adapter.rst
@@ -1,22 +1,23 @@
-.. index::
- single: Cache Pool
- single: PDO Cache, Doctrine DBAL Cache
+PDO Cache Adapter
+=================
-.. _pdo-doctrine-adapter:
+The PDO adapters store the cache items in a table of an SQL database.
-PDO & Doctrine DBAL Cache Adapter
-=================================
+.. note::
+
+ This adapter implements :class:`Symfony\\Component\\Cache\\PruneableInterface`,
+ allowing for manual :ref:`pruning of expired cache entries `
+ by calling the ``prune()`` method.
-This adapter stores the cache items in an SQL database. It requires a `PDO`_,
-`Doctrine DBAL Connection`_, or `Data Source Name (DSN)`_ as its first parameter, and
-optionally a namespace, default cache lifetime, and options array as its second,
-third, and forth parameters::
+The :class:`Symfony\\Component\\Cache\\Adapter\\PdoAdapter` requires a :phpclass:`PDO`,
+or `DSN`_ as its first parameter. You can pass a namespace,
+default cache lifetime, and options array as the other optional arguments::
use Symfony\Component\Cache\Adapter\PdoAdapter;
$cache = new PdoAdapter(
- // a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO
+ // a PDO connection or DSN for lazy connecting through PDO
$databaseConnectionOrDSN,
// the string prefixed to the keys of the items stored in this cache
@@ -42,12 +43,5 @@ your code.
When passed a `Data Source Name (DSN)`_ string (instead of a database connection
class instance), the connection will be lazy-loaded when needed.
-.. note::
-
- Since Symfony 3.4, this adapter implements :class:`Symfony\\Component\\Cache\\PruneableInterface`,
- allowing for manual :ref:`pruning of expired cache entries ` by
- calling its ``prune()`` method.
-
-.. _`PDO`: http://php.net/manual/en/class.pdo.php
-.. _`Doctrine DBAL Connection`: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Connection.php
+.. _`DSN`: https://php.net/manual/pdo.drivers.php
.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name
diff --git a/components/cache/adapters/php_array_cache_adapter.rst b/components/cache/adapters/php_array_cache_adapter.rst
index 6fc5729705d..ae5ef13f790 100644
--- a/components/cache/adapters/php_array_cache_adapter.rst
+++ b/components/cache/adapters/php_array_cache_adapter.rst
@@ -1,13 +1,9 @@
-.. index::
- single: Cache Pool
- single: PHP Array Cache
-
-Php Array Cache Adapter
+PHP Array Cache Adapter
=======================
This adapter is a high performance cache for static data (e.g. application configuration)
that is optimized and preloaded into OPcache memory storage. It is suited for any data that
-is mostly read-only after warmup::
+is mostly read-only after warm-up::
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
@@ -23,7 +19,7 @@ is mostly read-only after warmup::
$cache = new PhpArrayAdapter(
// single file where values are cached
__DIR__ . '/somefile.cache',
- // a backup adapter, if you set values after warmup
+ // a backup adapter, if you set values after warm-up
new FilesystemAdapter()
);
$cache->warmUp($values);
diff --git a/components/cache/adapters/php_files_adapter.rst b/components/cache/adapters/php_files_adapter.rst
index c6e78cf52c0..6f171f0fede 100644
--- a/components/cache/adapters/php_files_adapter.rst
+++ b/components/cache/adapters/php_files_adapter.rst
@@ -1,13 +1,7 @@
-.. index::
- single: Cache Pool
- single: PHP Files Cache
-
-.. _component-cache-files-adapter:
-
-Php Files Cache Adapter
+PHP Files Cache Adapter
=======================
-Similarly to :ref:`Filesystem Adapter `, this cache
+Similarly to :doc:`Filesystem Adapter `, this cache
implementation writes cache entries out to disk, but unlike the Filesystem cache adapter,
the PHP Files cache adapter writes and reads back these cache files *as native PHP code*.
For example, caching the value ``['my', 'cached', 'array']`` will write out a cache
@@ -34,7 +28,7 @@ file similar to the following::
handles file includes, this adapter has the potential to be much faster than other
filesystem-based caches.
-.. caution::
+.. warning::
While it supports updates and because it is using OPcache as a backend, this adapter is
better suited for append-mostly needs. Using it in other scenarios might lead to
@@ -63,8 +57,8 @@ directory path as constructor arguments::
.. note::
- Since Symfony 3.4, this adapter implements :class:`Symfony\\Component\\Cache\\PruneableInterface`,
+ This adapter implements :class:`Symfony\\Component\\Cache\\PruneableInterface`,
allowing for manual :ref:`pruning of expired cache entries ` by
calling its ``prune()`` method.
-.. _`OPcache`: http://php.net/manual/en/book.opcache.php
+.. _`OPcache`: https://www.php.net/manual/en/book.opcache.php
diff --git a/components/cache/adapters/proxy_adapter.rst b/components/cache/adapters/proxy_adapter.rst
index 85d41d2c6d1..5177bf219df 100644
--- a/components/cache/adapters/proxy_adapter.rst
+++ b/components/cache/adapters/proxy_adapter.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Cache Pool
- single: Proxy Cache
-
Proxy Cache Adapter
===================
@@ -36,5 +32,5 @@ and optionally a namespace and default cache lifetime as its second and third pa
$defaultLifetime = 0
);
-.. _`PSR-6`: http://www.php-fig.org/psr/psr-6/
-.. _`cache item pool interface`: http://www.php-fig.org/psr/psr-6/#cacheitempoolinterface
+.. _`PSR-6`: https://www.php-fig.org/psr/psr-6/
+.. _`cache item pool interface`: https://www.php-fig.org/psr/psr-6/#cacheitempoolinterface
diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst
index 1cbccc4d749..c0295b487a0 100644
--- a/components/cache/adapters/redis_adapter.rst
+++ b/components/cache/adapters/redis_adapter.rst
@@ -1,9 +1,3 @@
-.. index::
- single: Cache Pool
- single: Redis Cache
-
-.. _redis-adapter:
-
Redis Cache Adapter
===================
@@ -14,20 +8,21 @@ Redis Cache Adapter
:ref:`Symfony Cache configuration `
article if you are using it in a Symfony application.
-This adapter stores the values in-memory using one (or more) `Redis server`_ instances.
+This adapter stores the values in-memory using one (or more) `Redis server`_
+of `Valkey`_ server instances.
-Unlike the :ref:`APCu adapter `, and similarly to the
-:ref:`Memcached adapter `, it is not limited to the current server's
+Unlike the :doc:`APCu adapter `, and similarly to the
+:doc:`Memcached adapter `, it is not limited to the current server's
shared memory; you can store contents independent of your PHP environment. The ability
to utilize a cluster of servers to provide redundancy and/or fail-over is also available.
-.. caution::
+.. warning::
**Requirements:** At least one `Redis server`_ must be installed and running to use this
adapter. Additionally, this adapter requires a compatible extension or library that implements
- ``\Redis``, ``\RedisArray``, ``RedisCluster``, or ``\Predis``.
+ ``\Redis``, ``\RedisArray``, ``RedisCluster``, ``\Relay\Relay``, ``\Relay\Cluster`` or ``\Predis``.
-This adapter expects a `Redis`_, `RedisArray`_, `RedisCluster`_, or `Predis`_ instance to be
+This adapter expects a `Redis`_, `RedisArray`_, `RedisCluster`_, `Relay`_, `RelayCluster`_ or `Predis`_ instance to be
passed as the first parameter. A namespace and default cache lifetime can optionally be passed
as the second and third parameters::
@@ -44,13 +39,23 @@ as the second and third parameters::
// the default lifetime (in seconds) for cache items that do not define their
// own lifetime, with a value 0 causing items to be stored indefinitely (i.e.
// until RedisAdapter::clear() is invoked or the server(s) are purged)
- $defaultLifetime = 0
+ $defaultLifetime = 0,
+
+ // $marshaller (optional) An instance of MarshallerInterface to control the serialization
+ // and deserialization of cache items. By default, native PHP serialization is used.
+ // This can be useful for compressing data, applying custom serialization logic, or
+ // optimizing the size and performance of cached items
+ ?MarshallerInterface $marshaller = null
);
+.. versionadded:: 7.3
+
+ Support for ``Relay\Cluster`` was introduced in Symfony 7.3.
+
Configure the Connection
------------------------
-The :method:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter::createConnection`
+The :method:`Symfony\\Component\\Cache\\Traits\\RedisTrait::createConnection`
helper method allows creating and configuring the Redis client class instance using a
`Data Source Name (DSN)`_::
@@ -61,16 +66,28 @@ helper method allows creating and configuring the Redis client class instance us
'redis://localhost'
);
+.. versionadded:: 7.3
+
+ Starting in Symfony 7.3, when using Valkey servers you can use the
+ ``valkey[s]:`` scheme instead of the ``redis[s]:`` one in your DSNs.
+
The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a
-password and a database index.
+password and a database index. To enable TLS for connections, the scheme ``redis`` must be
+replaced by ``rediss`` (the second ``s`` means "secure").
.. note::
- A `Data Source Name (DSN)`_ for this adapter must use the following format.
+ A `Data Source Name (DSN)`_ for this adapter must use either one of the following formats.
.. code-block:: text
- redis://[pass@][ip|host|socket[:port]][/db-index]
+ redis[s]://[pass@][ip|host|socket[:port]][/db-index]
+
+ .. code-block:: text
+
+ redis[s]:[[user]:pass@]?[ip|host|socket[:port]][¶ms]
+
+ Values for placeholders ``[user]``, ``[:port]``, ``[/db-index]`` and ``[¶ms]`` are optional.
Below are common examples of valid DSNs showing a combination of available values::
@@ -88,20 +105,35 @@ Below are common examples of valid DSNs showing a combination of available value
// socket "/var/run/redis.sock" and auth "bad-pass"
RedisAdapter::createConnection('redis://bad-pass@/var/run/redis.sock');
- // a single DSN can define multiple servers using the following syntax:
- // host[hostname-or-IP:port] (where port is optional). Sockets must include a trailing ':'
+ // host "redis1" (docker container) with alternate DSN syntax and selecting database index "3"
+ RedisAdapter::createConnection('redis:?host[redis1:6379]&dbindex=3');
+
+ // providing credentials with alternate DSN syntax
+ RedisAdapter::createConnection('redis:default:verysecurepassword@?host[redis1:6379]&dbindex=3');
+
+ // a single DSN can also define multiple servers
RedisAdapter::createConnection(
'redis:?host[localhost]&host[localhost:6379]&host[/var/run/redis.sock:]&auth=my-password&redis_cluster=1'
);
`Redis Sentinel`_, which provides high availability for Redis, is also supported
-when using the Predis library. Use the ``redis_sentinel`` parameter to set the
-name of your service group::
+when using the PHP Redis Extension v5.2+ or the Predis library. Use the ``redis_sentinel``
+parameter to set the name of your service group::
RedisAdapter::createConnection(
'redis:?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster'
);
+ // providing credentials
+ RedisAdapter::createConnection(
+ 'redis:default:verysecurepassword@?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster'
+ );
+
+ // providing credentials and selecting database index "3"
+ RedisAdapter::createConnection(
+ 'redis:default:verysecurepassword@?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster&dbindex=3'
+ );
+
.. note::
See the :class:`Symfony\\Component\\Cache\\Traits\\RedisTrait` for more options
@@ -123,14 +155,19 @@ array of ``key => value`` pairs representing option names and their respective v
// associative array of configuration options
[
- 'compression' => true,
- 'lazy' => false,
+ 'class' => null,
'persistent' => 0,
'persistent_id' => null,
- 'tcp_keepalive' => 0,
'timeout' => 30,
'read_timeout' => 0,
'retry_interval' => 0,
+ 'tcp_keepalive' => 0,
+ 'lazy' => null,
+ 'redis_cluster' => false,
+ 'redis_sentinel' => null,
+ 'dbindex' => 0,
+ 'failover' => 'none',
+ 'ssl' => null,
]
);
@@ -138,19 +175,11 @@ array of ``key => value`` pairs representing option names and their respective v
Available Options
~~~~~~~~~~~~~~~~~
-``class`` (type: ``string``)
- Specifies the connection library to return, either ``\Redis`` or ``\Predis\Client``.
- If none is specified, it will return ``\Redis`` if the ``redis`` extension is
- available, and ``\Predis\Client`` otherwise.
-
-``compression`` (type: ``bool``, default: ``true``)
- Enables or disables compression of items. This requires phpredis v4 or higher with
- LZF support enabled.
-
-``lazy`` (type: ``bool``, default: ``false``)
- Enables or disables lazy connections to the backend. It's ``false`` by
- default when using this as a stand-alone component and ``true`` by default
- when using it inside a Symfony application.
+``class`` (type: ``string``, default: ``null``)
+ Specifies the connection library to return, either ``\Redis``, ``\Relay\Relay`` or ``\Predis\Client``.
+ If none is specified, fallback value is in following order, depending which one is available first:
+ ``\Redis``, ``\Relay\Relay``, ``\Predis\Client``. Explicitly set this to ``\Predis\Client`` for Sentinel if you are
+ running into issues when retrieving master information.
``persistent`` (type: ``int``, default: ``0``)
Enables or disables use of persistent connections. A value of ``0`` disables persistent
@@ -159,6 +188,10 @@ Available Options
``persistent_id`` (type: ``string|null``, default: ``null``)
Specifies the persistent id string to use for a persistent connection.
+``timeout`` (type: ``int``, default: ``30``)
+ Specifies the time (in seconds) used to connect to a Redis server before the
+ connection attempt times out.
+
``read_timeout`` (type: ``int``, default: ``0``)
Specifies the time (in seconds) used when performing read operations on the underlying
network resource before the operation times out.
@@ -171,21 +204,192 @@ Available Options
Specifies the `TCP-keepalive`_ timeout (in seconds) of the connection. This
requires phpredis v4 or higher and a TCP-keepalive enabled server.
-``timeout`` (type: ``int``, default: ``30``)
- Specifies the time (in seconds) used to connect to a Redis server before the
- connection attempt times out.
+``lazy`` (type: ``bool``, default: ``null``)
+ Enables or disables lazy connections to the backend. It's ``false`` by
+ default when using this as a stand-alone component and ``true`` by default
+ when using it inside a Symfony application.
+
+``redis_cluster`` (type: ``bool``, default: ``false``)
+ Enables or disables redis cluster. The actual value passed is irrelevant as long as it passes loose comparison
+ checks: ``redis_cluster=1`` will suffice.
+
+``redis_sentinel`` (type: ``string``, default: ``null``)
+ Specifies the master name connected to the sentinels.
+
+``sentinel_master`` (type: ``string``, default: ``null``)
+ Alias of ``redis_sentinel`` option.
+
+``dbindex`` (type: ``int``, default: ``0``)
+ Specifies the database index to select.
+
+``failover`` (type: ``string``, default: ``none``)
+ Specifies failover for cluster implementations. For ``\RedisCluster`` valid options are ``none`` (default),
+ ``error``, ``distribute`` or ``slaves``. For ``\Predis\ClientInterface`` valid options are ``slaves``
+ or ``distribute``.
+
+``ssl`` (type: ``array``, default: ``null``)
+ SSL context options. See `php.net/context.ssl`_ for more information.
+
+``relay_cluster_context`` (type: ``array``, default: ``[]``)
+ Defines configuration options specific to ``\Relay\Cluster``. For example, to
+ user a self-signed certificate for testing in local environment::
+
+ $options = [
+ // ...
+ 'relay_cluster_context' => [
+ // ...
+ 'stream' => [
+ 'verify_peer' => false,
+ 'verify_peer_name' => false,
+ 'allow_self_signed' => true,
+ 'local_cert' => '/valkey.crt',
+ 'local_pk' => '/valkey.key',
+ 'cafile' => '/valkey.crt',
+ ],
+ ],
+ ];
+
+.. versionadded:: 7.1
+
+ The option ``sentinel_master`` as an alias for ``redis_sentinel`` was introduced
+ in Symfony 7.1.
+
+.. versionadded:: 7.3
+
+ The ``relay_cluster_context`` option was introduced in Symfony 7.3.
.. note::
When using the `Predis`_ library some additional Predis-specific options are available.
Reference the `Predis Connection Parameters`_ documentation for more information.
+.. _redis-tag-aware-adapter:
+
+Configuring Redis
+-----------------
+
+When using Redis as cache, you should configure the ``maxmemory`` and ``maxmemory-policy``
+settings. By setting ``maxmemory``, you limit how much memory Redis is allowed to consume.
+If the amount is too low, Redis will drop entries that would still be useful and you benefit
+less from your cache. Setting the ``maxmemory-policy`` to ``allkeys-lru`` tells Redis that
+it is ok to drop data when it runs out of memory, and to first drop the oldest entries (least
+recently used). If you do not allow Redis to drop entries, it will return an error when you
+try to add data when no memory is available. An example setting could look as follows:
+
+.. code-block:: ini
+
+ maxmemory 100mb
+ maxmemory-policy allkeys-lru
+
+Working with Tags
+-----------------
+
+In order to use tag-based invalidation, you can wrap your adapter in
+:class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapter`. However, when Redis
+is used as backend, it's often more interesting to use the dedicated
+:class:`Symfony\\Component\\Cache\\Adapter\\RedisTagAwareAdapter`. Since tag
+invalidation logic is implemented in Redis itself, this adapter offers better
+performance when using tag-based invalidation::
+
+ use Symfony\Component\Cache\Adapter\RedisAdapter;
+ use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter;
+
+ $client = RedisAdapter::createConnection('redis://localhost');
+ $cache = new RedisTagAwareAdapter($client);
+
+.. note::
+
+ When using RedisTagAwareAdapter, in order to maintain relationships between
+ tags and cache items, you have to use either ``noeviction`` or ``volatile-*``
+ in the Redis ``maxmemory-policy`` eviction policy.
+
+Read more about this topic in the official `Redis LRU Cache Documentation`_.
+
+Working with Marshaller
+-----------------------
+
+TagAwareMarshaller for Tag-Based Caching
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Optimizes caching for tag-based retrieval, allowing efficient management of related items::
+
+ $marshaller = new TagAwareMarshaller();
+
+ $cache = new RedisAdapter($redis, 'tagged_namespace', 3600, $marshaller);
+
+ $item = $cache->getItem('tagged_key');
+ $item->set(['value' => 'some_data', 'tags' => ['tag1', 'tag2']]);
+ $cache->save($item);
+
+SodiumMarshaller for Encrypted Caching
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Encrypts cached data using Sodium for enhanced security::
+
+ $encryptionKeys = [sodium_crypto_box_keypair()];
+ $marshaller = new SodiumMarshaller($encryptionKeys);
+
+ $cache = new RedisAdapter($redis, 'secure_namespace', 3600, $marshaller);
+
+ $item = $cache->getItem('secure_key');
+ $item->set('confidential_data');
+ $cache->save($item);
+
+DefaultMarshaller with igbinary Serialization
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Uses ``igbinary` for faster and more efficient serialization when available::
+
+ $marshaller = new DefaultMarshaller(true);
+
+ $cache = new RedisAdapter($redis, 'optimized_namespace', 3600, $marshaller);
+
+ $item = $cache->getItem('optimized_key');
+ $item->set(['data' => 'optimized_data']);
+ $cache->save($item);
+
+DefaultMarshaller with Exception on Failure
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Throws an exception if serialization fails, facilitating error handling::
+
+ $marshaller = new DefaultMarshaller(false, true);
+
+ $cache = new RedisAdapter($redis, 'error_namespace', 3600, $marshaller);
+
+ try {
+ $item = $cache->getItem('error_key');
+ $item->set('data');
+ $cache->save($item);
+ } catch (\ValueError $e) {
+ echo 'Serialization failed: '.$e->getMessage();
+ }
+
+SodiumMarshaller with Key Rotation
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Supports key rotation, ensuring secure decryption with both old and new keys::
+
+ $keys = [sodium_crypto_box_keypair(), sodium_crypto_box_keypair()];
+ $marshaller = new SodiumMarshaller($keys);
+
+ $cache = new RedisAdapter($redis, 'rotated_namespace', 3600, $marshaller);
+
+ $item = $cache->getItem('rotated_key');
+ $item->set('data_to_encrypt');
+ $cache->save($item);
+
.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name
.. _`Redis server`: https://redis.io/
+.. _`Valkey`: https://valkey.io/
.. _`Redis`: https://github.com/phpredis/phpredis
-.. _`RedisArray`: https://github.com/phpredis/phpredis/blob/master/arrays.markdown#readme
-.. _`RedisCluster`: https://github.com/phpredis/phpredis/blob/master/cluster.markdown#readme
+.. _`RedisArray`: https://github.com/phpredis/phpredis/blob/develop/arrays.md
+.. _`RedisCluster`: https://github.com/phpredis/phpredis/blob/develop/cluster.md
+.. _`Relay`: https://relay.so/
+.. _`RelayCluster`: https://relay.so/docs/1.x/connections#cluster
.. _`Predis`: https://packagist.org/packages/predis/predis
.. _`Predis Connection Parameters`: https://github.com/nrk/predis/wiki/Connection-Parameters#list-of-connection-parameters
.. _`TCP-keepalive`: https://redis.io/topics/clients#tcp-keepalive
.. _`Redis Sentinel`: https://redis.io/topics/sentinel
+.. _`Redis LRU Cache Documentation`: https://redis.io/topics/lru-cache
+.. _`php.net/context.ssl`: https://php.net/context.ssl
diff --git a/components/cache/cache_invalidation.rst b/components/cache/cache_invalidation.rst
index e56153b9ce1..da88ea6273e 100644
--- a/components/cache/cache_invalidation.rst
+++ b/components/cache/cache_invalidation.rst
@@ -1,13 +1,9 @@
-.. index::
- single: Cache; Invalidation
- single: Cache; Tags
-
Cache Invalidation
==================
Cache invalidation is the process of removing all cached items related to a
change in the state of your model. The most basic kind of invalidation is direct
-items deletion. But when the state of a primary resource has spread across
+item deletion. But when the state of a primary resource has spread across
several cached items, keeping them in sync can be difficult.
The Symfony Cache component provides two mechanisms to help solve this problem:
@@ -28,7 +24,7 @@ To attach tags to cached items, you need to use the
:method:`Symfony\\Contracts\\Cache\\ItemInterface::tag` method that is implemented by
cache items::
- $item = $cache->get('cache_key', function (ItemInterface $item) {
+ $item = $cache->get('cache_key', function (ItemInterface $item): string {
// [...]
// add one or more tags
$item->tag('tag_1');
@@ -47,7 +43,7 @@ you can invalidate the cached items by calling
// if you know the cache key, you can also delete the item directly
$cache->delete('cache_key');
-Using tags invalidation is very useful when tracking cache keys becomes difficult.
+Using tag invalidation is very useful when tracking cache keys becomes difficult.
Tag Aware Adapters
~~~~~~~~~~~~~~~~~~
@@ -58,6 +54,12 @@ To store tags, you need to wrap a cache adapter with the
:method:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapterInterface::invalidateTags`
method.
+.. note::
+
+ When using a Redis backend, consider using :ref:`RedisTagAwareAdapter `
+ which is optimized for this purpose. When using filesystem, likewise consider to use
+ :ref:`FilesystemTagAwareAdapter `.
+
The :class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapter` class implements
instantaneous invalidation (time complexity is ``O(N)`` where ``N`` is the number
of invalidated tags). It needs one or two cache adapters: the first required
@@ -81,7 +83,7 @@ your fronts and have very fast invalidation checks::
.. note::
- Since Symfony 3.4, :class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapter`
+ :class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapter`
implements :class:`Symfony\\Component\\Cache\\PruneableInterface`,
enabling manual
:ref:`pruning of expired cache entries ` by
diff --git a/components/cache/cache_items.rst b/components/cache/cache_items.rst
index 027bb59f4a9..e958125c69d 100644
--- a/components/cache/cache_items.rst
+++ b/components/cache/cache_items.rst
@@ -1,8 +1,3 @@
-.. index::
- single: Cache Item
- single: Cache Expiration
- single: Cache Exceptions
-
Cache Items
===========
@@ -17,9 +12,8 @@ Cache Item Keys and Values
The **key** of a cache item is a plain string which acts as its
identifier, so it must be unique for each cache pool. You can freely choose the
keys, but they should only contain letters (A-Z, a-z), numbers (0-9) and the
-``_`` and ``.`` symbols. Other common symbols (such as ``{``, ``}``, ``(``,
-``)``, ``/``, ``\``, ``@`` and ``:``) are reserved by the PSR-6 standard for future
-uses.
+``_`` and ``.`` symbols. Other common symbols (such as ``{ } ( ) / \ @ :``) are
+reserved by the PSR-6 standard for future uses.
The **value** of a cache item can be any data represented by a type which is
serializable by PHP, such as basic types (string, integer, float, boolean, null),
@@ -32,7 +26,7 @@ The only way to create cache items is via cache pools. When using the Cache
Contracts, they are passed as arguments to the recomputation callback::
// $cache pool object was created before
- $productsCount = $cache->get('stats.products_count', function (ItemInterface $item) {
+ $productsCount = $cache->get('stats.products_count', function (ItemInterface $item): string {
// [...]
});
diff --git a/components/cache/cache_pools.rst b/components/cache/cache_pools.rst
index 375b514fe80..e50c2b67633 100644
--- a/components/cache/cache_pools.rst
+++ b/components/cache/cache_pools.rst
@@ -1,14 +1,3 @@
-.. index::
- single: Cache Pool
- single: APCu Cache
- single: Array Cache
- single: Chain Cache
- single: Doctrine Cache
- single: Filesystem Cache
- single: Memcached Cache
- single: PDO Cache, Doctrine DBAL Cache
- single: Redis Cache
-
.. _component-cache-cache-pools:
Cache Pools and Supported Adapters
@@ -36,7 +25,6 @@ ready to use in your applications.
adapters/*
-
Using the Cache Contracts
-------------------------
@@ -49,7 +37,7 @@ and deleting cache items using only two methods and a callback::
$cache = new FilesystemAdapter();
// The callable will only be executed on a cache miss.
- $value = $cache->get('my_cache_key', function (ItemInterface $item) {
+ $value = $cache->get('my_cache_key', function (ItemInterface $item): string {
$item->expiresAfter(3600);
// ... do some HTTP request or heavy computations
@@ -174,7 +162,7 @@ when all items are successfully deleted)::
If the cache component is used inside a Symfony application, you can remove
items from cache pools using the following commands (which reside within
- the :ref:`framework bundle `):
+ the :doc:`framework bundle `):
To remove *one specific item* from the *given pool*:
@@ -203,7 +191,7 @@ Pruning Cache Items
-------------------
Some cache pools do not include an automated mechanism for pruning expired cache items.
-For example, the :ref:`FilesystemAdapter ` cache
+For example, the :doc:`FilesystemAdapter ` cache
does not remove expired cache items *until an item is explicitly requested and determined to
be expired*, for example, via a call to ``Psr\Cache\CacheItemPoolInterface::getItem``.
Under certain workloads, this can cause stale cache entries to persist well past their
@@ -213,10 +201,11 @@ expired cache items.
This shortcoming has been solved through the introduction of
:class:`Symfony\\Component\\Cache\\PruneableInterface`, which defines the abstract method
:method:`Symfony\\Component\\Cache\\PruneableInterface::prune`. The
-:ref:`ChainAdapter `,
-:ref:`FilesystemAdapter `,
-:ref:`PdoAdapter `, and
-:ref:`PhpFilesAdapter ` all implement this new interface,
+:doc:`ChainAdapter `,
+:doc:`DoctrineDbalAdapter `, and
+:doc:`FilesystemAdapter `,
+:doc:`PdoAdapter `, and
+:doc:`PhpFilesAdapter ` all implement this new interface,
allowing manual removal of stale cache items::
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
@@ -225,7 +214,7 @@ allowing manual removal of stale cache items::
// ... do some set and get operations
$cache->prune();
-The :ref:`ChainAdapter ` implementation does not directly
+The :doc:`ChainAdapter ` implementation does not directly
contain any pruning logic itself. Instead, when calling the chain adapter's
:method:`Symfony\\Component\\Cache\\Adapter\\ChainAdapter::prune` method, the call is delegated to all
its compatible cache adapters (and those that do not implement ``PruneableInterface`` are
@@ -253,7 +242,7 @@ silently ignored)::
If the cache component is used inside a Symfony application, you can prune
*all items* from *all pools* using the following command (which resides within
- the :ref:`framework bundle `):
+ the :doc:`framework bundle `):
.. code-block:: terminal
diff --git a/components/cache/psr6_psr16_adapters.rst b/components/cache/psr6_psr16_adapters.rst
index 275de9f1a57..66e44b9c22d 100644
--- a/components/cache/psr6_psr16_adapters.rst
+++ b/components/cache/psr6_psr16_adapters.rst
@@ -1,8 +1,3 @@
-.. index::
- single: Cache
- single: Performance
- single: Components; Cache
-
Adapters For Interoperability between PSR-6 and PSR-16 Cache
============================================================
@@ -83,4 +78,4 @@ this use-case::
// now use this wherever you want
$githubApiClient = new GitHubApiClient($psr16Cache);
-.. _`PSR-16`: http://www.php-fig.org/psr/psr-16/
+.. _`PSR-16`: https://www.php-fig.org/psr/psr-16/
diff --git a/components/class_loader.rst b/components/class_loader.rst
deleted file mode 100644
index f3268b1ca71..00000000000
--- a/components/class_loader.rst
+++ /dev/null
@@ -1,12 +0,0 @@
-.. index::
- single: Components; ClassLoader
-
-The ClassLoader Component
-=========================
-
-.. caution::
-
- The ClassLoader component was removed in Symfony 4.0. As an alternative, use
- any of the `class loading optimizations`_ provided by Composer.
-
-.. _`class loading optimizations`: https://getcomposer.org/doc/articles/autoloader-optimization.md
diff --git a/components/clock.rst b/components/clock.rst
new file mode 100644
index 00000000000..c4ac88e9092
--- /dev/null
+++ b/components/clock.rst
@@ -0,0 +1,380 @@
+The Clock Component
+===================
+
+The Clock component decouples applications from the system clock. This allows
+you to fix time to improve testability of time-sensitive logic.
+
+The component provides a ``ClockInterface`` with the following implementations
+for different use cases:
+
+:class:`Symfony\\Component\\Clock\\NativeClock`
+ Provides a way to interact with the system clock, this is the same as doing
+ ``new \DateTimeImmutable()``.
+:class:`Symfony\\Component\\Clock\\MockClock`
+ Commonly used in tests as a replacement for the ``NativeClock`` to be able
+ to freeze and change the current time using either ``sleep()`` or ``modify()``.
+:class:`Symfony\\Component\\Clock\\MonotonicClock`
+ Relies on ``hrtime()`` and provides a high resolution, monotonic clock,
+ when you need a precise stopwatch.
+
+Installation
+------------
+
+.. code-block:: terminal
+
+ $ composer require symfony/clock
+
+.. include:: /components/require_autoload.rst.inc
+
+.. _clock_usage:
+
+Usage
+-----
+
+The :class:`Symfony\\Component\\Clock\\Clock` class returns the current time and
+allows to use any `PSR-20`_ compatible implementation as a global clock in your
+application::
+
+ use Symfony\Component\Clock\Clock;
+ use Symfony\Component\Clock\MockClock;
+
+ // by default, Clock uses the NativeClock implementation, but you can change
+ // this by setting any other implementation
+ Clock::set(new MockClock());
+
+ // Then, you can get the clock instance
+ $clock = Clock::get();
+
+ // Additionally, you can set a timezone
+ $clock->withTimeZone('Europe/Paris');
+
+ // From here, you can get the current time
+ $now = $clock->now();
+
+ // And sleep for any number of seconds
+ $clock->sleep(2.5);
+
+The Clock component also provides the ``now()`` function::
+
+ use function Symfony\Component\Clock\now;
+
+ // Get the current time as a DatePoint instance
+ $now = now();
+
+The ``now()`` function takes an optional ``modifier`` argument
+which will be applied to the current time::
+
+ $later = now('+3 hours');
+
+ $yesterday = now('-1 day');
+
+You can use any string `accepted by the DateTime constructor`_.
+
+Later on this page you can learn how to use this clock in your services and tests.
+When using the Clock component, you manipulate
+:class:`Symfony\\Component\\Clock\\DatePoint` instances. You can learn more
+about it in :ref:`the dedicated section `.
+
+Available Clocks Implementations
+--------------------------------
+
+The Clock component provides some ready-to-use implementations of the
+:class:`Symfony\\Component\\Clock\\ClockInterface`, which you can use
+as global clocks in your application depending on your needs.
+
+NativeClock
+~~~~~~~~~~~
+
+A clock service replaces creating a new ``DateTime`` or
+``DateTimeImmutable`` object for the current time. Instead, you inject the
+``ClockInterface`` and call ``now()``. By default, your application will likely
+use a ``NativeClock``, which always returns the current system time. In tests it is replaced with a ``MockClock``.
+
+The following example introduces a service utilizing the Clock component to
+determine the current time::
+
+ use Symfony\Component\Clock\ClockInterface;
+
+ class ExpirationChecker
+ {
+ public function __construct(
+ private ClockInterface $clock
+ ) {}
+
+ public function isExpired(DateTimeInterface $validUntil): bool
+ {
+ return $this->clock->now() > $validUntil;
+ }
+ }
+
+MockClock
+~~~~~~~~~
+
+The ``MockClock`` is instantiated with a time and does not move forward on its own. The time is
+fixed until ``sleep()`` or ``modify()`` are called. This gives you full control over what your code
+assumes is the current time.
+
+When writing a test for this service, you can check both cases where something
+is expired or not, by modifying the clock's time::
+
+ use PHPUnit\Framework\TestCase;
+ use Symfony\Component\Clock\MockClock;
+
+ class ExpirationCheckerTest extends TestCase
+ {
+ public function testIsExpired(): void
+ {
+ $clock = new MockClock('2022-11-16 15:20:00');
+ $expirationChecker = new ExpirationChecker($clock);
+ $validUntil = new DateTimeImmutable('2022-11-16 15:25:00');
+
+ // $validUntil is in the future, so it is not expired
+ $this->assertFalse($expirationChecker->isExpired($validUntil));
+
+ // Clock sleeps for 10 minutes, so now is '2022-11-16 15:30:00'
+ $clock->sleep(600); // Instantly changes time as if we waited for 10 minutes (600 seconds)
+
+ // modify the clock, accepts all formats supported by DateTimeImmutable::modify()
+ $this->assertTrue($expirationChecker->isExpired($validUntil));
+
+ $clock->modify('2022-11-16 15:00:00');
+
+ // $validUntil is in the future again, so it is no longer expired
+ $this->assertFalse($expirationChecker->isExpired($validUntil));
+ }
+ }
+
+Monotonic Clock
+~~~~~~~~~~~~~~~
+
+The ``MonotonicClock`` allows you to implement a precise stopwatch; depending on
+the system up to nanosecond precision. It can be used to measure the elapsed
+time between two calls without being affected by inconsistencies sometimes introduced
+by the system clock, e.g. by updating it. Instead, it consistently increases time,
+making it especially useful for measuring performance.
+
+.. _clock_use-inside-a-service:
+
+Using a Clock inside a Service
+------------------------------
+
+Using the Clock component in your services to retrieve the current time makes
+them easier to test. For example, by using the ``MockClock`` implementation as
+the default one during tests, you will have full control to set the "current time"
+to any arbitrary date/time.
+
+In order to use this component in your services, make their classes use the
+:class:`Symfony\\Component\\Clock\\ClockAwareTrait`. Thanks to
+:ref:`service autoconfiguration `, the ``setClock()`` method
+of the trait will automatically be called by the service container.
+
+You can now call the ``$this->now()`` method to get the current time::
+
+ namespace App\TimeUtils;
+
+ use Symfony\Component\Clock\ClockAwareTrait;
+
+ class MonthSensitive
+ {
+ use ClockAwareTrait;
+
+ public function isWinterMonth(): bool
+ {
+ $now = $this->now();
+
+ return match ($now->format('F')) {
+ 'December', 'January', 'February', 'March' => true,
+ default => false,
+ };
+ }
+ }
+
+Thanks to the ``ClockAwareTrait``, and by using the ``MockClock`` implementation,
+you can set the current time arbitrarily without having to change your service code.
+This will help you test every case of your method without the need of actually
+being in a month or another.
+
+.. _clock_date-point:
+
+The ``DatePoint`` Class
+-----------------------
+
+The Clock component uses a special :class:`Symfony\\Component\\Clock\\DatePoint`
+class. This is a small wrapper on top of PHP's :phpclass:`DateTimeImmutable`.
+You can use it seamlessly everywhere a :phpclass:`DateTimeImmutable` or
+:phpclass:`DateTimeInterface` is expected. The ``DatePoint`` object fetches the
+date and time from the :class:`Symfony\\Component\\Clock\\Clock` class. This means
+that if you did any changes to the clock as stated in the
+:ref:`usage section `, it will be reflected when creating a new
+``DatePoint``. You can also create a new ``DatePoint`` instance directly, for
+instance when using it as a default value::
+
+ use Symfony\Component\Clock\DatePoint;
+
+ class Post
+ {
+ public function __construct(
+ // ...
+ private \DateTimeImmutable $createdAt = new DatePoint(),
+ ) {
+ }
+ }
+
+The constructor also allows setting a timezone or custom referenced date::
+
+ // you can specify a timezone
+ $withTimezone = new DatePoint(timezone: new \DateTimezone('UTC'));
+
+ // you can also create a DatePoint from a reference date
+ $referenceDate = new \DateTimeImmutable();
+ $relativeDate = new DatePoint('+1month', reference: $referenceDate);
+
+The ``DatePoint`` class also provides a named constructor to create dates from
+timestamps::
+
+ $dateOfFirstCommitToSymfonyProject = DatePoint::createFromTimestamp(1129645656);
+ // equivalent to:
+ // $dateOfFirstCommitToSymfonyProject = (new \DateTimeImmutable())->setTimestamp(1129645656);
+
+ // negative timestamps (for dates before January 1, 1970) and float timestamps
+ // (for high precision sub-second datetimes) are also supported
+ $dateOfFirstMoonLanding = DatePoint::createFromTimestamp(-14182940);
+
+.. versionadded:: 7.1
+
+ The ``createFromTimestamp()`` method was introduced in Symfony 7.1.
+
+.. note::
+
+ In addition ``DatePoint`` offers stricter return types and provides consistent
+ error handling across versions of PHP, thanks to polyfilling `PHP 8.3's behavior`_
+ on the topic.
+
+``DatePoint`` also allows to set and get the microsecond part of the date and time::
+
+ $datePoint = new DatePoint();
+ $datePoint->setMicrosecond(345);
+ $microseconds = $datePoint->getMicrosecond();
+
+.. note::
+
+ This feature polyfills PHP 8.4's behavior on the topic, as microseconds manipulation
+ is not available in previous versions of PHP.
+
+.. versionadded:: 7.1
+
+ The :method:`Symfony\\Component\\Clock\\DatePoint::setMicrosecond` and
+ :method:`Symfony\\Component\\Clock\\DatePoint::getMicrosecond` methods were
+ introduced in Symfony 7.1.
+
+Storing DatePoints in the Database
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you :doc:`use Doctrine ` to work with databases, consider using the
+``date_point`` Doctrine type, which converts to/from ``DatePoint`` objects automatically::
+
+ // src/Entity/Product.php
+ namespace App\Entity;
+
+ use Doctrine\ORM\Mapping as ORM;
+ use Symfony\Component\Clock\DatePoint;
+
+ #[ORM\Entity]
+ class Product
+ {
+ // if you don't define the Doctrine type explicitly, Symfony will autodetect it:
+ #[ORM\Column]
+ private DatePoint $createdAt;
+
+ // if you prefer to define the Doctrine type explicitly:
+ #[ORM\Column(type: 'date_point')]
+ private DatePoint $updatedAt;
+
+ // ...
+ }
+
+.. versionadded:: 7.3
+
+ The ``DatePointType`` was introduced in Symfony 7.3.
+
+.. _clock_writing-tests:
+
+Writing Time-Sensitive Tests
+----------------------------
+
+The Clock component provides another trait, called :class:`Symfony\\Component\\Clock\\Test\\ClockSensitiveTrait`,
+to help you write time-sensitive tests. This trait provides methods to freeze
+time and restore the global clock after each test.
+
+Use the ``ClockSensitiveTrait::mockTime()`` method to interact with the mocked
+clock in your tests. This method accepts different types as its only argument:
+
+* A string, which can be a date to set the clock at (e.g. ``1996-07-01``) or an
+ interval to modify the clock (e.g. ``+2 days``);
+* A ``DateTimeImmutable`` to set the clock at;
+* A boolean, to freeze or restore the global clock.
+
+Let's say you want to test the method ``MonthSensitive::isWinterMonth()`` of the
+above example. This is how you can write that test::
+
+ namespace App\Tests\TimeUtils;
+
+ use App\TimeUtils\MonthSensitive;
+ use PHPUnit\Framework\TestCase;
+ use Symfony\Component\Clock\Test\ClockSensitiveTrait;
+
+ class MonthSensitiveTest extends TestCase
+ {
+ use ClockSensitiveTrait;
+
+ public function testIsWinterMonth(): void
+ {
+ $clock = static::mockTime(new \DateTimeImmutable('2022-03-02'));
+
+ $monthSensitive = new MonthSensitive();
+ $monthSensitive->setClock($clock);
+
+ $this->assertTrue($monthSensitive->isWinterMonth());
+ }
+
+ public function testIsNotWinterMonth(): void
+ {
+ $clock = static::mockTime(new \DateTimeImmutable('2023-06-02'));
+
+ $monthSensitive = new MonthSensitive();
+ $monthSensitive->setClock($clock);
+
+ $this->assertFalse($monthSensitive->isWinterMonth());
+ }
+ }
+
+This test will behave the same no matter which time of the year you run it.
+By combining the :class:`Symfony\\Component\\Clock\\ClockAwareTrait` and
+:class:`Symfony\\Component\\Clock\\Test\\ClockSensitiveTrait`, you have full
+control on your time-sensitive code's behavior.
+
+Exceptions Management
+---------------------
+
+The Clock component takes full advantage of some `PHP DateTime exceptions`_.
+If you pass an invalid string to the clock (e.g. when creating a clock or
+modifying a ``MockClock``) you'll get a ``DateMalformedStringException``. If you
+pass an invalid timezone, you'll get a ``DateInvalidTimeZoneException``::
+
+ $userInput = 'invalid timezone';
+
+ try {
+ $clock = Clock::get()->withTimeZone($userInput);
+ } catch (\DateInvalidTimeZoneException $exception) {
+ // ...
+ }
+
+These exceptions are available starting from PHP 8.3. However, thanks to the
+`symfony/polyfill-php83`_ dependency required by the Clock component, you can
+use them even if your project doesn't use PHP 8.3 yet.
+
+.. _`PSR-20`: https://www.php-fig.org/psr/psr-20/
+.. _`accepted by the DateTime constructor`: https://www.php.net/manual/en/datetime.formats.php
+.. _`PHP DateTime exceptions`: https://wiki.php.net/rfc/datetime-exceptions
+.. _`symfony/polyfill-php83`: https://github.com/symfony/polyfill-php83
+.. _`PHP 8.3's behavior`: https://wiki.php.net/rfc/datetime-exceptions
diff --git a/components/config.rst b/components/config.rst
index 7de46a6c6b7..9de03f1f869 100644
--- a/components/config.rst
+++ b/components/config.rst
@@ -1,13 +1,17 @@
-.. index::
- single: Config
- single: Components; Config
-
The Config Component
====================
- The Config component provides several classes to help you find, load,
- combine, fill and validate configuration values of any kind, whatever
- their source may be (YAML, XML, INI files, or for instance a database).
+The Config component provides utilities to define and manage the configuration
+options of PHP applications. It allows you to:
+
+* Define a configuration structure, its validation rules, default values and documentation;
+* Support different configuration formats (YAML, XML, INI, etc.);
+* Merge multiple configurations from different sources into a single configuration.
+
+.. note::
+
+ You don't have to use this component to configure Symfony applications.
+ Instead, read the docs about :doc:`how to configure Symfony applications `.
Installation
------------
diff --git a/components/config/caching.rst b/components/config/caching.rst
index 833492dd45e..80e23a4fdfb 100644
--- a/components/config/caching.rst
+++ b/components/config/caching.rst
@@ -1,12 +1,9 @@
-.. index::
- single: Config; Caching based on resources
-
Caching based on Resources
==========================
When all configuration resources are loaded, you may want to process the
configuration values and combine them all in one file. This file acts
-like a cache. Its contents don’t have to be regenerated every time the
+like a cache. Its contents don't have to be regenerated every time the
application runs – only when the configuration resources are modified.
For example, the Symfony Routing component allows you to load all routes,
@@ -58,3 +55,17 @@ the cache file itself. This ``.meta`` file contains the serialized resources,
whose timestamps are used to determine if the cache is still fresh. When
not in debug mode, the cache is considered to be "fresh" as soon as it exists,
and therefore no ``.meta`` file will be generated.
+
+You can explicitly define the absolute path to the meta file::
+
+ use Symfony\Component\Config\ConfigCache;
+ use Symfony\Component\Config\Resource\FileResource;
+
+ $cachePath = __DIR__.'/cache/appUserMatcher.php';
+
+ // the third optional argument indicates the absolute path to the meta file
+ $userMatcherCache = new ConfigCache($cachePath, true, '/my/absolute/path/to/cache.meta');
+
+.. versionadded:: 7.1
+
+ The argument to customize the meta file path was introduced in Symfony 7.1.
diff --git a/components/config/definition.rst b/components/config/definition.rst
index ba668cd8613..4848af33ffe 100644
--- a/components/config/definition.rst
+++ b/components/config/definition.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Config; Defining and processing configuration values
-
Defining and Processing Configuration Values
============================================
@@ -57,7 +54,7 @@ implements the :class:`Symfony\\Component\\Config\\Definition\\ConfigurationInte
class DatabaseConfiguration implements ConfigurationInterface
{
- public function getConfigTreeBuilder()
+ public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('database');
@@ -84,11 +81,21 @@ reflect the real structure of the configuration values::
->defaultTrue()
->end()
->scalarNode('default_connection')
- ->defaultValue('default')
+ ->defaultValue('mysql')
+ ->end()
+ ->stringNode('username')
+ ->defaultValue('root')
+ ->end()
+ ->stringNode('password')
+ ->defaultValue('root')
->end()
->end()
;
+.. versionadded:: 7.2
+
+ The ``stringNode()`` method was introduced in Symfony 7.2.
+
The root node itself is an array node, and has children, like the boolean
node ``auto_connect`` and the scalar node ``default_connection``. In general:
after defining a node, a call to ``end()`` takes you one step up in the
@@ -103,6 +110,7 @@ node definition. Node types are available for:
* scalar (generic type that includes booleans, strings, integers, floats
and ``null``)
* boolean
+* string
* integer
* float
* enum (similar to scalar, but it only allows a finite set of values)
@@ -112,6 +120,10 @@ node definition. Node types are available for:
and are created with ``node($name, $type)`` or their associated shortcut
``xxxxNode($name)`` method.
+.. versionadded:: 7.2
+
+ Support for the ``string`` type was introduced in Symfony 7.2.
+
Numeric Node Constraints
~~~~~~~~~~~~~~~~~~~~~~~~
@@ -151,11 +163,53 @@ values::
This will restrict the ``delivery`` options to be either ``standard``,
``expedited`` or ``priority``.
+You can also provide enum values to ``enumNode()``. Let's define an enumeration
+describing the possible states of the example above::
+
+ enum Delivery: string
+ {
+ case Standard = 'standard';
+ case Expedited = 'expedited';
+ case Priority = 'priority';
+ }
+
+The configuration can now be written like this::
+
+ $rootNode
+ ->children()
+ ->enumNode('delivery')
+ // You can provide all values of the enum...
+ ->values(Delivery::cases())
+ // ... or you can pass only some values next to other scalar values
+ ->values([Delivery::Priority, Delivery::Standard, 'other', false])
+ ->end()
+ ->end()
+ ;
+
+You can also use the ``enumClass()`` method to pass the FQCN of an enum
+class to the node. This will automatically set the values of the node to
+the cases of the enum::
+
+ $rootNode
+ ->children()
+ ->enumNode('delivery')
+ ->enumClass(Delivery::class)
+ ->end()
+ ->end()
+ ;
+
+When using a backed enum, the values provided to the node will be cast
+to one of the enum cases if possible.
+
+.. versionadded:: 7.3
+
+ The ``enumClass()`` method was introduced in Symfony 7.3.
+
Array Nodes
~~~~~~~~~~~
It is possible to add a deeper level to the hierarchy, by adding an array
-node. The array node itself, may have a pre-defined set of variable nodes::
+node. The array node itself, may have a predefined set of variable nodes::
$rootNode
->children()
@@ -193,7 +247,7 @@ above, it is possible to have multiple connection arrays (containing a ``driver`
``host``, etc.).
Sometimes, to improve the user experience of your application or bundle, you may
-allow to use a simple string or numeric value where an array value is required.
+allow the use of a simple string or numeric value where an array value is required.
Use the ``castToArray()`` helper to turn those variables into arrays::
->arrayNode('hosts')
@@ -346,6 +400,13 @@ In order to maintain the array keys use the ``useAttributeAsKey()`` method::
->end()
;
+.. note::
+
+ In YAML, the ``'name'`` argument of ``useAttributeAsKey()`` has a special
+ meaning and refers to the key of the map (``sf_connection`` and ``default``
+ in this example). If a child node was defined for the ``connections`` node
+ with the key ``name``, then that key of the map would be lost.
+
The argument of this method (``name`` in the example above) defines the name of
the attribute added to each XML node to differentiate them. Now you can use the
same YAML configuration shown before or the following XML configuration:
@@ -436,11 +497,15 @@ method::
->children()
->integerNode('old_option')
// this outputs the following generic deprecation message:
- // The child node "old_option" at path "..." is deprecated.
- ->setDeprecated()
+ // Since acme/package 1.2: The child node "old_option" at path "..." is deprecated.
+ ->setDeprecated('acme/package', '1.2')
// you can also pass a custom deprecation message (%node% and %path% placeholders are available):
- ->setDeprecated('The "%node%" option is deprecated. Use "new_config_option" instead.')
+ ->setDeprecated(
+ 'acme/package',
+ '1.2',
+ 'The "%node%" option is deprecated. Use "new_config_option" instead.'
+ )
->end()
->end()
;
@@ -481,6 +546,30 @@ and in XML:
+You can also provide a URL to a full documentation page::
+
+ $rootNode
+ ->docUrl('Full documentation is available at https://example.com/docs/{version:major}.{version:minor}/reference.html')
+ ->children()
+ ->integerNode('entries_per_page')
+ ->defaultValue(25)
+ ->end()
+ ->end()
+ ;
+
+A few placeholders are available to customize the URL:
+
+* ``{version:major}``: The major version of the package currently installed
+* ``{version:minor}``: The minor version of the package currently installed
+* ``{package}``: The name of the package
+
+The placeholders will be replaced when printing the configuration tree with the
+``config:dump-reference`` command.
+
+.. versionadded:: 7.3
+
+ The ``docUrl()`` method was introduced in Symfony 7.3.
+
Optional Sections
-----------------
@@ -532,7 +621,9 @@ be large and you may want to split it up into sections. You can do this
by making a section a separate node and then appending it into the main
tree with ``append()``::
- public function getConfigTreeBuilder()
+ use Symfony\Component\Config\Definition\Builder\NodeDefinition;
+
+ public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('database');
@@ -561,7 +652,7 @@ tree with ``append()``::
return $treeBuilder;
}
- public function addParametersNode()
+ public function addParametersNode(): NodeDefinition
{
$treeBuilder = new TreeBuilder('parameters');
@@ -637,7 +728,7 @@ The separator used in keys is typically ``_`` in YAML and ``-`` in XML.
For example, ``auto_connect`` in YAML and ``auto-connect`` in XML. The
normalization would make both of these ``auto_connect``.
-.. caution::
+.. warning::
The target key will not be altered if it's mixed like
``foo-bar_moo`` or if it already exists.
@@ -729,10 +820,10 @@ By changing a string value into an associative array with ``name`` as the key::
->arrayNode('connection')
->beforeNormalization()
->ifString()
- ->then(function ($v) { return ['name' => $v]; })
+ ->then(function (string $v): array { return ['name' => $v]; })
->end()
->children()
- ->scalarNode('name')->isRequired()
+ ->scalarNode('name')->isRequired()->end()
// ...
->end()
->end()
@@ -767,9 +858,10 @@ A validation rule always has an "if" part. You can specify this part in
the following ways:
- ``ifTrue()``
+- ``ifFalse()``
- ``ifString()``
- ``ifNull()``
-- ``ifEmpty()`` (since Symfony 3.2)
+- ``ifEmpty()``
- ``ifArray()``
- ``ifInArray()``
- ``ifNotInArray()``
@@ -785,6 +877,10 @@ A validation rule also requires a "then" part:
Usually, "then" is a closure. Its return value will be used as a new value
for the node, instead of the node's original value.
+.. versionadded:: 7.3
+
+ The ``ifFalse()`` method was introduced in Symfony 7.3.
+
Configuring the Node Path Separator
-----------------------------------
@@ -809,7 +905,8 @@ character (``.``)::
$node = $treeBuilder->buildTree();
$children = $node->getChildren();
- $path = $children['driver']->getPath();
+ $childChildren = $children['connection']->getChildren();
+ $path = $childChildren['driver']->getPath();
// $path = 'database.connection.driver'
Use the ``setPathSeparator()`` method on the config builder to change the path
@@ -820,7 +917,8 @@ separator::
$treeBuilder->setPathSeparator('/');
$node = $treeBuilder->buildTree();
$children = $node->getChildren();
- $path = $children['driver']->getPath();
+ $childChildren = $children['connection']->getChildren();
+ $path = $childChildren['driver']->getPath();
// $path = 'database/connection/driver'
Processing Configuration Values
@@ -853,3 +951,8 @@ Otherwise the result is a clean array of configuration values::
$databaseConfiguration,
$configs
);
+
+.. warning::
+
+ When processing the configuration tree, the processor assumes that the top
+ level array key (which matches the extension name) is already stripped off.
diff --git a/components/config/resources.rst b/components/config/resources.rst
index 3ee380a9828..f9b0fda61ae 100644
--- a/components/config/resources.rst
+++ b/components/config/resources.rst
@@ -1,17 +1,11 @@
-.. index::
- single: Config; Loading resources
-
Loading Resources
=================
-.. caution::
-
- The ``IniFileLoader`` parses the file contents using the
- :phpfunction:`parse_ini_file` function. Therefore, you can only set
- parameters to string values. To set parameters to other data types
- (e.g. boolean, integer, etc), the other loaders are recommended.
-
-Loaders populate the application's configuration from different sources like YAML files. The Config component defines the interface for such loaders. The :doc:`Dependency Injection ` and :doc:`Routing ` components come with specialized loaders for different file formats.
+Loaders populate the application's configuration from different sources
+like YAML files. The Config component defines the interface for such
+loaders. The :doc:`Dependency Injection `
+and `Routing`_ components come with specialized loaders for different file
+formats.
Locating Resources
------------------
@@ -36,7 +30,7 @@ an array containing all matches.
Resource Loaders
----------------
-For each type of resource (YAML, XML, annotation, etc.) a loader must be
+For each type of resource (YAML, XML, attributes, etc.) a loader must be
defined. Each loader should implement
:class:`Symfony\\Component\\Config\\Loader\\LoaderInterface` or extend the
abstract :class:`Symfony\\Component\\Config\\Loader\\FileLoader` class,
@@ -49,7 +43,7 @@ which allows for recursively importing other resources::
class YamlUserLoader extends FileLoader
{
- public function load($resource, $type = null)
+ public function load($resource, $type = null): void
{
$configValues = Yaml::parse(file_get_contents($resource));
@@ -60,7 +54,7 @@ which allows for recursively importing other resources::
// $this->import('extra_users.yaml');
}
- public function supports($resource, $type = null)
+ public function supports($resource, $type = null): bool
{
return is_string($resource) && 'yaml' === pathinfo(
$resource,
@@ -95,3 +89,5 @@ the resource::
// YamlUserLoader is used to load this resource because it supports
// files with the '.yaml' extension
$delegatingLoader->load(__DIR__.'/users.yaml');
+
+.. _Routing: https://github.com/symfony/routing
diff --git a/components/console.rst b/components/console.rst
index 6a2abe2366e..14817240206 100644
--- a/components/console.rst
+++ b/components/console.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Console; CLI
- single: Components; Console
-
The Console Component
=====================
@@ -52,6 +48,20 @@ Then, you can register the commands using
// ...
$application->add(new GenerateAdminCommand());
+You can also register inline commands and define their behavior thanks to the
+``Command::setCode()`` method::
+
+ // ...
+ $application->register('generate-admin')
+ ->addArgument('username', InputArgument::REQUIRED)
+ ->setCode(function (InputInterface $input, OutputInterface $output): int {
+ // ...
+
+ return Command::SUCCESS;
+ });
+
+This is useful when creating a :doc:`single-command application `.
+
See the :doc:`/console` article for information about how to create commands.
Learn more
@@ -63,5 +73,4 @@ Learn more
/console
/components/console/*
- /components/console/helpers/index
/console/*
diff --git a/components/console/changing_default_command.rst b/components/console/changing_default_command.rst
index 6eb9f2b5227..c69995ea395 100644
--- a/components/console/changing_default_command.rst
+++ b/components/console/changing_default_command.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Console; Changing the Default Command
-
Changing the Default Command
============================
@@ -10,22 +7,24 @@ name to the ``setDefaultCommand()`` method::
namespace Acme\Console\Command;
+ use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
+ #[AsCommand(name: 'hello:world')]
class HelloWorldCommand extends Command
{
- protected static $defaultName = 'hello:world';
-
- protected function configure()
+ protected function configure(): void
{
$this->setDescription('Outputs "Hello World"');
}
- protected function execute(InputInterface $input, OutputInterface $output)
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('Hello World');
+
+ return Command::SUCCESS;
}
}
@@ -53,7 +52,7 @@ This will print the following to the command line:
Hello World
-.. caution::
+.. warning::
This feature has a limitation: you cannot pass any argument or option to
the default command because they are ignored.
diff --git a/components/console/console_arguments.rst b/components/console/console_arguments.rst
index 79f5c6c1f4c..da538ac78f1 100644
--- a/components/console/console_arguments.rst
+++ b/components/console/console_arguments.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Console; Console arguments
-
Understanding how Console Arguments and Options Are Handled
===========================================================
@@ -14,6 +11,7 @@ Have a look at the following command that has three options::
namespace Acme\Console\Command;
+ use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
@@ -21,14 +19,12 @@ Have a look at the following command that has three options::
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
+ #[AsCommand(name: 'demo:args', description: 'Describe args behaviors')]
class DemoArgsCommand extends Command
{
- protected static $defaultName = 'demo:args';
-
- protected function configure()
+ protected function configure(): void
{
$this
- ->setDescription('Describe args behaviors')
->setDefinition(
new InputDefinition([
new InputOption('foo', 'f'),
@@ -38,7 +34,7 @@ Have a look at the following command that has three options::
);
}
- protected function execute(InputInterface $input, OutputInterface $output)
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
// ...
}
diff --git a/components/console/events.rst b/components/console/events.rst
index 93f6d1a3791..e550025b7dd 100644
--- a/components/console/events.rst
+++ b/components/console/events.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Console; Events
-
Using Events
============
@@ -17,10 +14,11 @@ the wheel, it uses the Symfony EventDispatcher component to do the work::
$application->setDispatcher($dispatcher);
$application->run();
-.. caution::
+.. warning::
Console events are only triggered by the main command being executed.
- Commands called by the main command will not trigger any event.
+ Commands called by the main command will not trigger any event, unless
+ run by the application itself, see :doc:`/console/calling_commands`.
The ``ConsoleEvents::COMMAND`` Event
------------------------------------
@@ -36,7 +34,7 @@ dispatched. Listeners receive a
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
- $dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
+ $dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event): void {
// gets the input instance
$input = $event->getInput();
@@ -67,7 +65,7 @@ C/C++ standard::
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
- $dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
+ $dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event): void {
// gets the command to be executed
$command = $event->getCommand();
@@ -100,14 +98,14 @@ Listeners receive a
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
- $dispatcher->addListener(ConsoleEvents::ERROR, function (ConsoleErrorEvent $event) {
+ $dispatcher->addListener(ConsoleEvents::ERROR, function (ConsoleErrorEvent $event): void {
$output = $event->getOutput();
$command = $event->getCommand();
$output->writeln(sprintf('Oops, exception thrown while running command %s ', $command->getName()));
- // gets the current exit code (the exception code or the exit code set by a ConsoleEvents::TERMINATE event)
+ // gets the current exit code (the exception code)
$exitCode = $event->getExitCode();
// changes the exception to another one
@@ -134,7 +132,7 @@ Listeners receive a
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
- $dispatcher->addListener(ConsoleEvents::TERMINATE, function (ConsoleTerminateEvent $event) {
+ $dispatcher->addListener(ConsoleEvents::TERMINATE, function (ConsoleTerminateEvent $event): void {
// gets the output
$output = $event->getOutput();
@@ -154,4 +152,107 @@ Listeners receive a
It is then dispatched just after the ``ConsoleEvents::ERROR`` event.
The exit code received in this case is the exception code.
+ Additionally, the event is dispatched when the command is being exited on
+ a signal. You can learn more about signals in the
+ :ref:`the dedicated section `.
+
+.. _console-events_signal:
+
+The ``ConsoleEvents::SIGNAL`` Event
+-----------------------------------
+
+**Typical Purposes**: To perform some actions after the command execution was interrupted.
+
+`Signals`_ are asynchronous notifications sent to a process in order to notify
+it of an event that occurred. For example, when you press ``Ctrl + C`` in a
+command, the operating system sends the ``SIGINT`` signal to it.
+
+When a command is interrupted, Symfony dispatches the ``ConsoleEvents::SIGNAL``
+event. Listen to this event so you can perform some actions (e.g. logging some
+results, cleaning some temporary files, etc.) before finishing the command execution.
+
+Listeners receive a
+:class:`Symfony\\Component\\Console\\Event\\ConsoleSignalEvent` event::
+
+ use Symfony\Component\Console\ConsoleEvents;
+ use Symfony\Component\Console\Event\ConsoleSignalEvent;
+
+ $dispatcher->addListener(ConsoleEvents::SIGNAL, function (ConsoleSignalEvent $event): void {
+
+ // gets the signal number
+ $signal = $event->getHandlingSignal();
+
+ // sets the exit code
+ $event->setExitCode(0);
+
+ if (\SIGINT === $signal) {
+ echo "bye bye!";
+ }
+ });
+
+It is also possible to abort the exit if you want the command to continue its
+execution even after the event has been dispatched, thanks to the
+:method:`Symfony\\Component\\Console\\Event\\ConsoleSignalEvent::abortExit`
+method::
+
+ use Symfony\Component\Console\ConsoleEvents;
+ use Symfony\Component\Console\Event\ConsoleSignalEvent;
+
+ $dispatcher->addListener(ConsoleEvents::SIGNAL, function (ConsoleSignalEvent $event) {
+ $event->abortExit();
+ });
+
+.. tip::
+
+ All the available signals (``SIGINT``, ``SIGQUIT``, etc.) are defined as
+ `constants of the PCNTL PHP extension`_. The extension has to be installed
+ for these constants to be available.
+
+If you use the Console component inside a Symfony application, commands can
+handle signals themselves. To do so, implement the
+:class:`Symfony\\Component\\Console\\Command\\SignalableCommandInterface` and subscribe to one or more signals::
+
+ // src/Command/SomeCommand.php
+ namespace App\Command;
+
+ use Symfony\Component\Console\Command\Command;
+ use Symfony\Component\Console\Command\SignalableCommandInterface;
+
+ class SomeCommand extends Command implements SignalableCommandInterface
+ {
+ // ...
+
+ public function getSubscribedSignals(): array
+ {
+ // return here any of the constants defined by PCNTL extension
+ return [\SIGINT, \SIGTERM];
+ }
+
+ public function handleSignal(int $signal): int|false
+ {
+ if (\SIGINT === $signal) {
+ // ...
+ }
+
+ // ...
+
+ // return an integer to set the exit code, or
+ // false to continue normal execution
+ return 0;
+ }
+ }
+
+Symfony doesn't handle any signal received by the command (not even ``SIGKILL``,
+``SIGTERM``, etc). This behavior is intended, as it gives you the flexibility to
+handle all signals e.g. to do some tasks before terminating the command.
+
+.. tip::
+
+ If you need to fetch the signal name from its integer value (e.g. for logging),
+ you can use the
+ :method:`Symfony\\Component\\Console\\SignalRegistry\\SignalMap::getSignalName`
+ method.
+
.. _`reserved exit codes`: https://www.tldp.org/LDP/abs/html/exitcodes.html
+.. _`Signals`: https://en.wikipedia.org/wiki/Signal_(IPC)
+.. _`constants of the PCNTL PHP extension`: https://www.php.net/manual/en/pcntl.constants.php
diff --git a/components/console/helpers/cursor.rst b/components/console/helpers/cursor.rst
new file mode 100644
index 00000000000..c5cab6c6d0b
--- /dev/null
+++ b/components/console/helpers/cursor.rst
@@ -0,0 +1,96 @@
+Cursor Helper
+=============
+
+The :class:`Symfony\\Component\\Console\\Cursor` allows you to change the
+cursor position in a console command. This allows you to write on any position
+of the output:
+
+.. image:: /_images/components/console/cursor.gif
+ :alt: A command outputs on various positions on the screen, eventually drawing the letters "SF".
+
+.. code-block:: php
+
+ // src/Command/MyCommand.php
+ namespace App\Command;
+
+ use Symfony\Component\Console\Command\Command;
+ use Symfony\Component\Console\Cursor;
+ use Symfony\Component\Console\Input\InputInterface;
+ use Symfony\Component\Console\Output\OutputInterface;
+
+ class MyCommand extends Command
+ {
+ // ...
+
+ public function execute(InputInterface $input, OutputInterface $output): int
+ {
+ // ...
+
+ $cursor = new Cursor($output);
+
+ // moves the cursor to a specific column (1st argument) and
+ // row (2nd argument) position
+ $cursor->moveToPosition(7, 11);
+
+ // and write text on this position using the output
+ $output->write('My text');
+
+ // ...
+ }
+ }
+
+Using the cursor
+----------------
+
+Moving the cursor
+.................
+
+There are few methods to control moving the command cursor::
+
+ // moves the cursor 1 line up from its current position
+ $cursor->moveUp();
+
+ // moves the cursor 3 lines up from its current position
+ $cursor->moveUp(3);
+
+ // same for down
+ $cursor->moveDown();
+
+ // moves the cursor 1 column right from its current position
+ $cursor->moveRight();
+
+ // moves the cursor 3 columns right from its current position
+ $cursor->moveRight(3);
+
+ // same for left
+ $cursor->moveLeft();
+
+ // move the cursor to a specific (column, row) position from the
+ // top-left position of the terminal
+ $cursor->moveToPosition(7, 11);
+
+You can get the current command's cursor position by using::
+
+ $position = $cursor->getCurrentPosition();
+ // $position[0] // columns (aka x coordinate)
+ // $position[1] // rows (aka y coordinate)
+
+Clearing output
+...............
+
+The cursor can also clear some output on the screen::
+
+ // clears all the output from the current line
+ $cursor->clearLine();
+
+ // clears all the output from the current line after the current position
+ $cursor->clearLineAfter();
+
+ // clears all the output from the cursors' current position to the end of the screen
+ $cursor->clearOutput();
+
+ // clears the entire screen
+ $cursor->clearScreen();
+
+You also can leverage the :method:`Symfony\\Component\\Console\\Cursor::show`
+and :method:`Symfony\\Component\\Console\\Cursor::hide` methods on the cursor.
diff --git a/components/console/helpers/debug_formatter.rst b/components/console/helpers/debug_formatter.rst
index 89609da8419..10d3c67a79a 100644
--- a/components/console/helpers/debug_formatter.rst
+++ b/components/console/helpers/debug_formatter.rst
@@ -1,17 +1,14 @@
-.. index::
- single: Console Helpers; DebugFormatter Helper
-
Debug Formatter Helper
======================
The :class:`Symfony\\Component\\Console\\Helper\\DebugFormatterHelper` provides
functions to output debug information when running an external program, for
instance a process or HTTP request. For example, if you used it to output
-the results of running ``ls -la`` on a UNIX system, it might output something
-like this:
+the results of running ``figlet symfony``, it might output something like
+this:
.. image:: /_images/components/console/debug_formatter.png
- :align: center
+ :alt: Console output, with the first line showing "RUN Running figlet", followed by lines showing the output of the command prefixed with "OUT" and "RES Finished the command" as last line in the output.
Using the debug_formatter
-------------------------
@@ -81,7 +78,7 @@ using
// ...
$process = new Process(...);
- $process->run(function ($type, $buffer) use ($output, $debugFormatter, $process) {
+ $process->run(function (string $type, string $buffer) use ($output, $debugFormatter, $process): void {
$output->writeln(
$debugFormatter->progress(
spl_object_hash($process),
diff --git a/components/console/helpers/formatterhelper.rst b/components/console/helpers/formatterhelper.rst
index ba3c2743d24..d2b19915a3a 100644
--- a/components/console/helpers/formatterhelper.rst
+++ b/components/console/helpers/formatterhelper.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Console Helpers; Formatter Helper
-
Formatter Helper
================
@@ -9,14 +6,20 @@ You can do more advanced things with this helper than you can in
:doc:`/console/coloring`.
The :class:`Symfony\\Component\\Console\\Helper\\FormatterHelper` is included
-in the default helper set, which you can get by calling
-:method:`Symfony\\Component\\Console\\Command\\Command::getHelperSet`::
+in the default helper set and you can get it by calling
+:method:`Symfony\\Component\\Console\\Command\\Command::getHelper`::
$formatter = $this->getHelper('formatter');
The methods return a string, which you'll usually render to the console by
passing it to the
-:method:`OutputInterface::writeln ` method.
+:method:`OutputInterface::writeln `
+method.
+
+.. note::
+
+ As an alternative, consider using the
+ :ref:`SymfonyStyle ` to display stylized blocks.
Print Messages in a Section
---------------------------
@@ -61,8 +64,9 @@ block will be formatted with more padding (one blank line above and below the
messages and 2 spaces on the left and right).
The exact "style" you use in the block is up to you. In this case, you're using
-the pre-defined ``error`` style, but there are other styles, or you can create
-your own. See :doc:`/console/coloring`.
+the pre-defined ``error`` style, but there are other styles (``info``,
+``comment``, ``question``), or you can create your own.
+See :doc:`/console/coloring`.
Print Truncated Messages
------------------------
@@ -78,11 +82,13 @@ you can write::
$truncatedMessage = $formatter->truncate($message, 7);
$output->writeln($truncatedMessage);
-And the output will be::
+And the output will be:
+
+.. code-block:: text
This is...
-The message is truncated to the given length, then the suffix is appended to end
+The message is truncated to the given length, then the suffix is appended to the end
of that string.
Negative String Length
@@ -93,7 +99,9 @@ from the end of the string::
$truncatedMessage = $formatter->truncate($message, -5);
-This will result in::
+This will result in:
+
+.. code-block:: text
This is a very long message, which should be trun...
@@ -102,7 +110,7 @@ Custom Suffix
By default, the ``...`` suffix is used. If you wish to use a different suffix,
pass it as the third argument to the method.
-The suffix is always appended, unless truncate length is longer than a message
+The suffix is always appended, unless truncated length is longer than a message
and a suffix length.
If you don't want to use suffix at all, pass an empty string::
@@ -112,3 +120,34 @@ If you don't want to use suffix at all, pass an empty string::
$truncatedMessage = $formatter->truncate('test', 10);
// result: test
// because length of the "test..." string is shorter than 10
+
+Formatting Time
+---------------
+
+Sometimes you want to format seconds to time. This is possible with the
+:method:`Symfony\\Component\\Console\\Helper\\Helper::formatTime` method.
+The first argument is the seconds to format and the second argument is the
+precision (default ``1``) of the result::
+
+ Helper::formatTime(0.001); // 1 ms
+ Helper::formatTime(42); // 42 s
+ Helper::formatTime(125); // 2 min
+ Helper::formatTime(125, 2); // 2 min, 5 s
+ Helper::formatTime(172799, 4); // 1 d, 23 h, 59 min, 59 s
+ Helper::formatTime(172799.056, 5); // 1 d, 23 h, 59 min, 59 s, 56 ms
+
+.. versionadded:: 7.3
+
+ Support for formatting up to milliseconds was introduced in Symfony 7.3.
+
+Formatting Memory
+-----------------
+
+Sometimes you want to format memory to GiB, MiB, KiB and B. This is possible with the
+:method:`Symfony\\Component\\Console\\Helper\\Helper::formatMemory` method.
+The only argument is the memory size to format::
+
+ Helper::formatMemory(512); // 512 B
+ Helper::formatMemory(1024); // 1 KiB
+ Helper::formatMemory(1024 * 1024); // 1.0 MiB
+ Helper::formatMemory(1024 * 1024 * 1024); // 1 GiB
diff --git a/components/console/helpers/index.rst b/components/console/helpers/index.rst
index 87c62ca7629..893652fb5ab 100644
--- a/components/console/helpers/index.rst
+++ b/components/console/helpers/index.rst
@@ -1,20 +1,7 @@
-.. index::
- single: Console; Console Helpers
-
The Console Helpers
===================
-.. toctree::
- :hidden:
-
- formatterhelper
- processhelper
- progressbar
- questionhelper
- table
- debug_formatter
-
The Console component comes with some useful helpers. These helpers contain
-function to ease some common tasks.
+functions to ease some common tasks.
.. include:: map.rst.inc
diff --git a/components/console/helpers/map.rst.inc b/components/console/helpers/map.rst.inc
index 68e1e722a87..73d5d4da7a0 100644
--- a/components/console/helpers/map.rst.inc
+++ b/components/console/helpers/map.rst.inc
@@ -1,6 +1,9 @@
* :doc:`/components/console/helpers/formatterhelper`
* :doc:`/components/console/helpers/processhelper`
* :doc:`/components/console/helpers/progressbar`
+* :doc:`/components/console/helpers/progressindicator`
* :doc:`/components/console/helpers/questionhelper`
* :doc:`/components/console/helpers/table`
+* :doc:`/components/console/helpers/tree`
* :doc:`/components/console/helpers/debug_formatter`
+* :doc:`/components/console/helpers/cursor`
diff --git a/components/console/helpers/processhelper.rst b/components/console/helpers/processhelper.rst
index 45572d90a66..b46d9f2e95f 100644
--- a/components/console/helpers/processhelper.rst
+++ b/components/console/helpers/processhelper.rst
@@ -1,14 +1,12 @@
-.. index::
- single: Console Helpers; Process Helper
-
Process Helper
==============
-The Process Helper shows processes as they're running and reports
-useful information about process status.
+The Process Helper shows processes as they're running and reports useful
+information about process status.
-To display process details, use the :class:`Symfony\\Component\\Console\\Helper\\ProcessHelper`
-and run your command with verbosity. For example, running the following code with
+To display process details, use the
+:class:`Symfony\\Component\\Console\\Helper\\ProcessHelper` and run your command
+with verbosity. For example, running the following code with
a very verbose verbosity (e.g. ``-vv``)::
use Symfony\Component\Process\Process;
@@ -21,24 +19,30 @@ a very verbose verbosity (e.g. ``-vv``)::
will result in this output:
.. image:: /_images/components/console/process-helper-verbose.png
+ :alt: Console output showing two lines: "RUN 'figlet' 'Symfony'" and "RES Command ran successfully".
It will result in more detailed output with debug verbosity (e.g. ``-vvv``):
.. image:: /_images/components/console/process-helper-debug.png
+ :alt: In between the command line and the result line, the command's output is now shown prefixed by "OUT".
In case the process fails, debugging is easier:
.. image:: /_images/components/console/process-helper-error-debug.png
+ :alt: The last line shows "RES 127 Command dit not run successfully", and the output lines show more the error information from the command.
-Arguments
----------
+.. note::
-There are three ways to use the process helper:
+ By default, the process helper uses the error output (``stderr``) as
+ its default output. This behavior can be changed by passing an instance of
+ :class:`Symfony\\Component\\Console\\Output\\StreamOutput` to the
+ :method:`Symfony\\Component\\Console\\Helper\\ProcessHelper::run`
+ method.
-* Using a command line string::
+Arguments
+---------
- // ...
- $helper->run($output, 'figlet Symfony');
+There are two ways to use the process helper:
* An array of arguments::
@@ -72,7 +76,7 @@ A custom process callback can be passed as the fourth argument. Refer to the
use Symfony\Component\Process\Process;
- $helper->run($output, $process, 'The process failed :(', function ($type, $data) {
+ $helper->run($output, $process, 'The process failed :(', function (string $type, string $data): void {
if (Process::ERR === $type) {
// ... do something with the stderr output
} else {
diff --git a/components/console/helpers/progressbar.rst b/components/console/helpers/progressbar.rst
index 08c8bc6b6a3..19e2d0daef5 100644
--- a/components/console/helpers/progressbar.rst
+++ b/components/console/helpers/progressbar.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Console Helpers; Progress Bar
-
Progress Bar
============
@@ -8,6 +5,12 @@ When executing longer-running commands, it may be helpful to show progress
information, which updates as your command runs:
.. image:: /_images/components/console/progressbar.gif
+ :alt: Console output showing a progress bar advance to 100%, with the estimated time left, the memory usage and a special message that changes when the bar closes completion.
+
+.. note::
+
+ As an alternative, consider using the
+ :ref:`SymfonyStyle ` to display a progress bar.
To display progress details, use the
:class:`Symfony\\Component\\Console\\Helper\\ProgressBar`, pass it a total
@@ -41,18 +44,38 @@ number of units, and advance the progress as the command executes::
``$progress->advance()`` with a negative value. For example, if you call
``$progress->advance(-2)`` then it will regress the progress bar 2 steps.
+.. note::
+
+ By default, the progress bar helper uses the error output (``stderr``) as
+ its default output. This behavior can be changed by passing an instance of
+ :class:`Symfony\\Component\\Console\\Output\\StreamOutput` to the
+ :class:`Symfony\\Component\\Console\\Helper\\ProgressBar`
+ constructor.
+
Instead of advancing the bar by a number of steps (with the
:method:`Symfony\\Component\\Console\\Helper\\ProgressBar::advance` method),
you can also set the current progress by calling the
:method:`Symfony\\Component\\Console\\Helper\\ProgressBar::setProgress` method.
+If you are resuming long-standing tasks, it's useful to start drawing the progress
+bar at a certain point. Use the second optional argument of ``start()`` to set
+that starting point::
+
+ use Symfony\Component\Console\Helper\ProgressBar;
+
+ // creates a new progress bar (100 units)
+ $progressBar = new ProgressBar($output, 100);
+
+ // displays the progress bar starting at 25 completed units
+ $progressBar->start(null, 25);
+
.. tip::
If your platform doesn't support ANSI codes, updates to the progress
bar are added as new lines. To prevent the output from being flooded,
- use the method :method:`Symfony\\Component\\Console\\Helper\\ProgressBar::minSecondsBetweenRedraws`
- to limit the number of redraws and the method
- :method:`Symfony\\Component\\Console\\Helper\\ProgressBar::setRedrawFrequency`
+ use the :method:`Symfony\\Component\\Console\\Helper\\ProgressBar::minSecondsBetweenRedraws`
+ method to limit the number of redraws and the
+ :method:`Symfony\\Component\\Console\\Helper\\ProgressBar::setRedrawFrequency` method
to redraw every N iterations. By default, redraw frequency is
**100ms** or **10%** of your ``max``.
@@ -84,6 +107,12 @@ The progress will then be displayed as a throbber:
1/3 [=========>------------------] 33%
3/3 [============================] 100%
+.. tip::
+
+ An alternative to this is to use a
+ :doc:`/components/console/helpers/progressindicator` instead of a
+ progress bar.
+
Whenever your task is finished, don't forget to call
:method:`Symfony\\Component\\Console\\Helper\\ProgressBar::finish` to ensure
that the progress bar display is refreshed with a 100% completion.
@@ -105,13 +134,19 @@ which starts, advances and finishes the progress bar automatically::
$progressBar = new ProgressBar($output);
- // $iterable can be for example an array ([1, 2, 3, ...]) or a generator
- // $iterable = function () { yield 1; yield 2; ... };
+ // $iterable can be array
+ $iterable = [1, 2];
foreach ($progressBar->iterate($iterable) as $value) {
// ... do some work
}
-If ``$iterable = [1, 2]``, the previous code will output the following:
+ // or a generator
+ function iterable() { yield 1; yield 2; ... };
+ foreach ($progressBar->iterate(iterable()) as $value) {
+ // ... do some work
+ }
+
+The previous code will output:
.. code-block:: text
@@ -141,9 +176,9 @@ level of verbosity of the ``OutputInterface`` instance:
3/3 [============================] 100% 1 sec
# OutputInterface::VERBOSITY_VERY_VERBOSE (-vv)
- 0/3 [>---------------------------] 0% 1 sec
- 1/3 [=========>------------------] 33% 1 sec
- 3/3 [============================] 100% 1 sec
+ 0/3 [>---------------------------] 0% 1 sec/1 sec
+ 1/3 [=========>------------------] 33% 1 sec/1 sec
+ 3/3 [============================] 100% 1 sec/1 sec
# OutputInterface::VERBOSITY_DEBUG (-vvv)
0/3 [>---------------------------] 0% 1 sec/1 sec 1.0 MB
@@ -204,10 +239,14 @@ current progress of the bar. Here is a list of the built-in placeholders:
* ``memory``: The current memory usage;
* ``message``: used to display arbitrary messages in the progress bar (as explained later).
+The time fields ``elapsed``, ``remaining`` and ``estimated`` are displayed with
+a precision of 2. That means ``172799`` seconds are displayed as
+``1 day, 23 hrs`` instead of ``1 day, 23 hrs, 59 mins, 59 secs``.
+
For instance, here is how you could set the format to be the same as the
``debug`` one::
- $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
+ $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:16s%/%estimated:-16s% %memory:6s%');
Notice the ``:6s`` part added to some placeholders? That's how you can tweak
the appearance of the bar (formatting and alignment). The part after the colon
@@ -284,10 +323,10 @@ to display it can be customized::
// the bar width
$progressBar->setBarWidth(50);
-.. caution::
+.. warning::
- For performance reasons, Symfony redraws screen every 100ms. If this is too
- fast or to slow for your application, use the methods
+ For performance reasons, Symfony redraws the screen once every 100ms. If this is too
+ fast or too slow for your application, use the methods
:method:`Symfony\\Component\\Console\\Helper\\ProgressBar::minSecondsBetweenRedraws` and
:method:`Symfony\\Component\\Console\\Helper\\ProgressBar::maxSecondsBetweenRedraws`::
@@ -315,13 +354,23 @@ display that are not available in the list of built-in placeholders, you can
create your own. Let's see how you can create a ``remaining_steps`` placeholder
that displays the number of remaining steps::
+ // This definition is globally registered for all ProgressBar instances
ProgressBar::setPlaceholderFormatterDefinition(
'remaining_steps',
- function (ProgressBar $progressBar, OutputInterface $output) {
+ function (ProgressBar $progressBar, OutputInterface $output): int {
return $progressBar->getMaxSteps() - $progressBar->getProgress();
}
);
+It is also possible to set a placeholder formatter per ProgressBar instance
+with the ``setPlaceholderFormatter`` method::
+
+ $progressBar = new ProgressBar($output, 3, 0);
+ $progressBar->setFormat('%countdown% [%bar%]');
+ $progressBar->setPlaceholderFormatter('countdown', function (ProgressBar $progressBar) {
+ return $progressBar->getMaxSteps() - $progressBar->getProgress();
+ });
+
Custom Messages
~~~~~~~~~~~~~~~
@@ -342,8 +391,8 @@ placeholder before displaying the progress bar::
$progressBar->start();
// 0/100 -- Start
- $progressBar->advance();
$progressBar->setMessage('Task is in progress...');
+ $progressBar->advance();
// 1/100 -- Task is in progress...
Messages can be combined with custom placeholders too. In this example, the
diff --git a/components/console/helpers/progressindicator.rst b/components/console/helpers/progressindicator.rst
new file mode 100644
index 00000000000..0defe7c83fd
--- /dev/null
+++ b/components/console/helpers/progressindicator.rst
@@ -0,0 +1,155 @@
+Progress Indicator
+==================
+
+Progress indicators are useful to let users know that a command isn't stalled.
+Unlike :doc:`progress bars `, these
+indicators are used when the command duration is indeterminate (e.g. long-running
+commands, unquantifiable tasks, etc.)
+
+They work by instantiating the :class:`Symfony\\Component\\Console\\Helper\\ProgressIndicator`
+class and advancing the progress as the command executes::
+
+ use Symfony\Component\Console\Helper\ProgressIndicator;
+
+ // creates a new progress indicator
+ $progressIndicator = new ProgressIndicator($output);
+
+ // starts and displays the progress indicator with a custom message
+ $progressIndicator->start('Processing...');
+
+ $i = 0;
+ while ($i++ < 50) {
+ // ... do some work
+
+ // advances the progress indicator
+ $progressIndicator->advance();
+ }
+
+ // ensures that the progress indicator shows a final message
+ $progressIndicator->finish('Finished');
+
+Customizing the Progress Indicator
+----------------------------------
+
+Built-in Formats
+~~~~~~~~~~~~~~~~
+
+By default, the information rendered on a progress indicator depends on the current
+level of verbosity of the ``OutputInterface`` instance:
+
+.. code-block:: text
+
+ # OutputInterface::VERBOSITY_NORMAL (CLI with no verbosity flag)
+ \ Processing...
+ | Processing...
+ / Processing...
+ - Processing...
+ ✔ Finished
+
+ # OutputInterface::VERBOSITY_VERBOSE (-v)
+ \ Processing... (1 sec)
+ | Processing... (1 sec)
+ / Processing... (1 sec)
+ - Processing... (1 sec)
+ ✔ Finished (1 sec)
+
+ # OutputInterface::VERBOSITY_VERY_VERBOSE (-vv) and OutputInterface::VERBOSITY_DEBUG (-vvv)
+ \ Processing... (1 sec, 6.0 MiB)
+ | Processing... (1 sec, 6.0 MiB)
+ / Processing... (1 sec, 6.0 MiB)
+ - Processing... (1 sec, 6.0 MiB)
+ ✔ Finished (1 sec, 6.0 MiB)
+
+.. tip::
+
+ Call a command with the quiet flag (``-q``) to not display any progress indicator.
+
+Instead of relying on the verbosity mode of the current command, you can also
+force a format via the second argument of the ``ProgressIndicator``
+constructor::
+
+ $progressIndicator = new ProgressIndicator($output, 'verbose');
+
+The built-in formats are the following:
+
+* ``normal``
+* ``verbose``
+* ``very_verbose``
+
+If your terminal doesn't support ANSI, use the ``no_ansi`` variants:
+
+* ``normal_no_ansi``
+* ``verbose_no_ansi``
+* ``very_verbose_no_ansi``
+
+Custom Indicator Values
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Instead of using the built-in indicator values, you can also set your own::
+
+ $progressIndicator = new ProgressIndicator($output, 'verbose', 100, ['⠏', '⠛', '⠹', '⢸', '⣰', '⣤', '⣆', '⡇']);
+
+The progress indicator will now look like this:
+
+.. code-block:: text
+
+ ⠏ Processing...
+ ⠛ Processing...
+ ⠹ Processing...
+ ⢸ Processing...
+ ✔ Finished
+
+Once the progress finishes, it displays a special finished indicator (which defaults
+to ✔). You can replace it with your own::
+
+ $progressIndicator = new ProgressIndicator($output, finishedIndicatorValue: '🎉');
+
+ try {
+ /* do something */
+ $progressIndicator->finish('Finished');
+ } catch (\Exception) {
+ $progressIndicator->finish('Failed', '🚨');
+ }
+
+The progress indicator will now look like this:
+
+.. code-block:: text
+
+ \ Processing...
+ | Processing...
+ / Processing...
+ - Processing...
+ 🎉 Finished
+
+.. versionadded:: 7.2
+
+ The ``finishedIndicator`` parameter for the constructor was introduced in Symfony 7.2.
+ The ``finishedIndicator`` parameter for method ``finish()`` was introduced in Symfony 7.2.
+
+Customize Placeholders
+~~~~~~~~~~~~~~~~~~~~~~
+
+A progress indicator uses placeholders (a name enclosed with the ``%``
+character) to determine the output format. Here is a list of the
+built-in placeholders:
+
+* ``indicator``: The current indicator;
+* ``elapsed``: The time elapsed since the start of the progress indicator;
+* ``memory``: The current memory usage;
+* ``message``: used to display arbitrary messages in the progress indicator.
+
+For example, this is how you can customize the ``message`` placeholder::
+
+ ProgressIndicator::setPlaceholderFormatterDefinition(
+ 'message',
+ static function (ProgressIndicator $progressIndicator): string {
+ // Return any arbitrary string
+ return 'My custom message';
+ }
+ );
+
+.. note::
+
+ Placeholders customization is applied globally, which means that any
+ progress indicator displayed after the
+ ``setPlaceholderFormatterDefinition()`` call will be affected.
diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst
index 73300db25c9..c7e064b16ca 100644
--- a/components/console/helpers/questionhelper.rst
+++ b/components/console/helpers/questionhelper.rst
@@ -1,23 +1,25 @@
-.. index::
- single: Console Helpers; Question Helper
-
Question Helper
===============
The :class:`Symfony\\Component\\Console\\Helper\\QuestionHelper` provides
functions to ask the user for more information. It is included in the default
-helper set, which you can get by calling
-:method:`Symfony\\Component\\Console\\Command\\Command::getHelperSet`::
+helper set and you can get it by calling
+:method:`Symfony\\Component\\Console\\Command\\Command::getHelper`::
$helper = $this->getHelper('question');
The Question Helper has a single method
-:method:`Symfony\\Component\\Console\\Command\\Command::ask` that needs an
+:method:`Symfony\\Component\\Console\\Helper\\QuestionHelper::ask` that needs an
:class:`Symfony\\Component\\Console\\Input\\InputInterface` instance as the
first argument, an :class:`Symfony\\Component\\Console\\Output\\OutputInterface`
instance as the second argument and a
:class:`Symfony\\Component\\Console\\Question\\Question` as last argument.
+.. note::
+
+ As an alternative, consider using the
+ :ref:`SymfonyStyle ` to ask questions.
+
Asking the User for Confirmation
--------------------------------
@@ -34,19 +36,25 @@ the following to your command::
{
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion('Continue with this action?', false);
if (!$helper->ask($input, $output, $question)) {
- return;
+ return Command::SUCCESS;
}
+
+ // ... do something here
+
+ return Command::SUCCESS;
}
}
In this case, the user will be asked "Continue with this action?". If the user
-answers with ``y`` it returns ``true`` or ``false`` if they answer with ``n``.
+answers with ``y`` (or any word, expression starting with ``y`` due to default
+answer regex, e.g ``yeti``) it returns ``true`` or ``false`` otherwise, e.g. ``n``.
+
The second argument to
:method:`Symfony\\Component\\Console\\Question\\ConfirmationQuestion::__construct`
is the default value to return if the user doesn't enter any valid input. If
@@ -66,6 +74,14 @@ the second argument is not provided, ``true`` is assumed.
The regex defaults to ``/^y/i``.
+.. note::
+
+ By default, the question helper uses the error output (``stderr``) as
+ its default output. This behavior can be changed by passing an instance of
+ :class:`Symfony\\Component\\Console\\Output\\StreamOutput` to the
+ :method:`Symfony\\Component\\Console\\Helper\\QuestionHelper::ask`
+ method.
+
Asking the User for Information
-------------------------------
@@ -75,12 +91,16 @@ if you want to know a bundle name, you can add this to your command::
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
$bundleName = $helper->ask($input, $output, $question);
+
+ // ... do something with the bundleName
+
+ return Command::SUCCESS;
}
The user will be asked "Please enter the name of the bundle". They can type
@@ -93,18 +113,21 @@ Let the User Choose from a List of Answers
If you have a predefined set of answers the user can choose from, you
could use a :class:`Symfony\\Component\\Console\\Question\\ChoiceQuestion`
-which makes sure that the user can only enter a valid string
-from a predefined list::
+which makes sure that the user can only enter a valid string or the index
+of the choice from a predefined list. In the example below, typing ``blue``
+or ``1`` is the same choice for the user. A default value is set with ``0``
+but ``red`` could be set instead (could be more explicit)::
use Symfony\Component\Console\Question\ChoiceQuestion;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
$question = new ChoiceQuestion(
'Please select your favorite color (defaults to red)',
+ // choices can also be PHP objects that implement __toString() method
['red', 'blue', 'yellow'],
0
);
@@ -114,16 +137,40 @@ from a predefined list::
$output->writeln('You have just selected: '.$color);
// ... do something with the color
+
+ return Command::SUCCESS;
}
The option which should be selected by default is provided with the third
argument of the constructor. The default is ``null``, which means that no
option is the default one.
+Choice questions display both the choice value and a numeric index, which starts
+from 0 by default. The user can type either the numeric index or the choice value
+to make a selection:
+
+.. code-block:: terminal
+
+ Please select your favorite color (defaults to red):
+ [0] red
+ [1] blue
+ [2] yellow
+ >
+
+.. tip::
+
+ To use custom indices, pass an array with custom numeric keys as the choice
+ values::
+
+ new ChoiceQuestion('Select a room:', [
+ 102 => 'Room Foo',
+ 213 => 'Room Bar',
+ ]);
+
If the user enters an invalid string, an error message is shown and the user
is asked to provide the answer another time, until they enter a valid string
or reach the maximum number of attempts. The default value for the maximum number
-of attempts is ``null``, which means infinite number of attempts. You can define
+of attempts is ``null``, which means an infinite number of attempts. You can define
your own error message using
:method:`Symfony\\Component\\Console\\Question\\ChoiceQuestion::setErrorMessage`.
@@ -137,7 +184,7 @@ this use :method:`Symfony\\Component\\Console\\Question\\ChoiceQuestion::setMult
use Symfony\Component\Console\Question\ChoiceQuestion;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
@@ -150,10 +197,14 @@ this use :method:`Symfony\\Component\\Console\\Question\\ChoiceQuestion::setMult
$colors = $helper->ask($input, $output, $question);
$output->writeln('You have just selected: ' . implode(', ', $colors));
+
+ return Command::SUCCESS;
}
Now, when the user enters ``1,2``, the result will be:
-``You have just selected: blue, yellow``.
+``You have just selected: blue, yellow``. The user can also enter strings
+(e.g. ``blue,yellow``) and even mix strings and the index of the choices
+(e.g. ``blue,2``).
If the user does not enter anything, the result will be:
``You have just selected: red, blue``.
@@ -167,7 +218,7 @@ will be autocompleted as the user types::
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
@@ -177,6 +228,10 @@ will be autocompleted as the user types::
$question->setAutocompleterValues($bundles);
$bundleName = $helper->ask($input, $output, $question);
+
+ // ... do something with the bundleName
+
+ return Command::SUCCESS;
}
In more complex use cases, it may be necessary to generate suggestions on the
@@ -186,7 +241,7 @@ provide a callback function to dynamically generate suggestions::
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
$helper = $this->getHelper('question');
@@ -203,7 +258,7 @@ provide a callback function to dynamically generate suggestions::
// where files and dirs can be found
$foundFilesAndDirs = @scandir($inputPath) ?: [];
- return array_map(function ($dirOrFile) use ($inputPath) {
+ return array_map(function (string $dirOrFile) use ($inputPath): string {
return $inputPath.$dirOrFile;
}, $foundFilesAndDirs);
};
@@ -212,6 +267,10 @@ provide a callback function to dynamically generate suggestions::
$question->setAutocompleterCallback($callback);
$filePath = $helper->ask($input, $output, $question);
+
+ // ... do something with the filePath
+
+ return Command::SUCCESS;
}
Do not Trim the Answer
@@ -223,7 +282,7 @@ You can also specify if you want to not trim the answer by setting it directly w
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
@@ -232,8 +291,41 @@ You can also specify if you want to not trim the answer by setting it directly w
$question->setTrimmable(false);
// if the users inputs 'elsa ' it will not be trimmed and you will get 'elsa ' as value
$name = $helper->ask($input, $output, $question);
+
+ // ... do something with the name
+
+ return Command::SUCCESS;
}
+Accept Multiline Answers
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+By default, the question helper stops reading user input when it receives a newline
+character (i.e., when the user hits ``ENTER`` once). However, you may specify that
+the response to a question should allow multiline answers by passing ``true`` to
+:method:`Symfony\\Component\\Console\\Question\\Question::setMultiline`::
+
+ use Symfony\Component\Console\Question\Question;
+
+ // ...
+ public function execute(InputInterface $input, OutputInterface $output): int
+ {
+ // ...
+ $helper = $this->getHelper('question');
+
+ $question = new Question('How do you solve world peace?');
+ $question->setMultiline(true);
+
+ $answer = $helper->ask($input, $output, $question);
+
+ // ... do something with the answer
+
+ return Command::SUCCESS;
+ }
+
+Multiline questions stop reading user input after receiving an end-of-transmission
+control character (``Ctrl-D`` on Unix systems or ``Ctrl-Z`` on Windows).
+
Hiding the User's Response
~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -243,7 +335,7 @@ convenient for passwords::
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
@@ -253,9 +345,13 @@ convenient for passwords::
$question->setHiddenFallback(false);
$password = $helper->ask($input, $output, $question);
+
+ // ... do something with the password
+
+ return Command::SUCCESS;
}
-.. caution::
+.. warning::
When you ask for a hidden response, Symfony will use either a binary, change
``stty`` mode or use another trick to hide the response. If none is available,
@@ -276,13 +372,15 @@ convenient for passwords::
use Symfony\Component\Console\Question\ChoiceQuestion;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
QuestionHelper::disableStty();
// ...
+
+ return Command::SUCCESS;
}
Normalizing the Answer
@@ -298,26 +396,32 @@ method::
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
- $question->setNormalizer(function ($value) {
+ $question->setNormalizer(function (string $value): string {
// $value can be null here
return $value ? trim($value) : '';
});
$bundleName = $helper->ask($input, $output, $question);
+
+ // ... do something with the bundleName
+
+ return Command::SUCCESS;
}
-.. caution::
+.. warning::
The normalizer is called first and the returned value is used as the input
of the validator. If the answer is invalid, don't throw exceptions in the
normalizer and let the validator handle those errors.
+.. _console-validate-question-answer:
+
Validating the Answer
---------------------
@@ -330,13 +434,13 @@ method::
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
- $question->setValidator(function ($answer) {
+ $question->setValidator(function (string $answer): string {
if (!is_string($answer) || 'Bundle' !== substr($answer, -6)) {
throw new \RuntimeException(
'The name of the bundle should be suffixed with \'Bundle\''
@@ -348,6 +452,10 @@ method::
$question->setMaxAttempts(2);
$bundleName = $helper->ask($input, $output, $question);
+
+ // ... do something with the bundleName
+
+ return Command::SUCCESS;
}
The ``$validator`` is a callback which handles the validation. It should
@@ -359,9 +467,25 @@ was successful.
You can set the max number of times to ask with the
:method:`Symfony\\Component\\Console\\Question\\Question::setMaxAttempts` method.
If you reach this max number it will use the default value. Using ``null`` means
-the amount of attempts is infinite. The user will be asked as long as they provide an
+the number of attempts is infinite. The user will be asked as long as they provide an
invalid answer and will only be able to proceed if their input is valid.
+.. tip::
+
+ You can even use the :doc:`Validator ` component to
+ validate the input by using the :method:`Symfony\\Component\\Validator\\Validation::createCallable`
+ method::
+
+ use Symfony\Component\Validator\Constraints\Regex;
+ use Symfony\Component\Validator\Validation;
+
+ $question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
+ $validation = Validation::createCallable(new Regex(
+ pattern: '/^[a-zA-Z]+Bundle$/',
+ message: 'The name of the bundle should be suffixed with \'Bundle\'',
+ ));
+ $question->setValidator($validation);
+
Validating a Hidden Response
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -370,14 +494,17 @@ You can also use a validator with a hidden question::
use Symfony\Component\Console\Question\Question;
// ...
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
// ...
$helper = $this->getHelper('question');
$question = new Question('Please enter your password');
- $question->setValidator(function ($value) {
- if (trim($value) == '') {
+ $question->setNormalizer(function (?string $value): string {
+ return $value ?? '';
+ });
+ $question->setValidator(function (string $value): string {
+ if ('' === trim($value)) {
throw new \Exception('The password cannot be empty');
}
@@ -387,6 +514,10 @@ You can also use a validator with a hidden question::
$question->setMaxAttempts(20);
$password = $helper->ask($input, $output, $question);
+
+ // ... do something with the password
+
+ return Command::SUCCESS;
}
Testing a Command that Expects Input
@@ -395,12 +526,10 @@ Testing a Command that Expects Input
If you want to write a unit test for a command which expects some kind of input
from the command line, you need to set the inputs that the command expects::
- use Symfony\Component\Console\Helper\HelperSet;
- use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Tester\CommandTester;
// ...
- public function testExecute()
+ public function testExecute(): void
{
// ...
$commandTester = new CommandTester($command);
@@ -433,7 +562,7 @@ This way you can test any user interaction (even complex ones) by passing the ap
simulates a user hitting ``ENTER`` after each input, no need for passing
an additional input.
-.. caution::
+.. warning::
On Windows systems Symfony uses a special binary to implement hidden
questions. This means that those questions don't use the default ``Input``
diff --git a/components/console/helpers/table.rst b/components/console/helpers/table.rst
index bc680cc5ad0..fe267599caf 100644
--- a/components/console/helpers/table.rst
+++ b/components/console/helpers/table.rst
@@ -1,21 +1,11 @@
-.. index::
- single: Console Helpers; Table
+Table Helper
+============
-Table
-=====
-
-When building a console application it may be useful to display tabular data:
-
-.. code-block:: terminal
-
- +---------------+--------------------------+------------------+
- | ISBN | Title | Author |
- +---------------+--------------------------+------------------+
- | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
- | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
- | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
- | 80-902734-1-6 | And Then There Were None | Agatha Christie |
- +---------------+--------------------------+------------------+
+When building console applications, Symfony provides several utilities for
+rendering tabular data. The simplest option is to use the table methods from
+:ref:`Symfony Style `. While convenient, this approach
+doesn't allow customization of the table's design. For more control and advanced
+features, use the ``Table`` console helper explained in this article.
To display a table, use :class:`Symfony\\Component\\Console\\Helper\\Table`,
set the headers, set the rows and then render the table::
@@ -28,7 +18,7 @@ set the headers, set the rows and then render the table::
class SomeCommand extends Command
{
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
$table = new Table($output);
$table
@@ -41,9 +31,27 @@ set the headers, set the rows and then render the table::
])
;
$table->render();
+
+ return Command::SUCCESS;
}
}
+This outputs:
+
+.. code-block:: terminal
+
+ +---------------+--------------------------+------------------+
+ | ISBN | Title | Author |
+ +---------------+--------------------------+------------------+
+ | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
+ | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
+ | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
+ | 80-902734-1-6 | And Then There Were None | Agatha Christie |
+ +---------------+--------------------------+------------------+
+
+Adding Table Separators
+-----------------------
+
You can add a table separator anywhere in the output by passing an instance of
:class:`Symfony\\Component\\Console\\Helper\\TableSeparator` as a row::
@@ -57,6 +65,8 @@ You can add a table separator anywhere in the output by passing an instance of
['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'],
]);
+This outputs:
+
.. code-block:: terminal
+---------------+--------------------------+------------------+
@@ -69,13 +79,18 @@ You can add a table separator anywhere in the output by passing an instance of
| 80-902734-1-6 | And Then There Were None | Agatha Christie |
+---------------+--------------------------+------------------+
+Adding Table Titles
+-------------------
+
You can optionally display titles at the top and the bottom of the table::
// ...
- $table->setHeaderTitle('Books')
- $table->setFooterTitle('Page 1/2')
+ $table->setHeaderTitle('Books');
+ $table->setFooterTitle('Page 1/2');
$table->render();
+This outputs:
+
.. code-block:: terminal
+---------------+----------- Books --------+------------------+
@@ -88,6 +103,9 @@ You can optionally display titles at the top and the bottom of the table::
| 80-902734-1-6 | And Then There Were None | Agatha Christie |
+---------------+--------- Page 1/2 -------+------------------+
+Setting the Column Widths Explicitly
+------------------------------------
+
By default, the width of the columns is calculated automatically based on their
contents. Use the :method:`Symfony\\Component\\Console\\Helper\\Table::setColumnWidths`
method to set the column widths explicitly::
@@ -110,7 +128,7 @@ argument is the column width::
$table->setColumnWidth(2, 30);
$table->render();
-The output of this command will be:
+This outputs:
.. code-block:: terminal
@@ -137,7 +155,7 @@ If you prefer to wrap long contents in multiple rows, use the
$table->setColumnMaxWidth(1, 10);
$table->render();
-The output of this command will be:
+This outputs:
.. code-block:: terminal
@@ -147,20 +165,51 @@ The output of this command will be:
| 99921 | Divine Com | Dante Alighieri |
| -58-1 | edy | |
| 0-7 | | |
- | (the rest of rows...) |
+ | (the rest of the rows...) |
+-------+------------+--------------------------------+
+Rendering Vertical Tables
+-------------------------
+
+By default, table contents are displayed horizontally. You can change this behavior
+via the :method:`Symfony\\Component\\Console\\Helper\\Table::setVertical` method::
+
+ // ...
+ $table->setVertical();
+ $table->render();
+
+This outputs:
+
+.. code-block:: terminal
+
+ +------------------------------+
+ | ISBN: 99921-58-10-7 |
+ | Title: Divine Comedy |
+ | Author: Dante Alighieri |
+ |------------------------------|
+ | ISBN: 9971-5-0210-0 |
+ | Title: A Tale of Two Cities |
+ | Author: Charles Dickens |
+ +------------------------------+
+
+Customizing the Table Style
+---------------------------
+
The table style can be changed to any built-in styles via
:method:`Symfony\\Component\\Console\\Helper\\Table::setStyle`::
- // same as calling nothing
+ // this 'default' style is the one used when no style is specified
$table->setStyle('default');
- // changes the default style to compact
+Built-in Table Styles
+~~~~~~~~~~~~~~~~~~~~~
+
+**Compact**::
+
$table->setStyle('compact');
$table->render();
-This code results in:
+This outputs:
.. code-block:: terminal
@@ -170,12 +219,12 @@ This code results in:
960-425-059-0 The Lord of the Rings J. R. R. Tolkien
80-902734-1-6 And Then There Were None Agatha Christie
-You can also set the style to ``borderless``::
+**Borderless**::
$table->setStyle('borderless');
$table->render();
-which outputs:
+This outputs:
.. code-block:: terminal
@@ -188,14 +237,14 @@ which outputs:
80-902734-1-6 And Then There Were None Agatha Christie
=============== ========================== ==================
-You can also set the style to ``box``::
+**Box**::
$table->setStyle('box');
$table->render();
-which outputs:
+This outputs:
-.. code-block:: text
+.. code-block:: terminal
┌───────────────┬──────────────────────────┬──────────────────┐
│ ISBN │ Title │ Author │
@@ -206,14 +255,14 @@ which outputs:
│ 80-902734-1-6 │ And Then There Were None │ Agatha Christie │
└───────────────┴──────────────────────────┴──────────────────┘
-You can also set the style to ``box-double``::
+**Double box**::
$table->setStyle('box-double');
$table->render();
-which outputs:
+This outputs:
-.. code-block:: text
+.. code-block:: terminal
╔═══════════════╤══════════════════════════╤══════════════════╗
║ ISBN │ Title │ Author ║
@@ -224,7 +273,30 @@ which outputs:
║ 80-902734-1-6 │ And Then There Were None │ Agatha Christie ║
╚═══════════════╧══════════════════════════╧══════════════════╝
-If the built-in styles do not fit your need, define your own::
+**Markdown**::
+
+ $table->setStyle('markdown');
+ $table->render();
+
+This outputs:
+
+.. code-block:: terminal
+
+ | ISBN | Title | Author |
+ |---------------|--------------------------|------------------|
+ | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
+ | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
+ | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
+ | 80-902734-1-6 | And Then There Were None | Agatha Christie |
+
+.. versionadded:: 7.3
+
+ The ``markdown`` style was introduced in Symfony 7.3.
+
+Making a Custom Table Style
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If the built-in styles do not fit your needs, define your own::
use Symfony\Component\Console\Helper\TableStyle;
@@ -233,7 +305,7 @@ If the built-in styles do not fit your need, define your own::
// customizes the style
$tableStyle
- ->setDefaultCrossingChars('|>')
+ ->setHorizontalBorderChars('|>')
->setVerticalBorderChars('->')
->setDefaultCrossingChar(' ')
;
@@ -244,7 +316,7 @@ If the built-in styles do not fit your need, define your own::
Here is a full list of things you can customize:
* :method:`Symfony\\Component\\Console\\Helper\\TableStyle::setPaddingChar`
-* :method:`Symfony\\Component\\Console\\Helper\\TableStyle::setDefaultCrossingChars`
+* :method:`Symfony\\Component\\Console\\Helper\\TableStyle::setHorizontalBorderChars`
* :method:`Symfony\\Component\\Console\\Helper\\TableStyle::setVerticalBorderChars`
* :method:`Symfony\\Component\\Console\\Helper\\TableStyle::setCrossingChars`
* :method:`Symfony\\Component\\Console\\Helper\\TableStyle::setDefaultCrossingChar`
@@ -265,6 +337,35 @@ Here is a full list of things you can customize:
This method can also be used to override a built-in style.
+In addition to the built-in table styles, you can also apply different styles
+to each table cell via :class:`Symfony\\Component\\Console\\Helper\\TableCellStyle`::
+
+ use Symfony\Component\Console\Helper\Table;
+ use Symfony\Component\Console\Helper\TableCellStyle;
+
+ $table = new Table($output);
+
+ $table->setRows([
+ [
+ '978-0804169127',
+ new TableCell(
+ 'Divine Comedy',
+ [
+ 'style' => new TableCellStyle([
+ 'align' => 'center',
+ 'fg' => 'red',
+ 'bg' => 'green',
+
+ // or
+ 'cellFormat' => '%s ',
+ ])
+ ]
+ )
+ ],
+ ]);
+
+ $table->render();
+
Spanning Multiple Columns and Rows
----------------------------------
@@ -285,7 +386,7 @@ To make a table cell that spans multiple columns you can use a :class:`Symfony\\
;
$table->render();
-This results in:
+This outputs:
.. code-block:: terminal
@@ -305,10 +406,10 @@ This results in:
$table->setHeaders([
[new TableCell('Main table title', ['colspan' => 3])],
['ISBN', 'Title', 'Author'],
- ])
+ ]);
// ...
- This generates:
+ This outputs:
.. code-block:: terminal
@@ -350,7 +451,7 @@ This outputs:
| 978-0804169127 | Divine Comedy | spans multiple rows |
+----------------+---------------+---------------------+
-You can use the ``colspan`` and ``rowspan`` options at the same time which allows
+You can use the ``colspan`` and ``rowspan`` options at the same time, which allows
you to create any table layout you may wish.
.. _console-modify-rendered-tables:
@@ -373,7 +474,7 @@ The only requirement to append rows is that the table must be rendered inside a
class SomeCommand extends Command
{
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
$section = $output->section();
$table = new Table($section);
@@ -382,10 +483,12 @@ The only requirement to append rows is that the table must be rendered inside a
$table->render();
$table->appendRow(['Symfony']);
+
+ return Command::SUCCESS;
}
}
-This will display the following table in the terminal:
+This outputs:
.. code-block:: terminal
@@ -393,3 +496,24 @@ This will display the following table in the terminal:
| Love |
| Symfony |
+---------+
+
+.. tip::
+
+ You can create multiple lines using the :method:`Symfony\\Component\\Console\\Helper\\Table::addRows` method::
+
+ // ...
+ $table->addRows([
+ ['Hello', 'World'],
+ ['Love', 'Symfony'],
+ ]);
+ $table->render();
+ // ...
+
+ This outputs:
+
+ .. code-block:: terminal
+
+ +-------+---------+
+ | Hello | World |
+ | Love | Symfony |
+ +-------+---------+
diff --git a/components/console/helpers/tree.rst b/components/console/helpers/tree.rst
new file mode 100644
index 00000000000..0839fb943e2
--- /dev/null
+++ b/components/console/helpers/tree.rst
@@ -0,0 +1,341 @@
+Tree Helper
+===========
+
+The Tree Helper allows you to build and display tree structures in the console.
+It's commonly used to render directory hierarchies, but you can also use it to render
+any tree-like content, such us organizational charts, product category trees, taxonomies, etc.
+
+.. versionadded:: 7.3
+
+ The ``TreeHelper`` class was introduced in Symfony 7.3.
+
+Rendering a Tree
+----------------
+
+The :method:`Symfony\\Component\\Console\\Helper\\TreeHelper::createTree` method
+creates a tree structure from an array and returns a :class:`Symfony\\Component\\Console\\Helper\\Tree`
+object that can be rendered in the console.
+
+Rendering a Tree from an Array
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You can build a tree from an array by passing the array to the
+:method:`Symfony\\Component\\Console\\Helper\\TreeHelper::createTree` method
+inside your console command::
+
+ namespace App\Command;
+
+ use Symfony\Component\Console\Attribute\AsCommand;
+ use Symfony\Component\Console\Command\Command;
+ use Symfony\Component\Console\Helper\TreeHelper;
+ use Symfony\Component\Console\Helper\TreeNode;
+ use Symfony\Component\Console\Input\InputInterface;
+ use Symfony\Component\Console\Output\OutputInterface;
+ use Symfony\Component\Console\Style\SymfonyStyle;
+
+ #[AsCommand(name: 'app:some-command', description: '...')]
+ class SomeCommand extends Command
+ {
+ // ...
+
+ protected function execute(InputInterface $input, OutputInterface $output): int
+ {
+ $io = new SymfonyStyle($input, $output);
+
+ $node = TreeNode::fromValues([
+ 'config/',
+ 'public/',
+ 'src/',
+ 'templates/',
+ 'tests/',
+ ]);
+
+ $tree = TreeHelper::createTree($io, $node);
+ $tree->render();
+
+ // ...
+ }
+ }
+
+This exampe would output the following:
+
+.. code-block:: terminal
+
+ ├── config/
+ ├── public/
+ ├── src/
+ ├── templates/
+ └── tests/
+
+The given contents can be defined in a multi-dimensional array::
+
+ $tree = TreeHelper::createTree($io, null, [
+ 'src' => [
+ 'Command',
+ 'Controller' => [
+ 'DefaultController.php',
+ ],
+ 'Kernel.php',
+ ],
+ 'templates' => [
+ 'base.html.twig',
+ ],
+ ]);
+
+ $tree->render();
+
+The above code will output the following tree:
+
+.. code-block:: terminal
+
+ ├── src
+ │ ├── Command
+ │ ├── Controller
+ │ │ └── DefaultController.php
+ │ └── Kernel.php
+ └── templates
+ └── base.html.twig
+
+Building a Tree Programmatically
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you don't know the tree elements beforehand, you can build the tree programmatically
+by creating a new instance of the :class:`Symfony\\Component\\Console\\Helper\\Tree`
+class and adding nodes to it::
+
+ use Symfony\Component\Console\Helper\TreeHelper;
+ use Symfony\Component\Console\Helper\TreeNode;
+
+ $root = new TreeNode('my-project/');
+ // you can pass a string directly or create a TreeNode object
+ $root->addChild('src/');
+ $root->addChild(new TreeNode('templates/'));
+
+ // create nested structures by adding child nodes to other nodes
+ $testsNode = new TreeNode('tests/');
+ $functionalTestsNode = new TreeNode('Functional/');
+ $testsNode->addChild($functionalTestsNode);
+ $root->addChild($testsNode);
+
+ $tree = TreeHelper::createTree($io, $root);
+ $tree->render();
+
+This example outputs:
+
+.. code-block:: terminal
+
+ my-project/
+ ├── src/
+ ├── templates/
+ └── tests/
+ └── Functional/
+
+If you prefer, you can build the array of elements programmatically and then
+create and render the tree like this::
+
+ $tree = TreeHelper::createTree($io, null, $array);
+ $tree->render();
+
+You can also build part of the tree from an array and then add other nodes::
+
+ $node = TreeNode::fromValues($array);
+ $node->addChild('templates');
+ // ...
+ $tree = TreeHelper::createTree($io, $node);
+ $tree->render();
+
+Customizing the Tree Style
+--------------------------
+
+Built-in Tree Styles
+~~~~~~~~~~~~~~~~~~~~
+
+The tree helper provides a few built-in styles that you can use to customize the
+output of the tree.
+
+**Default**::
+
+ TreeHelper::createTree($io, $node, [], TreeStyle::default());
+
+This outputs:
+
+.. code-block:: terminal
+
+ ├── config
+ │ ├── packages
+ │ └── routes
+ │ ├── framework.yaml
+ │ └── web_profiler.yaml
+ ├── src
+ │ ├── Command
+ │ ├── Controller
+ │ │ └── DefaultController.php
+ │ └── Kernel.php
+ └── templates
+ └── base.html.twig
+
+**Box**::
+
+ TreeHelper::createTree($io, $node, [], TreeStyle::box());
+
+This outputs:
+
+.. code-block:: terminal
+
+ ┃╸ config
+ ┃ ┃╸ packages
+ ┃ ┗╸ routes
+ ┃ ┃╸ framework.yaml
+ ┃ ┗╸ web_profiler.yaml
+ ┃╸ src
+ ┃ ┃╸ Command
+ ┃ ┃╸ Controller
+ ┃ ┃ ┗╸ DefaultController.php
+ ┃ ┗╸ Kernel.php
+ ┗╸ templates
+ ┗╸ base.html.twig
+
+**Double box**::
+
+ TreeHelper::createTree($io, $node, [], TreeStyle::doubleBox());
+
+This outputs:
+
+.. code-block:: terminal
+
+ ╠═ config
+ ║ ╠═ packages
+ ║ ╚═ routes
+ ║ ╠═ framework.yaml
+ ║ ╚═ web_profiler.yaml
+ ╠═ src
+ ║ ╠═ Command
+ ║ ╠═ Controller
+ ║ ║ ╚═ DefaultController.php
+ ║ ╚═ Kernel.php
+ ╚═ templates
+ ╚═ base.html.twig
+
+**Compact**::
+
+ TreeHelper::createTree($io, $node, [], TreeStyle::compact());
+
+This outputs:
+
+.. code-block:: terminal
+
+ ├ config
+ │ ├ packages
+ │ └ routes
+ │ ├ framework.yaml
+ │ └ web_profiler.yaml
+ ├ src
+ │ ├ Command
+ │ ├ Controller
+ │ │ └ DefaultController.php
+ │ └ Kernel.php
+ └ templates
+ └ base.html.twig
+
+**Light**::
+
+ TreeHelper::createTree($io, $node, [], TreeStyle::light());
+
+This outputs:
+
+.. code-block:: terminal
+
+ |-- config
+ | |-- packages
+ | `-- routes
+ | |-- framework.yaml
+ | `-- web_profiler.yaml
+ |-- src
+ | |-- Command
+ | |-- Controller
+ | | `-- DefaultController.php
+ | `-- Kernel.php
+ `-- templates
+ `-- base.html.twig
+
+**Minimal**::
+
+ TreeHelper::createTree($io, $node, [], TreeStyle::minimal());
+
+This outputs:
+
+.. code-block:: terminal
+
+ . config
+ . . packages
+ . . routes
+ . . framework.yaml
+ . . web_profiler.yaml
+ . src
+ . . Command
+ . . Controller
+ . . . DefaultController.php
+ . . Kernel.php
+ . templates
+ . base.html.twig
+
+**Rounded**::
+
+ TreeHelper::createTree($io, $node, [], TreeStyle::rounded());
+
+This outputs:
+
+.. code-block:: terminal
+
+ ├─ config
+ │ ├─ packages
+ │ ╰─ routes
+ │ ├─ framework.yaml
+ │ ╰─ web_profiler.yaml
+ ├─ src
+ │ ├─ Command
+ │ ├─ Controller
+ │ │ ╰─ DefaultController.php
+ │ ╰─ Kernel.php
+ ╰─ templates
+ ╰─ base.html.twig
+
+Making a Custom Tree Style
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You can create your own tree style by passing the characters to the constructor
+of the :class:`Symfony\\Component\\Console\\Helper\\TreeStyle` class::
+
+ use Symfony\Component\Console\Helper\TreeHelper;
+ use Symfony\Component\Console\Helper\TreeStyle;
+
+ $customStyle = new TreeStyle('🟣 ', '🟠 ', '🔵 ', '🟢 ', '🔴 ', '🟡 ');
+
+ // Pass the custom style to the createTree method
+
+ $tree = TreeHelper::createTree($io, null, [
+ 'src' => [
+ 'Command',
+ 'Controller' => [
+ 'DefaultController.php',
+ ],
+ 'Kernel.php',
+ ],
+ 'templates' => [
+ 'base.html.twig',
+ ],
+ ], $customStyle);
+
+ $tree->render();
+
+The above code will output the following tree:
+
+.. code-block:: terminal
+
+ 🔵 🟣 🟡 src
+ 🔵 🟢 🟣 🟡 Command
+ 🔵 🟢 🟣 🟡 Controller
+ 🔵 🟢 🟢 🟠 🟡 DefaultController.php
+ 🔵 🟢 🟠 🟡 Kernel.php
+ 🔵 🟠 🟡 templates
+ 🔵 🔴 🟠 🟡 base.html.twig
diff --git a/components/console/logger.rst b/components/console/logger.rst
index 8f029e47002..c3d5c447a89 100644
--- a/components/console/logger.rst
+++ b/components/console/logger.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Console; Logger
-
Using the Logger
================
@@ -19,14 +16,12 @@ PSR-3 compliant logger::
class MyDependency
{
- private $logger;
-
- public function __construct(LoggerInterface $logger)
- {
- $this->logger = $logger;
+ public function __construct(
+ private LoggerInterface $logger,
+ ) {
}
- public function doStuff()
+ public function doStuff(): void
{
$this->logger->info('I love Tony Vairelles\' hairdresser.');
}
@@ -37,30 +32,26 @@ You can rely on the logger to use this dependency inside a command::
namespace Acme\Console\Command;
use Acme\MyDependency;
+ use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
+ #[AsCommand(
+ name: 'my:command',
+ description: 'Use an external dependency requiring a PSR-3 logger'
+ )]
class MyCommand extends Command
{
- protected static $defaultName = 'my:command';
-
- protected function configure()
- {
- $this
- ->setDescription(
- 'Use an external dependency requiring a PSR-3 logger'
- )
- ;
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$logger = new ConsoleLogger($output);
$myDependency = new MyDependency($logger);
$myDependency->doStuff();
+
+ return Command::SUCCESS;
}
}
diff --git a/components/console/single_command_tool.rst b/components/console/single_command_tool.rst
index 74c554c46ef..97cb09bf030 100644
--- a/components/console/single_command_tool.rst
+++ b/components/console/single_command_tool.rst
@@ -1,38 +1,30 @@
-.. index::
- single: Console; Single command application
-
Building a single Command Application
=====================================
When building a command line tool, you may not need to provide several commands.
-In such case, having to pass the command name each time is tedious. Fortunately,
+In such a case, having to pass the command name each time is tedious. Fortunately,
it is possible to remove this need by declaring a single command application::
#!/usr/bin/env php
register('echo')
- ->addArgument('foo', InputArgument::OPTIONAL, 'The directory')
- ->addOption('bar', null, InputOption::VALUE_REQUIRED)
- ->setCode(function(InputInterface $input, OutputInterface $output) {
- // output arguments and options
- })
- ->getApplication()
- ->setDefaultCommand('echo', true) // Single command application
+ use Symfony\Component\Console\SingleCommandApplication;
+
+ (new SingleCommandApplication())
+ ->setName('My Super Command') // Optional
+ ->setVersion('1.0.0') // Optional
+ ->addArgument('foo', InputArgument::OPTIONAL, 'The directory')
+ ->addOption('bar', null, InputOption::VALUE_REQUIRED)
+ ->setCode(function (InputInterface $input, OutputInterface $output): int {
+ // output arguments and options
+ })
->run();
-The method :method:`Symfony\\Component\\Console\\Application::setDefaultCommand`
-accepts a boolean as second parameter. If true, the command ``echo`` will then
-always be used, without having to pass its name.
-
You can still register a command as usual::
#!/usr/bin/env php
@@ -49,3 +41,7 @@ You can still register a command as usual::
$application->setDefaultCommand($command->getName(), true);
$application->run();
+
+The :method:`Symfony\\Component\\Console\\Application::setDefaultCommand` method
+accepts a boolean as second parameter. If true, the command ``echo`` will then
+always be used, without having to pass its name.
diff --git a/components/console/usage.rst b/components/console/usage.rst
index e3a6601eec5..591994948b8 100644
--- a/components/console/usage.rst
+++ b/components/console/usage.rst
@@ -1,6 +1,3 @@
-.. index::
- single: Console; Usage
-
Using Console Commands, Shortcuts and Built-in Commands
=======================================================
@@ -68,9 +65,17 @@ You can suppress output with:
.. code-block:: terminal
+ # suppresses all output, including errors
+ $ php application.php list --silent
+
+ # suppresses all output except errors
$ php application.php list --quiet
$ php application.php list -q
+.. versionadded:: 7.2
+
+ The ``--silent`` option was introduced in Symfony 7.2.
+
You can get more verbose messages (if this is supported for a command)
with:
@@ -107,7 +112,7 @@ If you do not provide a console name then it will just output:
.. code-block:: text
- console tool
+ Console Tool
You can force turning on ANSI output coloring with:
diff --git a/components/contracts.rst b/components/contracts.rst
index 4f84c5f2935..56b0394397d 100644
--- a/components/contracts.rst
+++ b/components/contracts.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Contracts
- single: Components; Contracts
-
The Contracts Component
=======================
@@ -19,6 +15,7 @@ your projects really need:
$ composer require symfony/cache-contracts
$ composer require symfony/event-dispatcher-contracts
+ $ composer require symfony/deprecation-contracts
$ composer require symfony/http-client-contracts
$ composer require symfony/service-contracts
$ composer require symfony/translation-contracts
@@ -60,7 +57,7 @@ convention. For example:
{
"...": "...",
"provide": {
- "symfony/cache-implementation": "1.0"
+ "symfony/cache-implementation": "3.0"
}
}
diff --git a/components/css_selector.rst b/components/css_selector.rst
index e4a792a807c..1331a11e616 100644
--- a/components/css_selector.rst
+++ b/components/css_selector.rst
@@ -1,11 +1,7 @@
-.. index::
- single: CssSelector
- single: Components; CssSelector
-
The CssSelector Component
=========================
- The CssSelector component converts CSS selectors to XPath expressions.
+ The CssSelector component converts CSS selectors to `XPath`_ expressions.
Installation
------------
@@ -25,11 +21,11 @@ Usage
component in any PHP application. Read the :ref:`Symfony Functional Tests `
article to learn about how to use it when creating Symfony tests.
-Why to Use CSS selectors?
-~~~~~~~~~~~~~~~~~~~~~~~~~
+Why Use CSS selectors?
+~~~~~~~~~~~~~~~~~~~~~~
When you're parsing an HTML or an XML document, by far the most powerful
-method is XPath.
+method is `XPath`_.
XPath expressions are incredibly flexible, so there is almost always an
XPath expression that will find the element you need. Unfortunately, they
@@ -40,7 +36,7 @@ long and unwieldy expressions.
Many developers -- particularly web developers -- are more comfortable
using CSS selectors to find elements. As well as working in stylesheets,
CSS selectors are used in JavaScript with the ``querySelectorAll()`` function
-and in popular JavaScript libraries such as jQuery, Prototype and MooTools.
+and in popular JavaScript libraries such as jQuery.
CSS selectors are less powerful than XPath, but far easier to write, read
and understand. Since they are less powerful, almost all CSS selectors can
@@ -77,7 +73,7 @@ You can use this expression with, for instance, :phpclass:`DOMXPath` or
Limitations of the CssSelector Component
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Not all CSS selectors can be converted to XPath equivalents.
+Not all CSS selectors can be converted to `XPath`_ equivalents.
There are several CSS selectors that only make sense in the context of a
web-browser.
@@ -96,10 +92,16 @@ Pseudo-classes are partially supported:
* Not supported: ``*:first-of-type``, ``*:last-of-type``, ``*:nth-of-type`` and
``*:nth-last-of-type`` (all these work with an element name (e.g.
``li:first-of-type``) but not with the ``*`` selector).
-* Supported: ``*:only-of-type``.
+* Supported: ``*:only-of-type``, ``*:scope``, ``*:is`` and ``*:where``.
+
+.. versionadded:: 7.1
+
+ The support for ``*:is`` and ``*:where`` was introduced in Symfony 7.1.
Learn more
----------
* :doc:`/testing`
* :doc:`/components/dom_crawler`
+
+.. _`XPath`: https://en.wikipedia.org/wiki/XPath
diff --git a/components/dependency_injection.rst b/components/dependency_injection.rst
index 3213ed12513..d146f553a0c 100644
--- a/components/dependency_injection.rst
+++ b/components/dependency_injection.rst
@@ -1,7 +1,3 @@
-.. index::
- single: DependencyInjection
- single: Components; DependencyInjection
-
The DependencyInjection Component
=================================
@@ -35,7 +31,7 @@ you want to make available as a service::
class Mailer
{
- private $transport;
+ private string $transport;
public function __construct()
{
@@ -49,8 +45,8 @@ You can register this in the container as a service::
use Symfony\Component\DependencyInjection\ContainerBuilder;
- $containerBuilder = new ContainerBuilder();
- $containerBuilder->register('mailer', 'Mailer');
+ $container = new ContainerBuilder();
+ $container->register('mailer', 'Mailer');
An improvement to the class to make it more flexible would be to allow
the container to set the ``transport`` used. If you change the class
@@ -58,11 +54,9 @@ so this is passed into the constructor::
class Mailer
{
- private $transport;
-
- public function __construct($transport)
- {
- $this->transport = $transport;
+ public function __construct(
+ private string $transport,
+ ) {
}
// ...
@@ -72,8 +66,8 @@ Then you can set the choice of transport in the container::
use Symfony\Component\DependencyInjection\ContainerBuilder;
- $containerBuilder = new ContainerBuilder();
- $containerBuilder
+ $container = new ContainerBuilder();
+ $container
->register('mailer', 'Mailer')
->addArgument('sendmail');
@@ -87,9 +81,9 @@ the ``Mailer`` service's constructor argument::
use Symfony\Component\DependencyInjection\ContainerBuilder;
- $containerBuilder = new ContainerBuilder();
- $containerBuilder->setParameter('mailer.transport', 'sendmail');
- $containerBuilder
+ $container = new ContainerBuilder();
+ $container->setParameter('mailer.transport', 'sendmail');
+ $container
->register('mailer', 'Mailer')
->addArgument('%mailer.transport%');
@@ -99,11 +93,9 @@ like this::
class NewsletterManager
{
- private $mailer;
-
- public function __construct(\Mailer $mailer)
- {
- $this->mailer = $mailer;
+ public function __construct(
+ private \Mailer $mailer,
+ ) {
}
// ...
@@ -116,14 +108,14 @@ not exist yet. Use the ``Reference`` class to tell the container to inject the
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
- $containerBuilder = new ContainerBuilder();
+ $container = new ContainerBuilder();
- $containerBuilder->setParameter('mailer.transport', 'sendmail');
- $containerBuilder
+ $container->setParameter('mailer.transport', 'sendmail');
+ $container
->register('mailer', 'Mailer')
->addArgument('%mailer.transport%');
- $containerBuilder
+ $container
->register('newsletter_manager', 'NewsletterManager')
->addArgument(new Reference('mailer'));
@@ -132,9 +124,9 @@ it was only optional then you could use setter injection instead::
class NewsletterManager
{
- private $mailer;
+ private \Mailer $mailer;
- public function setMailer(\Mailer $mailer)
+ public function setMailer(\Mailer $mailer): void
{
$this->mailer = $mailer;
}
@@ -148,14 +140,14 @@ If you do want to though then the container can call the setter method::
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
- $containerBuilder = new ContainerBuilder();
+ $container = new ContainerBuilder();
- $containerBuilder->setParameter('mailer.transport', 'sendmail');
- $containerBuilder
+ $container->setParameter('mailer.transport', 'sendmail');
+ $container
->register('mailer', 'Mailer')
->addArgument('%mailer.transport%');
- $containerBuilder
+ $container
->register('newsletter_manager', 'NewsletterManager')
->addMethodCall('setMailer', [new Reference('mailer')]);
@@ -164,11 +156,40 @@ like this::
use Symfony\Component\DependencyInjection\ContainerBuilder;
+ $container = new ContainerBuilder();
+
+ // ...
+
+ $newsletterManager = $container->get('newsletter_manager');
+
+Getting Services That Don't Exist
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+By default, when you try to get a service that doesn't exist, you see an exception.
+You can override this behavior as follows::
+
+ use Symfony\Component\DependencyInjection\ContainerBuilder;
+ use Symfony\Component\DependencyInjection\ContainerInterface;
+
$containerBuilder = new ContainerBuilder();
// ...
- $newsletterManager = $containerBuilder->get('newsletter_manager');
+ // the second argument is optional and defines what to do when the service doesn't exist
+ $newsletterManager = $containerBuilder->get('newsletter_manager', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
+
+These are all the possible behaviors:
+
+* ``ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE``: throws an exception
+ at compile time (this is the **default** behavior);
+* ``ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE``: throws an
+ exception at runtime, when trying to access the missing service;
+* ``ContainerInterface::NULL_ON_INVALID_REFERENCE``: returns ``null``;
+* ``ContainerInterface::IGNORE_ON_INVALID_REFERENCE``: ignores the wrapping
+ command asking for the reference (for instance, ignore a setter if the service
+ does not exist);
+* ``ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE``: ignores/returns
+ ``null`` for uninitialized services or invalid references.
Avoiding your Code Becoming Dependent on the Container
------------------------------------------------------
@@ -202,8 +223,8 @@ Loading an XML config file::
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
- $containerBuilder = new ContainerBuilder();
- $loader = new XmlFileLoader($containerBuilder, new FileLocator(__DIR__));
+ $container = new ContainerBuilder();
+ $loader = new XmlFileLoader($container, new FileLocator(__DIR__));
$loader->load('services.xml');
Loading a YAML config file::
@@ -212,8 +233,8 @@ Loading a YAML config file::
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
- $containerBuilder = new ContainerBuilder();
- $loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__));
+ $container = new ContainerBuilder();
+ $loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$loader->load('services.yaml');
.. note::
@@ -237,8 +258,8 @@ into a separate config file and load it in a similar way::
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
- $containerBuilder = new ContainerBuilder();
- $loader = new PhpFileLoader($containerBuilder, new FileLocator(__DIR__));
+ $container = new ContainerBuilder();
+ $loader = new PhpFileLoader($container, new FileLocator(__DIR__));
$loader->load('services.php');
You can now set up the ``newsletter_manager`` and ``mailer`` services using
@@ -266,8 +287,9 @@ config files:
-
+ xsi:schemaLocation="http://symfony.com/schema/dic/services
+ https://symfony.com/schema/dic/services/services-1.0.xsd"
+ >
sendmail
@@ -290,24 +312,26 @@ config files:
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
- return function(ContainerConfigurator $configurator) {
- $configurator->parameters()
+ return static function (ContainerConfigurator $container): void {
+ $container->parameters()
// ...
->set('mailer.transport', 'sendmail')
;
- $services = $configurator->services();
-
+ $services = $container->services();
$services->set('mailer', 'Mailer')
->args(['%mailer.transport%'])
;
+ $services->set('mailer', 'Mailer')
+ ->args([param('mailer.transport')])
+ ;
+
$services->set('newsletter_manager', 'NewsletterManager')
- ->call('setMailer', [ref('mailer')])
+ ->call('setMailer', [service('mailer')])
;
};
-
Learn More
----------
@@ -318,4 +342,4 @@ Learn More
/components/dependency_injection/*
/service_container/*
-.. _`PSR-11`: http://www.php-fig.org/psr/psr-11/
+.. _`PSR-11`: https://www.php-fig.org/psr/psr-11/
diff --git a/components/dependency_injection/_imports-parameters-note.rst.inc b/components/dependency_injection/_imports-parameters-note.rst.inc
index 92868df1985..1389ca78fe3 100644
--- a/components/dependency_injection/_imports-parameters-note.rst.inc
+++ b/components/dependency_injection/_imports-parameters-note.rst.inc
@@ -2,7 +2,7 @@
Due to the way in which parameters are resolved, you cannot use them
to build paths in imports dynamically. This means that something like
- the following doesn't work:
+ **the following does not work:**
.. configuration-block::
@@ -19,8 +19,8 @@
-
+ https://symfony.com/schema/dic/services/services-1.0.xsd"
+ >
@@ -29,4 +29,8 @@
.. code-block:: php
// config/services.php
- $loader->import('%kernel.project_dir%/somefile.yaml');
+ namespace Symfony\Component\DependencyInjection\Loader\Configurator;
+
+ return static function (ContainerConfigurator $container): void {
+ $container->import('%kernel.project_dir%/somefile.yaml');
+ };
diff --git a/components/dependency_injection/compilation.rst b/components/dependency_injection/compilation.rst
index a68acf8f854..7f991e85b72 100644
--- a/components/dependency_injection/compilation.rst
+++ b/components/dependency_injection/compilation.rst
@@ -1,6 +1,3 @@
-.. index::
- single: DependencyInjection; Compilation
-
Compiling the Container
=======================
@@ -64,7 +61,7 @@ A very simple extension may just load configuration files into the container::
class AcmeDemoExtension implements ExtensionInterface
{
- public function load(array $configs, ContainerBuilder $container)
+ public function load(array $configs, ContainerBuilder $container): void
{
$loader = new XmlFileLoader(
$container,
@@ -93,7 +90,7 @@ The Extension must specify a ``getAlias()`` method to implement the interface::
{
// ...
- public function getAlias()
+ public function getAlias(): string
{
return 'acme_demo';
}
@@ -117,14 +114,14 @@ are loaded::
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
- $containerBuilder = new ContainerBuilder();
- $containerBuilder->registerExtension(new AcmeDemoExtension);
+ $container = new ContainerBuilder();
+ $container->registerExtension(new AcmeDemoExtension);
- $loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__));
+ $loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$loader->load('config.yaml');
// ...
- $containerBuilder->compile();
+ $container->compile();
.. note::
@@ -135,7 +132,7 @@ are loaded::
The values from those sections of the config files are passed into the first
argument of the ``load()`` method of the extension::
- public function load(array $configs, ContainerBuilder $container)
+ public function load(array $configs, ContainerBuilder $container): void
{
$foo = $configs[0]['foo']; //fooValue
$bar = $configs[0]['bar']; //barValue
@@ -153,7 +150,7 @@ will look like this::
],
]
-Whilst you can manually manage merging the different files, it is much better
+While you can manually manage merging the different files, it is much better
to use :doc:`the Config component ` to
merge and validate the config values. Using the configuration processing
you could access the config value this way::
@@ -161,7 +158,7 @@ you could access the config value this way::
use Symfony\Component\Config\Definition\Processor;
// ...
- public function load(array $configs, ContainerBuilder $container)
+ public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$processor = new Processor();
@@ -178,12 +175,12 @@ namespace so that the relevant parts of an XML config file are passed to
the extension. The other to specify the base path to XSD files to validate
the XML configuration::
- public function getXsdValidationBasePath()
+ public function getXsdValidationBasePath(): string
{
return __DIR__.'/../Resources/config/';
}
- public function getNamespace()
+ public function getNamespace(): string
{
return 'http://www.example.com/symfony/schema/';
}
@@ -197,16 +194,19 @@ The XML version of the config would then look like this:
.. code-block:: xml
-
+
-
-
+ xmlns:acme-demo="http://www.example.com/schema/dic/acme_demo"
+ xsi:schemaLocation="http://symfony.com/schema/dic/services
+ https://symfony.com/schema/dic/services/services-1.0.xsd
+ http://www.example.com/schema/dic/acme_demo
+ https://www.example.com/schema/dic/acme_demo/acme_demo-1.0.xsd"
+ >
+
fooValue
barValue
-
+
.. note::
@@ -219,7 +219,7 @@ The processed config value can now be added as container parameters as if
it were listed in a ``parameters`` section of the config file but with the
additional benefit of merging multiple files and validation of the configuration::
- public function load(array $configs, ContainerBuilder $container)
+ public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$processor = new Processor();
@@ -234,7 +234,7 @@ More complex configuration requirements can be catered for in the Extension
classes. For example, you may choose to load a main service configuration
file but also load a secondary one only if a certain parameter is set::
- public function load(array $configs, ContainerBuilder $container)
+ public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$processor = new Processor();
@@ -251,6 +251,33 @@ file but also load a secondary one only if a certain parameter is set::
}
}
+You can also deprecate container parameters in your extension to warn users
+about not using them anymore. This helps with the migration across major versions
+of an extension.
+
+Deprecation is only possible when using PHP to configure the extension, not when
+using XML or YAML. Use the ``ContainerBuilder::deprecateParameter()`` method to
+provide the deprecation details::
+
+ public function load(array $configs, ContainerBuilder $containerBuilder)
+ {
+ // ...
+
+ $containerBuilder->setParameter('acme_demo.database_user', $configs['db_user']);
+
+ $containerBuilder->deprecateParameter(
+ 'acme_demo.database_user',
+ 'acme/database-package',
+ '1.3',
+ // optionally you can set a custom deprecation message
+ '"acme_demo.database_user" is deprecated, you should configure database credentials with the "acme_demo.database_dsn" parameter instead.'
+ );
+ }
+
+The parameter being deprecated must be set before being declared as deprecated.
+Otherwise a :class:`Symfony\\Component\\DependencyInjection\\Exception\\ParameterNotFoundException`
+exception will be thrown.
+
.. note::
Just registering an extension with the container is not enough to get
@@ -263,11 +290,11 @@ file but also load a secondary one only if a certain parameter is set::
use Symfony\Component\DependencyInjection\ContainerBuilder;
- $containerBuilder = new ContainerBuilder();
+ $container = new ContainerBuilder();
$extension = new AcmeDemoExtension();
- $containerBuilder->registerExtension($extension);
- $containerBuilder->loadFromExtension($extension->getAlias());
- $containerBuilder->compile();
+ $container->registerExtension($extension);
+ $container->loadFromExtension($extension->getAlias());
+ $container->compile();
.. note::
@@ -292,7 +319,7 @@ method is called by implementing
{
// ...
- public function prepend(ContainerBuilder $container)
+ public function prepend(ContainerBuilder $container): void
{
// ...
@@ -323,7 +350,7 @@ compilation::
class AcmeDemoExtension implements ExtensionInterface, CompilerPassInterface
{
- public function process(ContainerBuilder $container)
+ public function process(ContainerBuilder $container): void
{
// ... do something during the compilation
}
@@ -341,7 +368,7 @@ methods described in :doc:`/service_container/definitions`.
.. note::
Please note that the ``process()`` method in the extension class is
- called during the optimization step. You can read
+ called during the ``PassConfig::TYPE_BEFORE_OPTIMIZATION`` step. You can read
:ref:`the next section ` if you
need to edit the container during another step.
@@ -358,8 +385,8 @@ methods described in :doc:`/service_container/definitions`.
method call if some required service is not available.
A common use-case of compiler passes is to search for all service definitions
-that have a certain tag in order to process dynamically plug each into some
-other service. See the section on :ref:`service tags `
+that have a certain tag, in order to dynamically plug each one into other services.
+See the section on :ref:`service tags `
for an example.
.. _components-di-separate-compiler-passes:
@@ -377,7 +404,7 @@ class implementing the ``CompilerPassInterface``::
class CustomPass implements CompilerPassInterface
{
- public function process(ContainerBuilder $container)
+ public function process(ContainerBuilder $container): void
{
// ... do something during the compilation
}
@@ -387,8 +414,8 @@ You then need to register your custom pass with the container::
use Symfony\Component\DependencyInjection\ContainerBuilder;
- $containerBuilder = new ContainerBuilder();
- $containerBuilder->addCompilerPass(new CustomPass());
+ $container = new ContainerBuilder();
+ $container->addCompilerPass(new CustomPass());
.. note::
@@ -418,7 +445,7 @@ For example, to run your custom pass after the default removal passes have
been run, use::
// ...
- $containerBuilder->addCompilerPass(
+ $container->addCompilerPass(
new CustomPass(),
PassConfig::TYPE_AFTER_REMOVING
);
@@ -460,14 +487,22 @@ serves at dumping the compiled container::
require_once $file;
$container = new ProjectServiceContainer();
} else {
- $containerBuilder = new ContainerBuilder();
+ $container = new ContainerBuilder();
// ...
- $containerBuilder->compile();
+ $container->compile();
- $dumper = new PhpDumper($containerBuilder);
+ $dumper = new PhpDumper($container);
file_put_contents($file, $dumper->dump());
}
+.. tip::
+
+ The ``file_put_contents()`` function is not atomic. That could cause issues
+ in a production environment with multiple concurrent requests. Instead, use
+ the :ref:`dumpFile() method ` from Symfony Filesystem
+ component or other methods provided by Symfony (e.g. ``$containerConfigCache->write()``)
+ which are atomic.
+
``ProjectServiceContainer`` is the default name given to the dumped container
class. However, you can change this with the ``class`` option when you
dump it::
@@ -479,11 +514,11 @@ dump it::
require_once $file;
$container = new MyCachedContainer();
} else {
- $containerBuilder = new ContainerBuilder();
+ $container = new ContainerBuilder();
// ...
- $containerBuilder->compile();
+ $container->compile();
- $dumper = new PhpDumper($containerBuilder);
+ $dumper = new PhpDumper($container);
file_put_contents(
$file,
$dumper->dump(['class' => 'MyCachedContainer'])
@@ -511,12 +546,12 @@ application::
require_once $file;
$container = new MyCachedContainer();
} else {
- $containerBuilder = new ContainerBuilder();
+ $container = new ContainerBuilder();
// ...
- $containerBuilder->compile();
+ $container->compile();
if (!$isDebug) {
- $dumper = new PhpDumper($containerBuilder);
+ $dumper = new PhpDumper($container);
file_put_contents(
$file,
$dumper->dump(['class' => 'MyCachedContainer'])
@@ -546,14 +581,14 @@ for these resources and use them as metadata for the cache::
$containerConfigCache = new ConfigCache($file, $isDebug);
if (!$containerConfigCache->isFresh()) {
- $containerBuilder = new ContainerBuilder();
+ $container = new ContainerBuilder();
// ...
- $containerBuilder->compile();
+ $container->compile();
- $dumper = new PhpDumper($containerBuilder);
+ $dumper = new PhpDumper($container);
$containerConfigCache->write(
$dumper->dump(['class' => 'MyCachedContainer']),
- $containerBuilder->getResources()
+ $container->getResources()
);
}
@@ -564,8 +599,8 @@ Now the cached dumped container is used regardless of whether debug mode
is on or not. The difference is that the ``ConfigCache`` is set to debug
mode with its second constructor argument. When the cache is not in debug
mode the cached container will always be used if it exists. In debug mode,
-an additional metadata file is written with the timestamps of all the resource
-files. These are then checked to see if the files have changed, if they
+an additional metadata file is written with all the involved resource
+files. These are then checked to see if their timestamps have changed, if they
have the cache will be considered stale.
.. note::
diff --git a/components/dependency_injection/workflow.rst b/components/dependency_injection/workflow.rst
index 750420f4d47..777b41dfabb 100644
--- a/components/dependency_injection/workflow.rst
+++ b/components/dependency_injection/workflow.rst
@@ -1,6 +1,3 @@
-.. index::
- single: DependencyInjection; Workflow
-
Container Building Workflow
===========================
@@ -21,11 +18,11 @@ Working with a Cached Container
-------------------------------
Before building it, the kernel checks to see if a cached version of the
-container exists. The HttpKernel has a debug setting and if this is false,
+container exists. The kernel has a debug setting and if this is false,
the cached version is used if it exists. If debug is true then the kernel
:doc:`checks to see if configuration is fresh `
and if it is, the cached version of the container is used. If not then the
-container is built from the application-level configuration and the bundles's
+container is built from the application-level configuration and the bundles'
extension configuration.
Read :ref:`Dumping the Configuration for Performance `
diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst
index aa395f44255..630d301302a 100644
--- a/components/dom_crawler.rst
+++ b/components/dom_crawler.rst
@@ -1,7 +1,3 @@
-.. index::
- single: DomCrawler
- single: Components; DomCrawler
-
The DomCrawler Component
========================
@@ -70,13 +66,6 @@ tree.
isn't meant to dump content, you can see the "fixed" version of your HTML
by :ref:`dumping it `.
-.. note::
-
- If you need better support for HTML5 contents or want to get rid of the
- inconsistencies of PHP's DOM extension, install the `html5-php library`_.
- The DomCrawler component will use it automatically when the content has
- an HTML5 doctype.
-
Node Filtering
~~~~~~~~~~~~~~
@@ -88,8 +77,8 @@ Using XPath expressions, you can select specific nodes within the document::
``DOMXPath::query`` is used internally to actually perform an XPath query.
-If you prefer CSS selectors over XPath, install the CssSelector component.
-It allows you to use jQuery-like selectors to traverse::
+If you prefer CSS selectors over XPath, install :doc:`/components/css_selector`.
+It allows you to use jQuery-like selectors::
$crawler = $crawler->filter('body > p');
@@ -100,17 +89,18 @@ An anonymous function can be used to filter with more complex criteria::
$crawler = $crawler
->filter('body > p')
- ->reduce(function (Crawler $node, $i) {
+ ->reduce(function (Crawler $node, $i): bool {
// filters every other node
- return ($i % 2) == 0;
+ return ($i % 2) === 0;
});
-To remove a node the anonymous function must return false.
+To remove a node, the anonymous function must return ``false``.
.. note::
All filter methods return a new :class:`Symfony\\Component\\DomCrawler\\Crawler`
- instance with filtered content.
+ instance with the filtered content. To check if the filter actually
+ found something, use ``$crawler->count() > 0`` on this new crawler.
Both the :method:`Symfony\\Component\\DomCrawler\\Crawler::filterXPath` and
:method:`Symfony\\Component\\DomCrawler\\Crawler::filter` methods work with
@@ -121,7 +111,7 @@ Consider the XML below:
.. code-block:: xml
-
+
filter('body > p')->nextAll();
$crawler->filter('body > p')->previousAll();
-Get all the child or parent nodes::
+Get all the child or ancestor nodes::
$crawler->filter('body')->children();
- $crawler->filter('body > p')->parents();
+ $crawler->filter('body > p')->ancestors();
Get all the direct child nodes matching a CSS selector::
@@ -220,14 +210,36 @@ Access the value of the first node of the current selection::
// avoid the exception passing an argument that text() returns when node does not exist
$message = $crawler->filterXPath('//body/p')->text('Default text content');
- // pass TRUE as the second argument of text() to remove all extra white spaces, including
- // the internal ones (e.g. " foo\n bar baz \n " is returned as "foo bar baz")
- $crawler->filterXPath('//body/p')->text('Default text content', true);
+ // by default, text() trims whitespace characters, including the internal ones
+ // (e.g. " foo\n bar baz \n " is returned as "foo bar baz")
+ // pass FALSE as the second argument to return the original text unchanged
+ $crawler->filterXPath('//body/p')->text('Default text content', false);
+
+ // innerText() is similar to text() but returns only text that is a direct
+ // descendant of the current node, excluding text from child nodes
+ $text = $crawler->filterXPath('//body/p')->innerText();
+ // if content is Foo Bar
or Bar Foo
+ // innerText() returns 'Foo' in both cases; and text() returns 'Foo Bar' and 'Bar Foo' respectively
+
+ // if there are multiple text nodes, between other child nodes, like
+ // Foo Bar Baz
+ // innerText() returns only the first text node 'Foo'
+
+ // like text(), innerText() also trims whitespace characters by default,
+ // but you can get the unchanged text by passing FALSE as argument
+ $text = $crawler->filterXPath('//body/p')->innerText(false);
Access the attribute value of the first node of the current selection::
$class = $crawler->filterXPath('//body/p')->attr('class');
+.. tip::
+
+ You can define the default value to use if the node or attribute is empty
+ by using the second argument of the ``attr()`` method::
+
+ $class = $crawler->filterXPath('//body/p')->attr('class', 'my-default-class');
+
Extract attribute and/or node values from the list of nodes::
$attributes = $crawler
@@ -245,7 +257,7 @@ Call an anonymous function on each node of the list::
use Symfony\Component\DomCrawler\Crawler;
// ...
- $nodeValues = $crawler->filter('p')->each(function (Crawler $node, $i) {
+ $nodeValues = $crawler->filter('p')->each(function (Crawler $node, $i): string {
return $node->text();
});
@@ -255,7 +267,7 @@ The result is an array of values returned by the anonymous function calls.
When using nested crawler, beware that ``filterXPath()`` is evaluated in the
context of the crawler::
- $crawler->filterXPath('parent')->each(function (Crawler $parentCrawler, $i) {
+ $crawler->filterXPath('parent')->each(function (Crawler $parentCrawler, $i): void {
// DON'T DO THIS: direct child can not be found
$subCrawler = $parentCrawler->filterXPath('sub-tag/sub-child-tag');
@@ -267,7 +279,9 @@ context of the crawler::
Adding the Content
~~~~~~~~~~~~~~~~~~
-The crawler supports multiple ways of adding the content::
+The crawler supports multiple ways of adding the content, but they are mutually
+exclusive, so you can only use one of them to add content (e.g. if you pass the
+content to the ``Crawler`` constructor, you can't call ``addContent()`` later)::
$crawler = new Crawler(' ');
@@ -516,15 +530,17 @@ You can virtually set and get values on the form::
// where "registration" is its own array
$values = $form->getPhpValues();
-To work with multi-dimensional fields::
+To work with multi-dimensional fields:
+
+.. code-block:: html
Pass an array of values::
@@ -582,15 +598,18 @@ of the information you need to create a POST request for the form::
// now use some HTTP client and post using this information
-One great example of an integrated system that uses all of this is `Goutte`_.
-Goutte understands the Symfony Crawler object and can use it to submit forms
+One great example of an integrated system that uses all of this is
+the :class:`Symfony\\Component\\BrowserKit\\HttpBrowser` provided by
+the :doc:`BrowserKit component `.
+It understands the Symfony Crawler object and can use it to submit forms
directly::
- use Goutte\Client;
+ use Symfony\Component\BrowserKit\HttpBrowser;
+ use Symfony\Component\HttpClient\HttpClient;
// makes a real request to an external site
- $client = new Client();
- $crawler = $client->request('GET', 'https://github.com/login');
+ $browser = new HttpBrowser(HttpClient::create());
+ $crawler = $browser->request('GET', 'https://github.com/login');
// select the form and fill in some values
$form = $crawler->selectButton('Sign in')->form();
@@ -598,7 +617,7 @@ directly::
$form['password'] = 'anypass';
// submits the given form
- $crawler = $client->submit($form);
+ $crawler = $browser->submit($form);
.. _components-dom-crawler-invalid:
@@ -617,11 +636,36 @@ the whole form or specific field(s)::
$form->disableValidation();
$form['country']->select('Invalid value');
+Resolving a URI
+~~~~~~~~~~~~~~~
+
+The :class:`Symfony\\Component\\DomCrawler\\UriResolver` class takes a URI
+(relative, absolute, fragment, etc.) and turns it into an absolute URI against
+another given base URI::
+
+ use Symfony\Component\DomCrawler\UriResolver;
+
+ UriResolver::resolve('/foo', 'http://localhost/bar/foo/'); // http://localhost/foo
+ UriResolver::resolve('?a=b', 'http://localhost/bar#foo'); // http://localhost/bar?a=b
+ UriResolver::resolve('../../', 'http://localhost/'); // http://localhost/
+
+Using a HTML5 Parser
+~~~~~~~~~~~~~~~~~~~~
+
+If you need the :class:`Symfony\\Component\\DomCrawler\\Crawler` to use an HTML5
+parser, set its ``useHtml5Parser`` constructor argument to ``true``::
+
+ use Symfony\Component\DomCrawler\Crawler;
+
+ $crawler = new Crawler(null, $uri, useHtml5Parser: true);
+
+By doing so, the crawler will use the HTML5 parser provided by the `masterminds/html5`_
+library to parse the documents.
+
Learn more
----------
* :doc:`/testing`
* :doc:`/components/css_selector`
-.. _`Goutte`: https://github.com/FriendsOfPHP/Goutte
-.. _`html5-php library`: https://github.com/Masterminds/html5-php
+.. _`masterminds/html5`: https://packagist.org/packages/masterminds/html5
diff --git a/components/dotenv.rst b/components/dotenv.rst
deleted file mode 100644
index 8fd627955ec..00000000000
--- a/components/dotenv.rst
+++ /dev/null
@@ -1,165 +0,0 @@
-.. index::
- single: Dotenv
- single: Components; Dotenv
-
-The Dotenv Component
-====================
-
- The Dotenv Component parses ``.env`` files to make environment variables
- stored in them accessible via ``$_ENV`` or ``$_SERVER``.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/dotenv
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Sensitive information and environment-dependent settings should be defined as
-environment variables (as recommended for `twelve-factor applications`_). Using
-a ``.env`` file to store those environment variables eases development and CI
-management by keeping them in one "standard" place and agnostic of the
-technology stack you are using (Nginx vs PHP built-in server for instance).
-
-.. note::
-
- PHP has a lot of different implementations of this "pattern". This
- implementation's goal is to replicate what ``source .env`` would do. It
- tries to be as similar as possible with the standard shell's behavior (so
- no value validation for instance).
-
-Load a ``.env`` file in your PHP application via ``Dotenv::load()``::
-
- use Symfony\Component\Dotenv\Dotenv;
-
- $dotenv = new Dotenv();
- $dotenv->load(__DIR__.'/.env');
-
- // You can also load several files
- $dotenv->load(__DIR__.'/.env', __DIR__.'/.env.dev');
-
-Given the following ``.env`` file content:
-
-.. code-block:: terminal
-
- # .env
- DB_USER=root
- DB_PASS=pass
-
-Access the value with ``$_ENV`` in your code::
-
- $dbUser = $_ENV['DB_USER'];
- // you can also use ``$_SERVER``
-
-The ``load()`` method never overwrites existing environment variables. Use the
-``overload()`` method if you need to overwrite them::
-
- // ...
- $dotenv->overload(__DIR__.'/.env');
-
-As you're working with the Dotenv component you'll notice that you might want
-to have different files depending on the environment you're working in. Typically
-this happens for local development or Continuous Integration where you might
-want to have different files for your ``test`` and ``dev`` environments.
-
-You can use ``Dotenv::loadEnv()`` to ease this process::
-
- use Symfony\Component\Dotenv\Dotenv;
-
- $dotenv = new Dotenv();
- $dotenv->loadEnv(__DIR__.'/.env');
-
-The Dotenv component will then look for the correct ``.env`` file to load
-in the following order whereas the files loaded later override the variables
-defined in previously loaded files:
-
-#. If ``.env`` exists, it is loaded first. In case there's no ``.env`` file but a
- ``.env.dist``, this one will be loaded instead.
-#. If one of the previously mentioned files contains the ``APP_ENV`` variable, the
- variable is populated and used to load environment-specific files hereafter. If
- ``APP_ENV`` is not defined in either of the previously mentioned files, ``dev`` is
- assumed for ``APP_ENV`` and populated by default.
-#. If there's a ``.env.local`` representing general local environment variables it's loaded now.
-#. If there's a ``.env.$env.local`` file, this one is loaded. Otherwise, it falls
- back to ``.env.$env``.
-
-This might look complicated at first glance but it gives you the opportunity to
-commit multiple environment-specific files that can then be adjusted to your
-local environment. Given you commit ``.env``, ``.env.test`` and ``.env.dev`` to
-represent different configuration settings for your environments, each of them
-can be adjusted by using ``.env.local``, ``.env.test.local`` and
-``.env.dev.local`` respectively.
-
-.. note::
-
- ``.env.local`` is always ignored in ``test`` environment because tests should produce the
- same results for everyone.
-
-You can adjust the variable defining the environment, default environment and test
-environments by passing them as additional arguments to ``Dotenv::loadEnv()``
-(see :method:`Symfony\\Component\\Dotenv\\Dotenv::loadEnv` for details).
-
-You should never store a ``.env.local`` file in your code repository as it might
-contain sensitive information; create a ``.env`` file (or multiple
-environment-specific ones as shown above) with sensible defaults instead.
-
-.. note::
-
- Symfony Dotenv can be used in any environment of your application:
- development, testing, staging and even production. However, in production
- it's recommended to configure real environment variables to avoid the
- performance overhead of parsing the ``.env`` file for every request.
-
-As a ``.env`` file is a regular shell script, you can ``source`` it in your own
-shell scripts:
-
-.. code-block:: terminal
-
- source .env
-
-Add comments by prefixing them with ``#``:
-
-.. code-block:: terminal
-
- # Database credentials
- DB_USER=root
- DB_PASS=pass # This is the secret password
-
-Use environment variables in values by prefixing variables with ``$``:
-
-.. code-block:: terminal
-
- DB_USER=root
- DB_PASS=${DB_USER}pass # Include the user as a password prefix
-
-.. note::
-
- The order is important when some env var depends on the value of other env
- vars. In the above example, ``DB_PASS`` must be defined after ``DB_USER``.
- Moreover, if you define multiple ``.env`` files and put ``DB_PASS`` first,
- its value will depend on the ``DB_USER`` value defined in other files
- instead of the value defined in this file.
-
-Define a default value in case the environment variable is not set:
-
-.. code-block:: terminal
-
- DB_USER=
- DB_PASS=${DB_USER:-root}pass # results in DB_PASS=rootpass
-
-Embed commands via ``$()`` (not supported on Windows):
-
-.. code-block:: terminal
-
- START_TIME=$(date)
-
-.. note::
-
- Note that using ``$()`` might not work depending on your shell.
-
-.. _twelve-factor applications: http://www.12factor.net/
diff --git a/components/error_handler.rst b/components/error_handler.rst
deleted file mode 100644
index f5b1e7b9c11..00000000000
--- a/components/error_handler.rst
+++ /dev/null
@@ -1,170 +0,0 @@
-.. index::
- single: Debug
- single: Error
- single: Exception
- single: Components; ErrorHandler
-
-The ErrorHandler Component
-==========================
-
- The ErrorHandler component provides tools to manage errors and ease
- debugging PHP code.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/error-handler
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-The ErrorHandler component provides several tools to help you debug PHP code:
-
-* An **error handler** that turns PHP errors into exceptions;
-* An **exception handler** that turns uncaught PHP exceptions into nice PHP responses;
-* A **debug class loader** that provides better errors when a class is not found.
-
-Call this method (e.g. in your :ref:`front controller `)
-to enable all these features in your application::
-
- // public/index.php
- use Symfony\Component\ErrorHandler\Debug;
-
- if ($_SERVER['APP_DEBUG']) {
- Debug::enable();
- }
-
- // ...
-
-Keep reading this article to learn more about each feature, including how to
-enable each of them separately.
-
-.. caution::
-
- You should never enable the debug tools, except for the error handler, in a
- production environment as they might disclose sensitive information to the user.
-
-Turning PHP Errors into Exceptions
-----------------------------------
-
-The :class:`Symfony\\Component\\ErrorHandler\\ErrorHandler` class catches PHP
-errors and turns them into PHP's :phpclass:`ErrorException` objects, except for
-fatal PHP errors, which are turned into Symfony's
-:class:`Symfony\\Component\\ErrorHandler\\Exception\\FatalErrorException` objects.
-
-If the application uses the FrameworkBundle, this error handler is enabled by
-default in the :ref:`production environment `
-because it generates better error logs.
-
-Use the following code (e.g. in your :ref:`front controller `)
-to enable this error handler::
-
- use Symfony\Component\ErrorHandler\ErrorHandler;
-
- ErrorHandler::register();
-
-.. tip::
-
- If you want to get even better exception pages, install the
- :doc:`ErrorRenderer component ` too.
-
-Catching PHP Function Errors and Turning Them into Exceptions
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Consider the following example::
-
- $data = json_decode(file_get_contents($filename), true);
- $data['read_at'] = date($datetimeFormat);
- file_put_contents($filename, json_encode($data));
-
-Most PHP core functions were written before exception handling was introduced,
-so they return ``false`` or ``null`` in case of error instead of throwing an
-exception. That's why you need to add something like these to check for errors::
-
- $content = @file_get_contents($filename);
- if (false === $content) {
- throw new \RuntimeException('Could not load file.');
- }
-
- // since PHP 7.3 json_decode() defines an option to throw JSON_THROW_ON_ERROR
- // but you need to enable that option explicitly
- $data = @json_decode($content, true);
- if (null === $data) {
- throw new \RuntimeException('File does not contain valid JSON.');
- }
-
- $datetime = @date($datetimeFormat);
- if (false === $datetime) {
- throw new \RuntimeException('Invalid datetime format.');
- }
-
-To simplify this code, the :class:`Symfony\\Component\\ErrorHandler\\ErrorHandler`
-class provides a :method:`Symfony\\Component\\ErrorHandler\\ErrorHandler::call`
-method that throws an exception automatically when a PHP error occurs::
-
- $content = ErrorHandler::call('file_get_contents', $filename);
-
-The first argument of ``call()`` is the name of the PHP function to execute and
-the rest of arguments are passed to the PHP function. The result of the PHP
-function is returned as the result of ``call()``.
-
-You can pass any PHP callable as the first argument of ``call()``, so you can
-wrap several function calls inside an anonymous function::
-
- $data = ErrorHandler::call(static function () use ($filename, $datetimeFormat) {
- // if any code executed inside this anonymous function fails, a PHP exception
- // will be thrown, even if the code uses the '@' PHP silence operator
- $data = json_decode(file_get_contents($filename), true);
- $data['read_at'] = date($datetimeFormat);
- file_put_contents($filename, json_encode($data));
-
- return $data;
- });
-
-Debugging Uncaught PHP Exceptions
----------------------------------
-
-The :class:`Symfony\\Component\\ErrorHandler\\ExceptionHandler` class catches
-uncaught PHP exceptions and turns them into a nice response, so you can debug
-them. It is useful in :ref:`debug mode ` to replace the default
-PHP/XDebug output with something prettier and more useful.
-
-If the :doc:`HttpFoundation component ` is
-available, the handler returns a Symfony's
-:class:`Symfony\\Component\\HttpFoundation\\Response` object. Otherwise, it returns
-a generic PHP response.
-
-Use the following code (e.g. in your :ref:`front controller `)
-to enable this exception handler::
-
- use Symfony\Component\ErrorHandler\ExceptionHandler;
-
- ExceptionHandler::register();
-
-.. tip::
-
- If you want to get even better exception pages, install the
- :doc:`ErrorRenderer component ` too.
-
-.. _component-debug-class-loader:
-
-Class Loading Debugger
-----------------------
-
-The :class:`Symfony\\Component\\ErrorHandler\\DebugClassLoader` class throws
-more useful exceptions when a class isn't found by the registered autoloaders
-(e.g. looks for typos in the class names and suggest the right class name).
-
-In practice, this debugger looks for all registered autoloaders that implement a
-``findFile()`` method and replaces them by its own method to find class files.
-
-Use the following code (e.g. in your :ref:`front controller `)
-to enable this class loading debugger::
-
- use Symfony\Component\ErrorHandler\DebugClassLoader;
-
- DebugClassLoader::enable();
diff --git a/components/error_renderer.rst b/components/error_renderer.rst
deleted file mode 100644
index 607935aa6bb..00000000000
--- a/components/error_renderer.rst
+++ /dev/null
@@ -1,159 +0,0 @@
-.. index::
- single: Error
- single: Exception
- single: Components; ErrorRenderer
-
-The ErrorRenderer Component
-===========================
-
- The ErrorRenderer component converts PHP errors and exceptions into other
- formats such as JSON and HTML and renders them.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/error-renderer
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-The ErrorRenderer component provides several renderers to convert PHP errors and
-exceptions into other formats such as JSON and HTML easier to debug when working
-with HTTP applications::
-
- use Symfony\Component\ErrorRenderer\ErrorRenderer;
- use Symfony\Component\ErrorRenderer\ErrorRenderer\HtmlErrorRenderer;
- use Symfony\Component\ErrorRenderer\ErrorRenderer\JsonErrorRenderer;
- use Symfony\Component\ErrorRenderer\Exception\FlattenException;
- use Symfony\Component\HttpFoundation\Response;
-
- $renderers = [
- new HtmlErrorRenderer(),
- new JsonErrorRenderer(),
- // ...
- ];
- $errorRenderer = new ErrorRenderer($renderers);
-
- try {
- // ...
- } catch (\Throwable $e) {
- $e = FlattenException::createFromThrowable($e);
-
- return new Response($errorRenderer->render($e, 'json'), 500, ['Content-Type' => 'application/json']);
- }
-
-Built-in Error Renderers
-------------------------
-
-This component provides error renderers for the most common needs:
-
- * :class:`Symfony\\Component\\ErrorRenderer\\ErrorRenderer\\HtmlErrorRenderer`
- renders errors in HTML format;
- * :class:`Symfony\\Component\\ErrorRenderer\\ErrorRenderer\\JsonErrorRenderer`
- renders errors in JSON format and it's compliant with the `RFC 7807`_ standard;
- * :class:`Symfony\\Component\\ErrorRenderer\\ErrorRenderer\\XmlErrorRenderer`
- renders errors in XML and Atom formats. It's compliant with the `RFC 7807`_
- standard;
- * :class:`Symfony\\Component\\ErrorRenderer\\ErrorRenderer\\TxtErrorRenderer`
- renders errors in plain text format.
-
-Adding a Custom Error Renderer
-------------------------------
-
-Error renderers are PHP classes that implement the
-:class:`Symfony\\Component\\ErrorRenderer\\ErrorRenderer\\ErrorRendererInterface`.
-For example, if you need to render errors in `JSON-LD format`_, create this
-class anywhere in your project::
-
- namespace App\ErrorRenderer;
-
- use Symfony\Component\ErrorRenderer\ErrorRenderer\ErrorRendererInterface;
- use Symfony\Component\ErrorRenderer\Exception\FlattenException;
-
- class JsonLdErrorRenderer implements ErrorRendererInterface
- {
- private $debug;
-
- public function __construct(bool $debug = true)
- {
- $this->debug = $debug;
- }
-
- public static function getFormat(): string
- {
- return 'jsonld';
- }
-
- public function render(FlattenException $exception): string
- {
- $content = [
- '@id' => 'https://example.com',
- '@type' => 'error',
- '@context' => [
- 'title' => $exception->getTitle(),
- 'code' => $exception->getStatusCode(),
- 'message' => $exception->getMessage(),
- ],
- ];
-
- if ($this->debug) {
- $content['@context']['exceptions'] = $exception->toArray();
- }
-
- return (string) json_encode($content);
- }
- }
-
-.. tip::
-
- If the ``getFormat()`` method of your error renderer matches one of formats
- supported by the built-in renderers, the built-in renderer is replaced by
- your custom renderer.
-
-To enable the new error renderer in the application,
-:ref:`register it as a service ` and
-:doc:`tag it ` with the ``error_renderer.renderer``
-tag.
-
-.. configuration-block::
-
- .. code-block:: yaml
-
- # config/services.yaml
- services:
- App\ErrorRenderer\JsonLdErrorRenderer:
- arguments: ['%kernel.debug%']
- tags: ['error_renderer.renderer']
-
- .. code-block:: xml
-
-
-
-
-
-
-
- %kernel.debug%
-
-
-
-
-
- .. code-block:: php
-
- // config/services.php
- use App\ErrorRenderer\JsonLdErrorRenderer;
-
- $container->register(JsonLdErrorRenderer::class)
- ->setArguments([$container->getParameter('kernel.debug')]);
- ->addTag('error_renderer.renderer');
-
-.. _`RFC 7807`: https://tools.ietf.org/html/rfc7807
-.. _`JSON-LD format`: https://en.wikipedia.org/wiki/JSON-LD
diff --git a/components/event_dispatcher.rst b/components/event_dispatcher.rst
index 6cfff941a4f..62a3707bb39 100644
--- a/components/event_dispatcher.rst
+++ b/components/event_dispatcher.rst
@@ -1,7 +1,3 @@
-.. index::
- single: EventDispatcher
- single: Components; EventDispatcher
-
The EventDispatcher Component
=============================
@@ -32,7 +28,7 @@ truly extensible.
Take an example from :doc:`the HttpKernel component `.
Once a ``Response`` object has been created, it may be useful to allow other
elements in the system to modify it (e.g. add some cache headers) before
-it's actually used. To make this possible, the Symfony kernel throws an
+it's actually used. To make this possible, the Symfony kernel dispatches an
event - ``kernel.response``. Here's how it works:
* A *listener* (PHP object) tells a central *dispatcher* object that it
@@ -46,9 +42,6 @@ event - ``kernel.response``. Here's how it works:
``kernel.response`` event, allowing each of them to make modifications
to the ``Response`` object.
-.. index::
- single: EventDispatcher; Events
-
Installation
------------
@@ -76,23 +69,6 @@ An :class:`Symfony\\Contracts\\EventDispatcher\\Event` instance is also
created and passed to all of the listeners. As you'll see later, the ``Event``
object itself often contains data about the event being dispatched.
-.. index::
- pair: EventDispatcher; Naming conventions
-
-Naming Conventions
-..................
-
-The unique event name can be any string, but optionally follows a few
-naming conventions:
-
-* Use only lowercase letters, numbers, dots (``.``) and underscores (``_``);
-* Prefix names with a namespace followed by a dot (e.g. ``order.*``, ``user.*``);
-* End names with a verb that indicates what action has been taken (e.g.
- ``order.placed``).
-
-.. index::
- single: EventDispatcher; Event subclasses
-
Event Names and Event Objects
.............................
@@ -126,9 +102,6 @@ listeners registered with that event::
$dispatcher = new EventDispatcher();
-.. index::
- single: EventDispatcher; Listeners
-
Connecting Listeners
~~~~~~~~~~~~~~~~~~~~
@@ -163,7 +136,7 @@ The ``addListener()`` method takes up to three arguments:
use Symfony\Contracts\EventDispatcher\Event;
- $dispatcher->addListener('acme.foo.action', function (Event $event) {
+ $dispatcher->addListener('acme.foo.action', function (Event $event): void {
// will be executed when the acme.foo.action event is dispatched
});
@@ -178,7 +151,7 @@ the ``Event`` object as the single argument::
{
// ...
- public function onFooAction(Event $event)
+ public function onFooAction(Event $event): void
{
// ... do something
}
@@ -198,39 +171,68 @@ determine which instance is passed.
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
- use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
use Symfony\Component\EventDispatcher\EventDispatcher;
- $containerBuilder = new ContainerBuilder(new ParameterBag());
+ $container = new ContainerBuilder(new ParameterBag());
// register the compiler pass that handles the 'kernel.event_listener'
// and 'kernel.event_subscriber' service tags
- $containerBuilder->addCompilerPass(new RegisterListenersPass());
+ $container->addCompilerPass(new RegisterListenersPass());
- $containerBuilder->register('event_dispatcher', EventDispatcher::class);
+ $container->register('event_dispatcher', EventDispatcher::class);
// registers an event listener
- $containerBuilder->register('listener_service_id', \AcmeListener::class)
+ $container->register('listener_service_id', \AcmeListener::class)
->addTag('kernel.event_listener', [
'event' => 'acme.foo.action',
'method' => 'onFooAction',
]);
// registers an event subscriber
- $containerBuilder->register('subscriber_service_id', \AcmeSubscriber::class)
+ $container->register('subscriber_service_id', \AcmeSubscriber::class)
->addTag('kernel.event_subscriber');
- By default, the listeners pass assumes that the event dispatcher's service
+ ``RegisterListenersPass`` resolves aliased class names which for instance
+ allows to refer to an event via the fully qualified class name (FQCN) of the
+ event class. The pass will read the alias mapping from a dedicated container
+ parameter. This parameter can be extended by registering another compiler pass,
+ ``AddEventAliasesPass``::
+
+ use Symfony\Component\DependencyInjection\Compiler\PassConfig;
+ use Symfony\Component\DependencyInjection\ContainerBuilder;
+ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
+ use Symfony\Component\EventDispatcher\DependencyInjection\AddEventAliasesPass;
+ use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
+ use Symfony\Component\EventDispatcher\EventDispatcher;
+
+ $container = new ContainerBuilder(new ParameterBag());
+ $container->addCompilerPass(new AddEventAliasesPass([
+ \AcmeFooActionEvent::class => 'acme.foo.action',
+ ]));
+ $container->addCompilerPass(new RegisterListenersPass(), PassConfig::TYPE_BEFORE_REMOVING);
+
+ $container->register('event_dispatcher', EventDispatcher::class);
+
+ // registers an event listener
+ $container->register('listener_service_id', \AcmeListener::class)
+ ->addTag('kernel.event_listener', [
+ // will be translated to 'acme.foo.action' by RegisterListenersPass.
+ 'event' => \AcmeFooActionEvent::class,
+ 'method' => 'onFooAction',
+ ]);
+
+ .. note::
+
+ Note that ``AddEventAliasesPass`` has to be processed before ``RegisterListenersPass``.
+
+ The listeners pass assumes that the event dispatcher's service
id is ``event_dispatcher``, that event listeners are tagged with the
- ``kernel.event_listener`` tag and that event subscribers are tagged
- with the ``kernel.event_subscriber`` tag. You can change these default
- values by passing custom values to the constructor of ``RegisterListenersPass``.
+ ``kernel.event_listener`` tag, that event subscribers are tagged
+ with the ``kernel.event_subscriber`` tag and that the alias mapping is
+ stored as parameter ``event_dispatcher.event_aliases``.
.. _event_dispatcher-closures-as-listeners:
-.. index::
- single: EventDispatcher; Creating and dispatching an event
-
Creating and Dispatching an Event
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -244,7 +246,7 @@ system flexible and decoupled.
Creating an Event Class
.......................
-Suppose you want to create a new event - ``order.placed`` - that is dispatched
+Suppose you want to create a new event that is dispatched
each time a customer orders a product with your application. When dispatching
this event, you'll pass a custom event instance that has access to the placed
order. Start by creating this custom event class and documenting it::
@@ -255,21 +257,14 @@ order. Start by creating this custom event class and documenting it::
use Symfony\Contracts\EventDispatcher\Event;
/**
- * The order.placed event is dispatched each time an order is created
- * in the system.
+ * This event is dispatched each time an order
+ * is placed in the system.
*/
- class OrderPlacedEvent extends Event
+ final class OrderPlacedEvent extends Event
{
- public const NAME = 'order.placed';
-
- protected $order;
-
- public function __construct(Order $order)
- {
- $this->order = $order;
- }
+ public function __construct(private Order $order) {}
- public function getOrder()
+ public function getOrder(): Order
{
return $this->order;
}
@@ -277,22 +272,14 @@ order. Start by creating this custom event class and documenting it::
Each listener now has access to the order via the ``getOrder()`` method.
-.. note::
-
- If you don't need to pass any additional data to the event listeners, you
- can also use the default
- :class:`Symfony\\Contracts\\EventDispatcher\\Event` class. In such case,
- you can document the event and its name in a generic ``StoreEvents`` class,
- similar to the :class:`Symfony\\Component\\HttpKernel\\KernelEvents`
- class.
-
Dispatch the Event
..................
The :method:`Symfony\\Component\\EventDispatcher\\EventDispatcher::dispatch`
method notifies all listeners of the given event. It takes two arguments:
-the ``Event`` instance to pass to each listener of that event and the name
-of the event to dispatch and ::
+the ``Event`` instance to pass to each listener of that event and optionally the
+name of the event to dispatch. If it's not defined, the class of the ``Event``
+instance will be used::
use Acme\Store\Event\OrderPlacedEvent;
use Acme\Store\Order;
@@ -303,14 +290,37 @@ of the event to dispatch and ::
// creates the OrderPlacedEvent and dispatches it
$event = new OrderPlacedEvent($order);
- $dispatcher->dispatch($event, OrderPlacedEvent::NAME);
+ $dispatcher->dispatch($event);
Notice that the special ``OrderPlacedEvent`` object is created and passed to
-the ``dispatch()`` method. Now, any listener to the ``order.placed``
+the ``dispatch()`` method. Now, any listener to the ``OrderPlacedEvent::class``
event will receive the ``OrderPlacedEvent``.
-.. index::
- single: EventDispatcher; Event subscribers
+.. note::
+
+ If you don't need to pass any additional data to the event listeners, you
+ can also use the default
+ :class:`Symfony\\Contracts\\EventDispatcher\\Event` class. In such case,
+ you can document the event and its name in a generic ``StoreEvents`` class,
+ similar to the :class:`Symfony\\Component\\HttpKernel\\KernelEvents`
+ class::
+
+ namespace App\Event;
+
+ class StoreEvents {
+
+ /**
+ * @Event("Symfony\Contracts\EventDispatcher\Event")
+ */
+ public const ORDER_PLACED = 'order.placed';
+ }
+
+ And use the :class:`Symfony\\Contracts\\EventDispatcher\\Event` class to
+ dispatch the event::
+
+ use Symfony\Contracts\EventDispatcher\Event;
+
+ $this->eventDispatcher->dispatch(new Event(), StoreEvents::ORDER_PLACED);
.. _event_dispatcher-using-event-subscribers:
@@ -328,7 +338,7 @@ events it should subscribe to. It implements the
interface, which requires a single static method called
:method:`Symfony\\Component\\EventDispatcher\\EventSubscriberInterface::getSubscribedEvents`.
Take the following example of a subscriber that subscribes to the
-``kernel.response`` and ``order.placed`` events::
+``kernel.response`` and ``OrderPlacedEvent::class`` events::
namespace Acme\Store\Event;
@@ -339,29 +349,30 @@ Take the following example of a subscriber that subscribes to the
class StoreSubscriber implements EventSubscriberInterface
{
- public static function getSubscribedEvents()
+ public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => [
['onKernelResponsePre', 10],
['onKernelResponsePost', -10],
],
- OrderPlacedEvent::NAME => 'onStoreOrder',
+ OrderPlacedEvent::class => 'onPlacedOrder',
];
}
- public function onKernelResponsePre(ResponseEvent $event)
+ public function onKernelResponsePre(ResponseEvent $event): void
{
// ...
}
- public function onKernelResponsePost(ResponseEvent $event)
+ public function onKernelResponsePost(ResponseEvent $event): void
{
// ...
}
- public function onStoreOrder(OrderPlacedEvent $event)
+ public function onPlacedOrder(OrderPlacedEvent $event): void
{
+ $order = $event->getOrder();
// ...
}
}
@@ -391,9 +402,6 @@ example, when the ``kernel.response`` event is triggered, the methods
``onKernelResponsePre()`` and ``onKernelResponsePost()`` are called in that
order.
-.. index::
- single: EventDispatcher; Stopping event flow
-
.. _event_dispatcher-event-propagation:
Stopping Event Flow/Propagation
@@ -404,18 +412,18 @@ from being called. In other words, the listener needs to be able to tell
the dispatcher to stop all propagation of the event to future listeners
(i.e. to not notify any more listeners). This can be accomplished from
inside a listener via the
-:method:`Symfony\\Component\\EventDispatcher\\Event::stopPropagation` method::
+:method:`Symfony\\Contracts\\EventDispatcher\\Event::stopPropagation` method::
use Acme\Store\Event\OrderPlacedEvent;
- public function onStoreOrder(OrderPlacedEvent $event)
+ public function onPlacedOrder(OrderPlacedEvent $event): void
{
// ...
$event->stopPropagation();
}
-Now, any listeners to ``order.placed`` that have not yet been called will
+Now, any listeners to ``OrderPlacedEvent::class`` that have not yet been called will
*not* be called.
It is possible to detect if an event was stopped by using the
@@ -428,9 +436,6 @@ method which returns a boolean value::
// ...
}
-.. index::
- single: EventDispatcher; EventDispatcher aware events and listeners
-
.. _event_dispatcher-dispatcher-aware-events:
EventDispatcher Aware Events and Listeners
@@ -441,9 +446,6 @@ name and a reference to itself to the listeners. This can lead to some advanced
applications of the ``EventDispatcher`` including dispatching other events inside
listeners, chaining events or even lazy loading listeners into the dispatcher object.
-.. index::
- single: EventDispatcher; Event name introspection
-
.. _event_dispatcher-event-name-introspection:
Event Name Introspection
@@ -455,9 +457,9 @@ is dispatched, are passed as arguments to the listener::
use Symfony\Contracts\EventDispatcher\Event;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
- class Foo
+ class MyListener
{
- public function myEventListener(Event $event, $eventName, EventDispatcherInterface $dispatcher)
+ public function myEventListener(Event $event, string $eventName, EventDispatcherInterface $dispatcher): void
{
// ... do something with the event name
}
@@ -475,17 +477,11 @@ with some other dispatchers:
Learn More
----------
-.. toctree::
- :maxdepth: 1
- :glob:
-
- /components/event_dispatcher/*
- /event_dispatcher/*
-
+* :doc:`/components/event_dispatcher/generic_event`
* :ref:`The kernel.event_listener tag `
* :ref:`The kernel.event_subscriber tag `
.. _Mediator: https://en.wikipedia.org/wiki/Mediator_pattern
.. _Observer: https://en.wikipedia.org/wiki/Observer_pattern
-.. _Closures: https://php.net/manual/en/functions.anonymous.php
-.. _PHP callable: https://php.net/manual/en/language.pseudo-types.php#language.types.callback
+.. _Closures: https://www.php.net/manual/en/functions.anonymous.php
+.. _PHP callable: https://www.php.net/manual/en/language.types.callable.php
diff --git a/components/event_dispatcher/container_aware_dispatcher.rst b/components/event_dispatcher/container_aware_dispatcher.rst
deleted file mode 100644
index 659a94cee7a..00000000000
--- a/components/event_dispatcher/container_aware_dispatcher.rst
+++ /dev/null
@@ -1,10 +0,0 @@
-.. index::
- single: EventDispatcher; Service container aware
-
-The Container Aware Event Dispatcher
-====================================
-
-.. caution::
-
- The ``ContainerAwareEventDispatcher`` was removed in Symfony 4.0. Use
- ``EventDispatcher`` with closure-proxy injection instead.
diff --git a/components/event_dispatcher/generic_event.rst b/components/event_dispatcher/generic_event.rst
index 1f9be477151..41d0a9d66a4 100644
--- a/components/event_dispatcher/generic_event.rst
+++ b/components/event_dispatcher/generic_event.rst
@@ -1,6 +1,3 @@
-.. index::
- single: EventDispatcher
-
The Generic Event Object
========================
@@ -57,7 +54,7 @@ Passing a subject::
class FooListener
{
- public function handler(GenericEvent $event)
+ public function handler(GenericEvent $event): void
{
if ($event->getSubject() instanceof Foo) {
// ...
@@ -78,9 +75,9 @@ access the event arguments::
class FooListener
{
- public function handler(GenericEvent $event)
+ public function handler(GenericEvent $event): void
{
- if (isset($event['type']) && $event['type'] === 'foo') {
+ if (isset($event['type']) && 'foo' === $event['type']) {
// ... do something
}
@@ -97,9 +94,8 @@ Filtering data::
class FooListener
{
- public function filter(GenericEvent $event)
+ public function filter(GenericEvent $event): void
{
$event['data'] = strtolower($event['data']);
}
}
-
diff --git a/components/event_dispatcher/immutable_dispatcher.rst b/components/event_dispatcher/immutable_dispatcher.rst
index 25940825065..a6a98c47f37 100644
--- a/components/event_dispatcher/immutable_dispatcher.rst
+++ b/components/event_dispatcher/immutable_dispatcher.rst
@@ -1,6 +1,3 @@
-.. index::
- single: EventDispatcher; Immutable
-
The Immutable Event Dispatcher
==============================
@@ -16,9 +13,10 @@ To use it, first create a normal ``EventDispatcher`` dispatcher and register
some listeners or subscribers::
use Symfony\Component\EventDispatcher\EventDispatcher;
+ use Symfony\Contracts\EventDispatcher\Event;
$dispatcher = new EventDispatcher();
- $dispatcher->addListener('foo.action', function ($event) {
+ $dispatcher->addListener('foo.action', function (Event $event): void {
// ...
});
diff --git a/components/event_dispatcher/traceable_dispatcher.rst b/components/event_dispatcher/traceable_dispatcher.rst
index 87d58023445..7b3819e3a48 100644
--- a/components/event_dispatcher/traceable_dispatcher.rst
+++ b/components/event_dispatcher/traceable_dispatcher.rst
@@ -1,7 +1,3 @@
-.. index::
- single: EventDispatcher; Debug
- single: EventDispatcher; Traceable
-
The Traceable Event Dispatcher
==============================
@@ -41,10 +37,10 @@ to register event listeners and dispatch events::
$traceableEventDispatcher->dispatch($event, 'event.the_name');
After your application has been processed, you can use the
-:method:`Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcherInterface::getCalledListeners`
+:method:`Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher::getCalledListeners`
method to retrieve an array of event listeners that have been called in
your application. Similarly, the
-:method:`Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcherInterface::getNotCalledListeners`
+:method:`Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher::getNotCalledListeners`
method returns an array of event listeners that have not been called::
// ...
diff --git a/components/expression_language.rst b/components/expression_language.rst
index 90600bf7357..b0dd10b0f42 100644
--- a/components/expression_language.rst
+++ b/components/expression_language.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Expressions
- Single: Components; Expression Language
-
The ExpressionLanguage Component
================================
@@ -18,12 +14,14 @@ Installation
.. include:: /components/require_autoload.rst.inc
-How can the Expression Engine Help Me?
---------------------------------------
+.. _how-can-the-expression-engine-help-me:
+
+How can the Expression Language Help Me?
+----------------------------------------
The purpose of the component is to allow users to use expressions inside
-configuration for more complex logic. For some examples, the Symfony Framework
-uses expressions in security, for validation rules and in route matching.
+configuration for more complex logic. For example, the Symfony Framework uses
+expressions in security, for validation rules and in route matching.
Besides using the component in the framework itself, the ExpressionLanguage
component is a perfect candidate for the foundation of a *business rule engine*.
@@ -43,9 +41,10 @@ way without using PHP and without introducing security problems:
# Send an alert when
product.stock < 15
-Expressions can be seen as a very restricted PHP sandbox and are immune to
-external injections as you must explicitly declare which variables are available
-in an expression.
+Expressions can be seen as a very restricted PHP sandbox and are less vulnerable
+to external injections because you must explicitly declare which variables are
+available in an expression (but you should still sanitize any data given by end
+users and passed to expressions).
Usage
-----
@@ -73,11 +72,66 @@ The main class of the component is
var_dump($expressionLanguage->compile('1 + 2')); // displays (1 + 2)
-Expression Syntax
------------------
+.. tip::
+
+ See :doc:`/reference/formats/expression_language` to learn the syntax of
+ the ExpressionLanguage component.
+
+Null Coalescing Operator
+........................
+
+.. note::
+
+ This content has been moved to the :ref:`null coalescing operator `
+ section of ExpressionLanguage syntax reference page.
+
+Parsing and Linting Expressions
+...............................
+
+The ExpressionLanguage component provides a way to parse and lint expressions.
+The :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::parse`
+method returns a :class:`Symfony\\Component\\ExpressionLanguage\\ParsedExpression`
+instance that can be used to inspect and manipulate the expression. The
+:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::lint`, on the
+other hand, throws a :class:`Symfony\\Component\\ExpressionLanguage\\SyntaxError`
+if the expression is not valid::
+
+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
+
+ $expressionLanguage = new ExpressionLanguage();
+
+ var_dump($expressionLanguage->parse('1 + 2', []));
+ // displays the AST nodes of the expression which can be
+ // inspected and manipulated
+
+ $expressionLanguage->lint('1 + 2', []); // doesn't throw anything
+
+ $expressionLanguage->lint('1 + a', []);
+ // throws a SyntaxError exception:
+ // "Variable "a" is not valid around position 5 for expression `1 + a`."
+
+The behavior of these methods can be configured with some flags defined in the
+:class:`Symfony\\Component\\ExpressionLanguage\\Parser` class:
+
+* ``IGNORE_UNKNOWN_VARIABLES``: don't throw an exception if a variable is not
+ defined in the expression;
+* ``IGNORE_UNKNOWN_FUNCTIONS``: don't throw an exception if a function is not
+ defined in the expression.
+
+This is how you can use these flags::
+
+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
+ use Symfony\Component\ExpressionLanguage\Parser;
+
+ $expressionLanguage = new ExpressionLanguage();
+
+ // does not throw a SyntaxError because the unknown variables and functions are ignored
+ $expressionLanguage->lint('unknown_var + unknown_function()', [], Parser::IGNORE_UNKNOWN_VARIABLES | Parser::IGNORE_UNKNOWN_FUNCTIONS);
-See :doc:`/components/expression_language/syntax` to learn the syntax of the
-ExpressionLanguage component.
+.. versionadded:: 7.1
+
+ The support for flags in the ``parse()`` and ``lint()`` methods
+ was introduced in Symfony 7.1.
Passing in Variables
--------------------
@@ -91,7 +145,7 @@ PHP type (including objects)::
class Apple
{
- public $variety;
+ public string $variety;
}
$apple = new Apple();
@@ -104,28 +158,262 @@ PHP type (including objects)::
]
)); // displays "Honeycrisp"
-For more information, see the :doc:`/components/expression_language/syntax`
-entry, especially :ref:`component-expression-objects` and :ref:`component-expression-arrays`.
+When using this component inside a Symfony application, certain objects and
+variables are automatically injected by Symfony so you can use them in your
+expressions (e.g. the request, the current user, etc.):
+
+* :doc:`Variables available in security expressions `;
+* :doc:`Variables available in service container expressions `;
+* :ref:`Variables available in routing expressions `.
+
+.. _expression-language-caching:
Caching
-------
-The component provides some different caching strategies, read more about them
-in :doc:`/components/expression_language/caching`.
+The ExpressionLanguage component provides a
+:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::compile`
+method to be able to cache the expressions in plain PHP. But internally, the
+component also caches the parsed expressions, so duplicated expressions can be
+compiled/evaluated quicker.
+
+The Workflow
+~~~~~~~~~~~~
+
+Both :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::evaluate`
+and ``compile()`` need to do some things before each can provide the return
+values. For ``evaluate()``, this overhead is even bigger.
+
+Both methods need to tokenize and parse the expression. This is done by the
+:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::parse`
+method. It returns a :class:`Symfony\\Component\\ExpressionLanguage\\ParsedExpression`.
+Now, the ``compile()`` method just returns the string conversion of this object.
+The ``evaluate()`` method needs to loop through the "nodes" (pieces of an
+expression saved in the ``ParsedExpression``) and evaluate them on the fly.
+
+To save time, the ``ExpressionLanguage`` caches the ``ParsedExpression`` so
+it can skip the tokenization and parsing steps with duplicate expressions. The
+caching is done by a PSR-6 `CacheItemPoolInterface`_ instance (by default, it
+uses an :class:`Symfony\\Component\\Cache\\Adapter\\ArrayAdapter`). You can
+customize this by creating a custom cache pool or using one of the available
+ones and injecting this using the constructor::
+
+ use Symfony\Component\Cache\Adapter\RedisAdapter;
+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
+
+ $cache = new RedisAdapter(...);
+ $expressionLanguage = new ExpressionLanguage($cache);
+
+.. seealso::
+
+ See the :doc:`/components/cache` documentation for more information about
+ available cache adapters.
+
+Using Parsed and Serialized Expressions
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Both ``evaluate()`` and ``compile()`` can handle ``ParsedExpression`` and
+``SerializedParsedExpression``::
+
+ // ...
+
+ // the parse() method returns a ParsedExpression
+ $expression = $expressionLanguage->parse('1 + 4', []);
+
+ var_dump($expressionLanguage->evaluate($expression)); // prints 5
+
+.. code-block:: php
+
+ use Symfony\Component\ExpressionLanguage\SerializedParsedExpression;
+ // ...
+
+ $expression = new SerializedParsedExpression(
+ '1 + 4',
+ serialize($expressionLanguage->parse('1 + 4', [])->getNodes())
+ );
+
+ var_dump($expressionLanguage->evaluate($expression)); // prints 5
+
+.. _expression-language-ast:
AST Dumping and Editing
-----------------------
-The AST (*Abstract Syntax Tree*) of expressions can be dumped and manipulated
-as explained in :doc:`/components/expression_language/ast`.
+It's difficult to manipulate or inspect the expressions created with the ExpressionLanguage
+component, because the expressions are plain strings. A better approach is to
+turn those expressions into an AST. In computer science, `AST`_ (*Abstract
+Syntax Tree*) is *"a tree representation of the structure of source code written
+in a programming language"*. In Symfony, an ExpressionLanguage AST is a set of
+nodes that contain PHP classes representing the given expression.
+
+Dumping the AST
+~~~~~~~~~~~~~~~
+
+Call the :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::getNodes`
+method after parsing any expression to get its AST::
+
+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
+
+ $ast = (new ExpressionLanguage())
+ ->parse('1 + 2', [])
+ ->getNodes()
+ ;
+
+ // dump the AST nodes for inspection
+ var_dump($ast);
+
+ // dump the AST nodes as a string representation
+ $astAsString = $ast->dump();
+
+Manipulating the AST
+~~~~~~~~~~~~~~~~~~~~
+
+The nodes of the AST can also be dumped into a PHP array of nodes to allow
+manipulating them. Call the :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::toArray`
+method to turn the AST into an array::
+
+ // ...
+
+ $astAsArray = (new ExpressionLanguage())
+ ->parse('1 + 2', [])
+ ->getNodes()
+ ->toArray()
+ ;
+
+.. _expression-language-extending:
+
+Extending the ExpressionLanguage
+--------------------------------
+
+The ExpressionLanguage can be extended by adding custom functions. For
+instance, in the Symfony Framework, the security has custom functions to check
+the user's role.
+
+.. note::
+
+ If you want to learn how to use functions in an expression, read
+ ":ref:`component-expression-functions`".
+
+Registering Functions
+~~~~~~~~~~~~~~~~~~~~~
+
+Functions are registered on each specific ``ExpressionLanguage`` instance.
+That means the functions can be used in any expression executed by that
+instance.
+
+To register a function, use
+:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::register`.
+This method has 3 arguments:
+
+* **name** - The name of the function in an expression;
+* **compiler** - A function executed when compiling an expression using the
+ function;
+* **evaluator** - A function executed when the expression is evaluated.
+
+Example::
+
+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
+
+ $expressionLanguage = new ExpressionLanguage();
+ $expressionLanguage->register('lowercase', function ($str): string {
+ return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str);
+ }, function ($arguments, $str): string {
+ if (!is_string($str)) {
+ return $str;
+ }
+
+ return strtolower($str);
+ });
+
+ var_dump($expressionLanguage->evaluate('lowercase("HELLO")'));
+ // this will print: hello
+
+In addition to the custom function arguments, the **evaluator** is passed an
+``arguments`` variable as its first argument, which is equal to the second
+argument of ``evaluate()`` (e.g. the "values" when evaluating an expression).
+
+.. _components-expression-language-provider:
+
+Using Expression Providers
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+When you use the ``ExpressionLanguage`` class in your library, you often want
+to add custom functions. To do so, you can create a new expression provider by
+creating a class that implements
+:class:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunctionProviderInterface`.
+
+This interface requires one method:
+:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunctionProviderInterface::getFunctions`,
+which returns an array of expression functions (instances of
+:class:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunction`) to
+register::
+
+ use Symfony\Component\ExpressionLanguage\ExpressionFunction;
+ use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
+
+ class StringExpressionLanguageProvider implements ExpressionFunctionProviderInterface
+ {
+ public function getFunctions(): array
+ {
+ return [
+ new ExpressionFunction('lowercase', function ($str): string {
+ return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str);
+ }, function ($arguments, $str): string {
+ if (!is_string($str)) {
+ return $str;
+ }
+
+ return strtolower($str);
+ }),
+ ];
+ }
+ }
+
+.. tip::
+
+ To create an expression function from a PHP function with the
+ :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunction::fromPhp` static method::
+
+ ExpressionFunction::fromPhp('strtoupper');
+
+ Namespaced functions are supported, but they require a second argument to
+ define the name of the expression::
+
+ ExpressionFunction::fromPhp('My\strtoupper', 'my_strtoupper');
+
+You can register providers using
+:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::registerProvider`
+or by using the second argument of the constructor::
+
+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
+
+ // using the constructor
+ $expressionLanguage = new ExpressionLanguage(null, [
+ new StringExpressionLanguageProvider(),
+ // ...
+ ]);
+
+ // using registerProvider()
+ $expressionLanguage->registerProvider(new StringExpressionLanguageProvider());
+
+.. tip::
+
+ It is recommended to create your own ``ExpressionLanguage`` class in your
+ library. Now you can add the extension by overriding the constructor::
+
+ use Psr\Cache\CacheItemPoolInterface;
+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage;
-Learn More
-----------
+ class ExpressionLanguage extends BaseExpressionLanguage
+ {
+ public function __construct(?CacheItemPoolInterface $cache = null, array $providers = [])
+ {
+ // prepends the default provider to let users override it
+ array_unshift($providers, new StringExpressionLanguageProvider());
-.. toctree::
- :maxdepth: 1
- :glob:
+ parent::__construct($cache, $providers);
+ }
+ }
- /components/expression_language/*
- /service_container/expression_language
- /reference/constraints/Expression
+.. _`AST`: https://en.wikipedia.org/wiki/Abstract_syntax_tree
+.. _`CacheItemPoolInterface`: https://github.com/php-fig/cache/blob/master/src/CacheItemPoolInterface.php
diff --git a/components/expression_language/ast.rst b/components/expression_language/ast.rst
deleted file mode 100644
index 0f15c20647a..00000000000
--- a/components/expression_language/ast.rst
+++ /dev/null
@@ -1,49 +0,0 @@
-.. index::
- single: AST; ExpressionLanguage
- single: AST; Abstract Syntax Tree
-
-Dumping and Manipulating the AST of Expressions
-===============================================
-
-Manipulating or inspecting the expressions created with the ExpressionLanguage
-component is difficult because they are plain strings. A better approach is to
-turn those expressions into an AST. In computer science, `AST`_ (*Abstract
-Syntax Tree*) is *"a tree representation of the structure of source code written
-in a programming language"*. In Symfony, a ExpressionLanguage AST is a set of
-nodes that contain PHP classes representing the given expression.
-
-Dumping the AST
----------------
-
-Call the :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::getNodes`
-method after parsing any expression to get its AST::
-
- use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
-
- $ast = (new ExpressionLanguage())
- ->parse('1 + 2', [])
- ->getNodes()
- ;
-
- // dump the AST nodes for inspection
- var_dump($ast);
-
- // dump the AST nodes as a string representation
- $astAsString = $ast->dump();
-
-Manipulating the AST
---------------------
-
-The nodes of the AST can also be dumped into a PHP array of nodes to allow
-manipulating them. Call the :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::toArray`
-method to turn the AST into an array::
-
- // ...
-
- $astAsArray = (new ExpressionLanguage())
- ->parse('1 + 2', [])
- ->getNodes()
- ->toArray()
- ;
-
-.. _`AST`: https://en.wikipedia.org/wiki/Abstract_syntax_tree
diff --git a/components/expression_language/caching.rst b/components/expression_language/caching.rst
deleted file mode 100644
index 770c2768ca5..00000000000
--- a/components/expression_language/caching.rst
+++ /dev/null
@@ -1,70 +0,0 @@
-.. index::
- single: Caching; ExpressionLanguage
-
-Caching Expressions Using Parser Caches
-=======================================
-
-The ExpressionLanguage component already provides a
-:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::compile`
-method to be able to cache the expressions in plain PHP. But internally, the
-component also caches the parsed expressions, so duplicated expressions can be
-compiled/evaluated quicker.
-
-The Workflow
-------------
-
-Both :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::evaluate`
-and ``compile()`` need to do some things before each can provide the return
-values. For ``evaluate()``, this overhead is even bigger.
-
-Both methods need to tokenize and parse the expression. This is done by the
-:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::parse`
-method. It returns a :class:`Symfony\\Component\\ExpressionLanguage\\ParsedExpression`.
-Now, the ``compile()`` method just returns the string conversion of this object.
-The ``evaluate()`` method needs to loop through the "nodes" (pieces of an
-expression saved in the ``ParsedExpression``) and evaluate them on the fly.
-
-To save time, the ``ExpressionLanguage`` caches the ``ParsedExpression`` so
-it can skip the tokenize and parse steps with duplicate expressions. The
-caching is done by a PSR-6 `CacheItemPoolInterface`_ instance (by default, it
-uses an :class:`Symfony\\Component\\Cache\\Adapter\\ArrayAdapter`). You can
-customize this by creating a custom cache pool or using one of the available
-ones and injecting this using the constructor::
-
- use Symfony\Component\Cache\Adapter\RedisAdapter;
- use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
-
- $cache = new RedisAdapter(...);
- $expressionLanguage = new ExpressionLanguage($cache);
-
-.. seealso::
-
- See the :doc:`/components/cache` documentation for more information about
- available cache adapters.
-
-Using Parsed and Serialized Expressions
----------------------------------------
-
-Both ``evaluate()`` and ``compile()`` can handle ``ParsedExpression`` and
-``SerializedParsedExpression``::
-
- // ...
-
- // the parse() method returns a ParsedExpression
- $expression = $expressionLanguage->parse('1 + 4', []);
-
- var_dump($expressionLanguage->evaluate($expression)); // prints 5
-
-.. code-block:: php
-
- use Symfony\Component\ExpressionLanguage\SerializedParsedExpression;
- // ...
-
- $expression = new SerializedParsedExpression(
- '1 + 4',
- serialize($expressionLanguage->parse('1 + 4', [])->getNodes())
- );
-
- var_dump($expressionLanguage->evaluate($expression)); // prints 5
-
-.. _`CacheItemPoolInterface`: https://github.com/php-fig/cache/blob/master/src/CacheItemPoolInterface.php
diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst
deleted file mode 100644
index e3ec448a495..00000000000
--- a/components/expression_language/extending.rst
+++ /dev/null
@@ -1,136 +0,0 @@
-.. index::
- single: Extending; ExpressionLanguage
-
-Extending the ExpressionLanguage
-================================
-
-The ExpressionLanguage can be extended by adding custom functions. For
-instance, in the Symfony Framework, the security has custom functions to check
-the user's role.
-
-.. note::
-
- If you want to learn how to use functions in an expression, read
- ":ref:`component-expression-functions`".
-
-Registering Functions
----------------------
-
-Functions are registered on each specific ``ExpressionLanguage`` instance.
-That means the functions can be used in any expression executed by that
-instance.
-
-To register a function, use
-:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::register`.
-This method has 3 arguments:
-
-* **name** - The name of the function in an expression;
-* **compiler** - A function executed when compiling an expression using the
- function;
-* **evaluator** - A function executed when the expression is evaluated.
-
-Example::
-
- use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
-
- $expressionLanguage = new ExpressionLanguage();
- $expressionLanguage->register('lowercase', function ($str) {
- return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str);
- }, function ($arguments, $str) {
- if (!is_string($str)) {
- return $str;
- }
-
- return strtolower($str);
- });
-
- var_dump($expressionLanguage->evaluate('lowercase("HELLO")'));
- // this will print: hello
-
-In addition to the custom function arguments, the **evaluator** is passed an
-``arguments`` variable as its first argument, which is equal to the second
-argument of ``compile()`` (e.g. the "values" when evaluating an expression).
-
-.. _components-expression-language-provider:
-
-Using Expression Providers
---------------------------
-
-When you use the ``ExpressionLanguage`` class in your library, you often want
-to add custom functions. To do so, you can create a new expression provider by
-creating a class that implements
-:class:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunctionProviderInterface`.
-
-This interface requires one method:
-:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunctionProviderInterface::getFunctions`,
-which returns an array of expression functions (instances of
-:class:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunction`) to
-register::
-
- use Symfony\Component\ExpressionLanguage\ExpressionFunction;
- use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
-
- class StringExpressionLanguageProvider implements ExpressionFunctionProviderInterface
- {
- public function getFunctions()
- {
- return [
- new ExpressionFunction('lowercase', function ($str) {
- return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str);
- }, function ($arguments, $str) {
- if (!is_string($str)) {
- return $str;
- }
-
- return strtolower($str);
- }),
- ];
- }
- }
-
-.. tip::
-
- To create an expression function from a PHP function with the
- :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionFunction::fromPhp` static method::
-
- ExpressionFunction::fromPhp('strtoupper');
-
- Namespaced functions are supported, but they require a second argument to
- define the name of the expression::
-
- ExpressionFunction::fromPhp('My\strtoupper', 'my_strtoupper');
-
-You can register providers using
-:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::registerProvider`
-or by using the second argument of the constructor::
-
- use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
-
- // using the constructor
- $expressionLanguage = new ExpressionLanguage(null, [
- new StringExpressionLanguageProvider(),
- // ...
- ]);
-
- // using registerProvider()
- $expressionLanguage->registerProvider(new StringExpressionLanguageProvider());
-
-.. tip::
-
- It is recommended to create your own ``ExpressionLanguage`` class in your
- library. Now you can add the extension by overriding the constructor::
-
- use Psr\Cache\CacheItemPoolInterface;
- use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage;
-
- class ExpressionLanguage extends BaseExpressionLanguage
- {
- public function __construct(CacheItemPoolInterface $parser = null, array $providers = [])
- {
- // prepends the default provider to let users override it
- array_unshift($providers, new StringExpressionLanguageProvider());
-
- parent::__construct($parser, $providers);
- }
- }
-
diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst
deleted file mode 100644
index 147782b4c9f..00000000000
--- a/components/expression_language/syntax.rst
+++ /dev/null
@@ -1,321 +0,0 @@
-.. index::
- single: Syntax; ExpressionLanguage
-
-The Expression Syntax
-=====================
-
-The ExpressionLanguage component uses a specific syntax which is based on the
-expression syntax of Twig. In this document, you can find all supported
-syntaxes.
-
-Supported Literals
-------------------
-
-The component supports:
-
-* **strings** - single and double quotes (e.g. ``'hello'``)
-* **numbers** - e.g. ``103``
-* **arrays** - using JSON-like notation (e.g. ``[1, 2]``)
-* **hashes** - using JSON-like notation (e.g. ``{ foo: 'bar' }``)
-* **booleans** - ``true`` and ``false``
-* **null** - ``null``
-
-.. caution::
-
- A backslash (``\``) must be escaped by 4 backslashes (``\\\\``) in a string
- and 8 backslashes (``\\\\\\\\``) in a regex::
-
- echo $expressionLanguage->evaluate('"\\\\"'); // prints \
- $expressionLanguage->evaluate('"a\\\\b" matches "/^a\\\\\\\\b$/"'); // returns true
-
- Control characters (e.g. ``\n``) in expressions are replaced with
- whitespace. To avoid this, escape the sequence with a single backslash
- (e.g. ``\\n``).
-
-.. _component-expression-objects:
-
-Working with Objects
---------------------
-
-When passing objects into an expression, you can use different syntaxes to
-access properties and call methods on the object.
-
-Accessing Public Properties
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Public properties on objects can be accessed by using the ``.`` syntax, similar
-to JavaScript::
-
- class Apple
- {
- public $variety;
- }
-
- $apple = new Apple();
- $apple->variety = 'Honeycrisp';
-
- var_dump($expressionLanguage->evaluate(
- 'fruit.variety',
- [
- 'fruit' => $apple,
- ]
- ));
-
-This will print out ``Honeycrisp``.
-
-Calling Methods
-~~~~~~~~~~~~~~~
-
-The ``.`` syntax can also be used to call methods on an object, similar to
-JavaScript::
-
- class Robot
- {
- public function sayHi($times)
- {
- $greetings = [];
- for ($i = 0; $i < $times; $i++) {
- $greetings[] = 'Hi';
- }
-
- return implode(' ', $greetings).'!';
- }
- }
-
- $robot = new Robot();
-
- var_dump($expressionLanguage->evaluate(
- 'robot.sayHi(3)',
- [
- 'robot' => $robot,
- ]
- ));
-
-This will print out ``Hi Hi Hi!``.
-
-.. _component-expression-functions:
-
-Working with Functions
-----------------------
-
-You can also use registered functions in the expression by using the same
-syntax as PHP and JavaScript. The ExpressionLanguage component comes with one
-function by default: ``constant()``, which will return the value of the PHP
-constant::
-
- define('DB_USER', 'root');
-
- var_dump($expressionLanguage->evaluate(
- 'constant("DB_USER")'
- ));
-
-This will print out ``root``.
-
-.. tip::
-
- To read how to register your own functions to use in an expression, see
- ":doc:`/components/expression_language/extending`".
-
-.. _component-expression-arrays:
-
-Working with Arrays
--------------------
-
-If you pass an array into an expression, use the ``[]`` syntax to access
-array keys, similar to JavaScript::
-
- $data = ['life' => 10, 'universe' => 10, 'everything' => 22];
-
- var_dump($expressionLanguage->evaluate(
- 'data["life"] + data["universe"] + data["everything"]',
- [
- 'data' => $data,
- ]
- ));
-
-This will print out ``42``.
-
-Supported Operators
--------------------
-
-The component comes with a lot of operators:
-
-Arithmetic Operators
-~~~~~~~~~~~~~~~~~~~~
-
-* ``+`` (addition)
-* ``-`` (subtraction)
-* ``*`` (multiplication)
-* ``/`` (division)
-* ``%`` (modulus)
-* ``**`` (pow)
-
-For example::
-
- var_dump($expressionLanguage->evaluate(
- 'life + universe + everything',
- [
- 'life' => 10,
- 'universe' => 10,
- 'everything' => 22,
- ]
- ));
-
-This will print out ``42``.
-
-Bitwise Operators
-~~~~~~~~~~~~~~~~~
-
-* ``&`` (and)
-* ``|`` (or)
-* ``^`` (xor)
-
-Comparison Operators
-~~~~~~~~~~~~~~~~~~~~
-
-* ``==`` (equal)
-* ``===`` (identical)
-* ``!=`` (not equal)
-* ``!==`` (not identical)
-* ``<`` (less than)
-* ``>`` (greater than)
-* ``<=`` (less than or equal to)
-* ``>=`` (greater than or equal to)
-* ``matches`` (regex match)
-
-.. tip::
-
- To test if a string does *not* match a regex, use the logical ``not``
- operator in combination with the ``matches`` operator::
-
- $expressionLanguage->evaluate('not ("foo" matches "/bar/")'); // returns true
-
- You must use parenthesis because the unary operator ``not`` has precedence
- over the binary operator ``matches``.
-
-Examples::
-
- $ret1 = $expressionLanguage->evaluate(
- 'life == everything',
- [
- 'life' => 10,
- 'universe' => 10,
- 'everything' => 22,
- ]
- );
-
- $ret2 = $expressionLanguage->evaluate(
- 'life > everything',
- [
- 'life' => 10,
- 'universe' => 10,
- 'everything' => 22,
- ]
- );
-
-Both variables would be set to ``false``.
-
-Logical Operators
-~~~~~~~~~~~~~~~~~
-
-* ``not`` or ``!``
-* ``and`` or ``&&``
-* ``or`` or ``||``
-
-For example::
-
- $ret = $expressionLanguage->evaluate(
- 'life < universe or life < everything',
- [
- 'life' => 10,
- 'universe' => 10,
- 'everything' => 22,
- ]
- );
-
-This ``$ret`` variable will be set to ``true``.
-
-String Operators
-~~~~~~~~~~~~~~~~
-
-* ``~`` (concatenation)
-
-For example::
-
- var_dump($expressionLanguage->evaluate(
- 'firstName~" "~lastName',
- [
- 'firstName' => 'Arthur',
- 'lastName' => 'Dent',
- ]
- ));
-
-This would print out ``Arthur Dent``.
-
-Array Operators
-~~~~~~~~~~~~~~~
-
-* ``in`` (contain)
-* ``not in`` (does not contain)
-
-For example::
-
- class User
- {
- public $group;
- }
-
- $user = new User();
- $user->group = 'human_resources';
-
- $inGroup = $expressionLanguage->evaluate(
- 'user.group in ["human_resources", "marketing"]',
- [
- 'user' => $user,
- ]
- );
-
-The ``$inGroup`` would evaluate to ``true``.
-
-Numeric Operators
-~~~~~~~~~~~~~~~~~
-
-* ``..`` (range)
-
-For example::
-
- class User
- {
- public $age;
- }
-
- $user = new User();
- $user->age = 34;
-
- $expressionLanguage->evaluate(
- 'user.age in 18..45',
- [
- 'user' => $user,
- ]
- );
-
-This will evaluate to ``true``, because ``user.age`` is in the range from
-``18`` to ``45``.
-
-Ternary Operators
-~~~~~~~~~~~~~~~~~
-
-* ``foo ? 'yes' : 'no'``
-* ``foo ?: 'no'`` (equal to ``foo ? foo : 'no'``)
-* ``foo ? 'yes'`` (equal to ``foo ? 'yes' : ''``)
-
-Built-in Objects and Variables
-------------------------------
-
-When using this component inside a Symfony application, certain objects and
-variables are automatically injected by Symfony so you can use them in your
-expressions (e.g. the request, the current user, etc.):
-
-* :doc:`Variables available in security expressions `;
-* :doc:`Variables available in service container expressions `;
-* :ref:`Variables available in routing expressions `.
diff --git a/components/filesystem.rst b/components/filesystem.rst
index 21881a307d3..dabf3f81872 100644
--- a/components/filesystem.rst
+++ b/components/filesystem.rst
@@ -1,10 +1,8 @@
-.. index::
- single: Filesystem
-
The Filesystem Component
========================
- The Filesystem component provides basic utilities for the filesystem.
+ The Filesystem component provides platform-independent utilities for
+ filesystem operations and for file/directory paths manipulation.
Installation
------------
@@ -18,38 +16,32 @@ Installation
Usage
-----
-The :class:`Symfony\\Component\\Filesystem\\Filesystem` class is the unique
-endpoint for filesystem operations::
+The component contains two main classes called :class:`Symfony\\Component\\Filesystem\\Filesystem`
+and :class:`Symfony\\Component\\Filesystem\\Path`::
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
+ use Symfony\Component\Filesystem\Path;
$filesystem = new Filesystem();
try {
- $filesystem->mkdir(sys_get_temp_dir().'/'.random_int(0, 1000));
+ $filesystem->mkdir(
+ Path::normalize(sys_get_temp_dir().'/'.random_int(0, 1000)),
+ );
} catch (IOExceptionInterface $exception) {
echo "An error occurred while creating your directory at ".$exception->getPath();
}
-.. note::
-
- Methods :method:`Symfony\\Component\\Filesystem\\Filesystem::mkdir`,
- :method:`Symfony\\Component\\Filesystem\\Filesystem::exists`,
- :method:`Symfony\\Component\\Filesystem\\Filesystem::touch`,
- :method:`Symfony\\Component\\Filesystem\\Filesystem::remove`,
- :method:`Symfony\\Component\\Filesystem\\Filesystem::chmod`,
- :method:`Symfony\\Component\\Filesystem\\Filesystem::chown` and
- :method:`Symfony\\Component\\Filesystem\\Filesystem::chgrp` can receive a
- string, an array or any object implementing :phpclass:`Traversable` as
- the target argument.
+Filesystem Utilities
+--------------------
``mkdir``
~~~~~~~~~
:method:`Symfony\\Component\\Filesystem\\Filesystem::mkdir` creates a directory recursively.
On POSIX filesystems, directories are created with a default mode value
-`0777`. You can use the second argument to set your own mode::
+``0777``. You can use the second argument to set your own mode::
$filesystem->mkdir('/tmp/photos', 0700);
@@ -162,7 +154,7 @@ permissions of a file. The fourth argument is a boolean recursive option::
// sets the mode of the video to 0600
$filesystem->chmod('video.ogg', 0600);
- // changes the mod of the src directory recursively
+ // changes the mode of the src directory recursively
$filesystem->chmod('src', 0700, 0000, true);
.. note::
@@ -193,6 +185,8 @@ of a single file or directory::
$filesystem->rename('/tmp/processed_video.ogg', '/path/to/store/video_647.ogg');
// renames a directory
$filesystem->rename('/tmp/files', '/path/to/store/files');
+ // if the target already exists, a third boolean argument is available to overwrite.
+ $filesystem->rename('/tmp/processed_video2.ogg', '/path/to/store/video_647.ogg', true);
``symlink``
~~~~~~~~~~~
@@ -212,13 +206,9 @@ support symbolic links, a third boolean argument is available::
:method:`Symfony\\Component\\Filesystem\\Filesystem::readlink` read links targets.
-PHP's ``readlink()`` function returns the target of a symbolic link. However, its behavior
-is completely different under Windows and Unix. On Windows systems, ``readlink()``
-resolves recursively the children links of a link until a final target is found. On
-Unix-based systems ``readlink()`` only resolves the next link.
-
-The :method:`Symfony\\Component\\Filesystem\\Filesystem::readlink` method provided
-by the Filesystem component always behaves in the same way::
+The :method:`Symfony\\Component\\Filesystem\\Filesystem::readlink` method
+provided by the Filesystem component behaves in the same way on all operating
+systems (unlike PHP's :phpfunction:`readlink` function)::
// returns the next direct target of the link without considering the existence of the target
$filesystem->readlink('/path/to/link');
@@ -226,17 +216,22 @@ by the Filesystem component always behaves in the same way::
// returns its absolute fully resolved final version of the target (if there are nested links, they are resolved)
$filesystem->readlink('/path/to/link', true);
-Its behavior is the following::
-
- public function readlink($path, $canonicalize = false)
+Its behavior is the following:
* When ``$canonicalize`` is ``false``:
- * if ``$path`` does not exist or is not a link, it returns ``null``.
- * if ``$path`` is a link, it returns the next direct target of the link without considering the existence of the target.
+
+ * if ``$path`` does not exist or is not a link, it returns ``null``.
+ * if ``$path`` is a link, it returns the next direct target of the link without considering the existence of the target.
* When ``$canonicalize`` is ``true``:
- * if ``$path`` does not exist, it returns null.
- * if ``$path`` exists, it returns its absolute fully resolved final version.
+
+ * if ``$path`` does not exist, it returns null.
+ * if ``$path`` exists, it returns its absolute fully resolved final version.
+
+.. note::
+
+ If you wish to canonicalize the path without checking its existence, you can
+ use :method:`Symfony\\Component\\Filesystem\\Path::canonicalize` method instead.
``makePathRelative``
~~~~~~~~~~~~~~~~~~~~
@@ -250,7 +245,7 @@ absolute paths and returns the relative path from the second path to the first o
'/var/lib/symfony/src/Symfony/Component'
);
// returns 'videos/'
- $filesystem->makePathRelative('/tmp/videos', '/tmp')
+ $filesystem->makePathRelative('/tmp/videos', '/tmp');
``mirror``
~~~~~~~~~~
@@ -286,15 +281,20 @@ exception on failure::
// returns a path like : /tmp/prefix_wyjgtF
$filesystem->tempnam('/tmp', 'prefix_');
+ // returns a path like : /tmp/prefix_wyjgtF.png
+ $filesystem->tempnam('/tmp', 'prefix_', '.png');
+
+.. _filesystem-dumpfile:
``dumpFile``
~~~~~~~~~~~~
:method:`Symfony\\Component\\Filesystem\\Filesystem::dumpFile` saves the given
-contents into a file. It does this in an atomic manner: it writes a temporary
-file first and then moves it to the new file location when it's finished.
-This means that the user will always see either the complete old file or
-complete new file (but never a partially-written file)::
+contents into a file (creating the file and its directory if they don't exist).
+It does this in an atomic manner: it writes a temporary file first and then moves
+it to the new file location when it's finished. This means that the user will
+always see either the complete old file or complete new file (but never a
+partially-written file)::
$filesystem->dumpFile('file.txt', 'Hello World');
@@ -307,10 +307,203 @@ The ``file.txt`` file contains ``Hello World`` now.
contents at the end of some file::
$filesystem->appendToFile('logs.txt', 'Email sent to user@example.com');
+ // the third argument tells whether the file should be locked when writing to it
+ $filesystem->appendToFile('logs.txt', 'Email sent to user@example.com', true);
If either the file or its containing directory doesn't exist, this method
creates them before appending the contents.
+``readFile``
+~~~~~~~~~~~~
+
+.. versionadded:: 7.1
+
+ The ``readFile()`` method was introduced in Symfony 7.1.
+
+:method:`Symfony\\Component\\Filesystem\\Filesystem::readFile` returns all the
+contents of a file as a string. Unlike the :phpfunction:`file_get_contents` function
+from PHP, it throws an exception when the given file path is not readable and
+when passing the path to a directory instead of a file::
+
+ $contents = $filesystem->readFile('/some/path/to/file.txt');
+
+The ``$contents`` variable now stores all the contents of the ``file.txt`` file.
+
+Path Manipulation Utilities
+---------------------------
+
+Dealing with file paths usually involves some difficulties:
+
+- Platform differences: file paths look different on different platforms. UNIX
+ file paths start with a slash ("/"), while Windows file paths start with a
+ system drive ("C:"). UNIX uses forward slashes, while Windows uses backslashes
+ by default.
+- Absolute/relative paths: web applications frequently need to deal with absolute
+ and relative paths. Converting one to the other properly is tricky and repetitive.
+
+:class:`Symfony\\Component\\Filesystem\\Path` provides utility methods to tackle
+those issues.
+
+Canonicalization
+~~~~~~~~~~~~~~~~
+
+Returns the shortest path name equivalent to the given path. It applies the
+following rules iteratively until no further processing can be done:
+
+- "." segments are removed;
+- ".." segments are resolved;
+- backslashes ("\\") are converted into forward slashes ("/");
+- root paths ("/" and "C:/") always terminate with a slash;
+- non-root paths never terminate with a slash;
+- schemes (such as "phar://") are kept;
+- replace ``~`` with the user's home directory.
+
+You can canonicalize a path with :method:`Symfony\\Component\\Filesystem\\Path::canonicalize`::
+
+ echo Path::canonicalize('/var/www/vhost/webmozart/../config.ini');
+ // => /var/www/vhost/config.ini
+
+You can pass absolute paths and relative paths to the
+:method:`Symfony\\Component\\Filesystem\\Path::canonicalize` method. When a
+relative path is passed, ".." segments at the beginning of the path are kept::
+
+ echo Path::canonicalize('../uploads/../config/config.yaml');
+ // => ../config/config.yaml
+
+Malformed paths are returned unchanged::
+
+ echo Path::canonicalize('C:Programs/PHP/php.ini');
+ // => C:Programs/PHP/php.ini
+
+Converting Absolute/Relative Paths
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Absolute/relative paths can be converted with the methods
+:method:`Symfony\\Component\\Filesystem\\Path::makeAbsolute`
+and :method:`Symfony\\Component\\Filesystem\\Path::makeRelative`.
+
+:method:`Symfony\\Component\\Filesystem\\Path::makeAbsolute` method expects a
+relative path and a base path to base that relative path upon::
+
+ echo Path::makeAbsolute('config/config.yaml', '/var/www/project');
+ // => /var/www/project/config/config.yaml
+
+If an absolute path is passed in the first argument, the absolute path is
+returned unchanged::
+
+ echo Path::makeAbsolute('/usr/share/lib/config.ini', '/var/www/project');
+ // => /usr/share/lib/config.ini
+
+The method resolves ".." segments, if there are any::
+
+ echo Path::makeAbsolute('../config/config.yaml', '/var/www/project/uploads');
+ // => /var/www/project/config/config.yaml
+
+This method is very useful if you want to be able to accept relative paths (for
+example, relative to the root directory of your project) and absolute paths at
+the same time.
+
+:method:`Symfony\\Component\\Filesystem\\Path::makeRelative` is the inverse
+operation to :method:`Symfony\\Component\\Filesystem\\Path::makeAbsolute`::
+
+ echo Path::makeRelative('/var/www/project/config/config.yaml', '/var/www/project');
+ // => config/config.yaml
+
+If the path is not within the base path, the method will prepend ".." segments
+as necessary::
+
+ echo Path::makeRelative('/var/www/project/config/config.yaml', '/var/www/project/uploads');
+ // => ../config/config.yaml
+
+Use :method:`Symfony\\Component\\Filesystem\\Path::isAbsolute` and
+:method:`Symfony\\Component\\Filesystem\\Path::isRelative` to check whether a
+path is absolute or relative::
+
+ Path::isAbsolute('C:\Programs\PHP\php.ini')
+ // => true
+
+All four methods internally canonicalize the passed path.
+
+Finding Longest Common Base Paths
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+When you store absolute file paths on the file system, this leads to a lot of
+duplicated information::
+
+ return [
+ '/var/www/vhosts/project/httpdocs/config/config.yaml',
+ '/var/www/vhosts/project/httpdocs/config/routing.yaml',
+ '/var/www/vhosts/project/httpdocs/config/services.yaml',
+ '/var/www/vhosts/project/httpdocs/images/banana.gif',
+ '/var/www/vhosts/project/httpdocs/uploads/images/nicer-banana.gif',
+ ];
+
+Especially when storing many paths, the amount of duplicated information is
+noticeable. You can use :method:`Symfony\\Component\\Filesystem\\Path::getLongestCommonBasePath`
+to check a list of paths for a common base path::
+
+ $basePath = Path::getLongestCommonBasePath(
+ '/var/www/vhosts/project/httpdocs/config/config.yaml',
+ '/var/www/vhosts/project/httpdocs/config/routing.yaml',
+ '/var/www/vhosts/project/httpdocs/config/services.yaml',
+ '/var/www/vhosts/project/httpdocs/images/banana.gif',
+ '/var/www/vhosts/project/httpdocs/uploads/images/nicer-banana.gif'
+ );
+ // => /var/www/vhosts/project/httpdocs
+
+Use this common base path to shorten the stored paths::
+
+ return [
+ $basePath.'/config/config.yaml',
+ $basePath.'/config/routing.yaml',
+ $basePath.'/config/services.yaml',
+ $basePath.'/images/banana.gif',
+ $basePath.'/uploads/images/nicer-banana.gif',
+ ];
+
+:method:`Symfony\\Component\\Filesystem\\Path::getLongestCommonBasePath` always
+returns canonical paths.
+
+Use :method:`Symfony\\Component\\Filesystem\\Path::isBasePath` to test whether a
+path is a base path of another path::
+
+ Path::isBasePath("/var/www", "/var/www/project");
+ // => true
+
+ Path::isBasePath("/var/www", "/var/www/project/..");
+ // => true
+
+ Path::isBasePath("/var/www", "/var/www/project/../..");
+ // => false
+
+Finding Directories/Root Directories
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+PHP offers the function :phpfunction:`dirname` to obtain the directory path of a
+file path. This method has a few quirks::
+
+- ``dirname()`` does not accept backslashes on UNIX
+- ``dirname("C:/Programs")`` returns "C:", not "C:/"
+- ``dirname("C:/")`` returns ".", not "C:/"
+- ``dirname("C:")`` returns ".", not "C:/"
+- ``dirname("Programs")`` returns ".", not ""
+- ``dirname()`` does not canonicalize the result
+
+:method:`Symfony\\Component\\Filesystem\\Path::getDirectory` fixes these
+shortcomings::
+
+ echo Path::getDirectory("C:\Programs");
+ // => C:/
+
+Additionally, you can use :method:`Symfony\\Component\\Filesystem\\Path::getRoot`
+to obtain the root of a path::
+
+ echo Path::getRoot("/etc/apache2/sites-available");
+ // => /
+
+ echo Path::getRoot("C:\Programs\Apache\Config");
+ // => C:/
+
Error Handling
--------------
diff --git a/components/filesystem/lock_handler.rst b/components/filesystem/lock_handler.rst
deleted file mode 100644
index e7dab2fa625..00000000000
--- a/components/filesystem/lock_handler.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-:orphan:
-
-LockHandler
-===========
-
-.. caution::
-
- The ``LockHandler`` utility was removed in Symfony 4.0. Use the new Symfony
- :doc:`Lock component ` instead.
diff --git a/components/finder.rst b/components/finder.rst
index abe849f11f5..cecc597ac64 100644
--- a/components/finder.rst
+++ b/components/finder.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Finder
- single: Components; Finder
-
The Finder Component
====================
@@ -45,7 +41,7 @@ The ``$file`` variable is an instance of
:class:`Symfony\\Component\\Finder\\SplFileInfo` which extends PHP's own
:phpclass:`SplFileInfo` to provide methods to work with relative paths.
-.. caution::
+.. warning::
The ``Finder`` object doesn't reset its internal state automatically.
This means that you need to create a new instance if you do not want
@@ -119,9 +115,7 @@ And it also works with user-defined streams::
Files or Directories
~~~~~~~~~~~~~~~~~~~~
-By default, the Finder returns files and directories; but the
-:method:`Symfony\\Component\\Finder\\Finder::files` and
-:method:`Symfony\\Component\\Finder\\Finder::directories` methods control that::
+By default, the Finder returns both files and directories. If you need to find either files or directories only, use the :method:`Symfony\\Component\\Finder\\Finder::files` and :method:`Symfony\\Component\\Finder\\Finder::directories` methods::
// look for files only; ignore directories
$finder->files();
@@ -133,6 +127,30 @@ If you want to follow `symbolic links`_, use the ``followLinks()`` method::
$finder->files()->followLinks();
+Note that this method follows links but it doesn't resolve them. Consider
+the following structure of files of directories:
+
+.. code-block:: text
+
+ ├── folder1/
+ │ ├──file1.txt
+ │ ├── file2link (symbolic link to folder2/file2.txt file)
+ │ └── folder3link (symbolic link to folder3/ directory)
+ ├── folder2/
+ │ └── file2.txt
+ └── folder3/
+ └── file3.txt
+
+If you try to find all files in ``folder1/`` via ``$finder->files()->in('/path/to/folder1/')``
+you'll get the following results:
+
+* When **not** using the ``followLinks()`` method: ``file1.txt`` and ``file2link``
+ (this link is not resolved). The ``folder3link`` doesn't appear in the results
+ because it's not followed or resolved;
+* When using the ``followLinks()`` method: ``file1.txt``, ``file2link`` (this link
+ is still not resolved) and ``folder3/file3.txt`` (this file appears in the results
+ because the ``folder1/folder3link`` link was followed).
+
Version Control Files
~~~~~~~~~~~~~~~~~~~~~
@@ -143,13 +161,22 @@ default when looking for files and directories, but you can change this with the
$finder->ignoreVCS(false);
-If the search directory contains a ``.gitignore`` file, you can reuse those
-rules to exclude files and directories from the results with the
+If the search directory and its subdirectories contain ``.gitignore`` files, you
+can reuse those rules to exclude files and directories from the results with the
:method:`Symfony\\Component\\Finder\\Finder::ignoreVCSIgnored` method::
// excludes files/directories matching the .gitignore patterns
$finder->ignoreVCSIgnored(true);
+The rules of a directory always override the rules of its parent directories.
+
+.. note::
+
+ Git looks for ``.gitignore`` files starting from the repository root directory.
+ Symfony's Finder behavior is different and it looks for ``.gitignore`` files
+ starting from the directory used to search files/directories. To be consistent
+ with Git behavior, you should explicitly search from the Git repository root.
+
File Name
~~~~~~~~~
@@ -212,7 +239,7 @@ Use the forward slash (i.e. ``/``) as the directory separator on all platforms,
including Windows. The component makes the necessary conversion internally.
The ``path()`` method accepts a string, a regular expression or an array of
-strings or regulars expressions::
+strings or regular expressions::
$finder->path('foo/bar');
$finder->path('/^foo\/bar/');
@@ -295,6 +322,7 @@ Directory Depth
By default, the Finder recursively traverses directories. Restrict the depth of
traversing with :method:`Symfony\\Component\\Finder\\Finder::depth`::
+ // this will only consider files/directories which are direct children
$finder->depth('== 0');
$finder->depth('< 3');
@@ -325,13 +353,23 @@ it is called with the file as a :class:`Symfony\\Component\\Finder\\SplFileInfo`
instance. The file is excluded from the result set if the Closure returns
``false``.
+The ``filter()`` method includes a second optional argument to prune directories.
+If set to ``true``, this method completely skips the excluded directories instead
+of traversing the entire file/directory structure and excluding them later. When
+using a closure, return ``false`` for the directories which you want to prune.
+
+Pruning directories early can improve performance significantly depending on the
+file/directory hierarchy complexity and the number of excluded directories.
+
Sorting Results
---------------
-Sort the results by name or by type (directories first, then files)::
+Sort the results by name, extension, size or type (directories first, then files)::
$finder->sortByName();
-
+ $finder->sortByCaseInsensitiveName();
+ $finder->sortByExtension();
+ $finder->sortBySize();
$finder->sortByType();
.. tip::
@@ -341,6 +379,11 @@ Sort the results by name or by type (directories first, then files)::
as its argument to use PHP's `natural sort order`_ algorithm instead (e.g.
``file1.txt``, ``file2.txt``, ``file10.txt``).
+ The ``sortByCaseInsensitiveName()`` method uses the case insensitive
+ :phpfunction:`strcasecmp` PHP function. Pass ``true`` as its argument to use
+ PHP's case insensitive `natural sort order`_ algorithm instead (i.e. the
+ :phpfunction:`strnatcasecmp` PHP function)
+
Sort the files and directories by the last accessed, changed or modified time::
$finder->sortByAccessedTime();
@@ -351,7 +394,7 @@ Sort the files and directories by the last accessed, changed or modified time::
You can also define your own sorting algorithm with the ``sort()`` method::
- $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b) {
+ $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b): int {
return strcmp($a->getRealPath(), $b->getRealPath());
});
@@ -400,7 +443,7 @@ The contents of returned files can be read with
.. _`fluent interface`: https://en.wikipedia.org/wiki/Fluent_interface
.. _`symbolic links`: https://en.wikipedia.org/wiki/Symbolic_link
.. _`Version Control Systems`: https://en.wikipedia.org/wiki/Version_control
-.. _`PHP wrapper for URL-style protocols`: https://php.net/manual/en/wrappers.php
-.. _`PHP streams`: https://php.net/streams
+.. _`PHP wrapper for URL-style protocols`: https://www.php.net/manual/en/wrappers.php
+.. _`PHP streams`: https://www.php.net/streams
.. _`IEC standard`: https://physics.nist.gov/cuu/Units/binary.html
.. _`natural sort order`: https://en.wikipedia.org/wiki/Natural_sort_order
diff --git a/components/form.rst b/components/form.rst
index bcfce8939d7..44f407e4c8e 100644
--- a/components/form.rst
+++ b/components/form.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Forms
- single: Components; Form
-
The Form Component
==================
@@ -55,7 +51,7 @@ support for very important features:
The Symfony Form component relies on other libraries to solve these problems.
Most of the time you will use Twig and the Symfony
:doc:`HttpFoundation `,
-:doc:`Translation ` and :doc:`Validator `
+:doc:`Translation ` and :doc:`Validator `
components, but you can replace any of these with a different library of your choice.
The following sections explain how to plug these libraries into the form
@@ -121,16 +117,16 @@ The following snippet adds CSRF protection to the form factory::
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Form\Forms;
- use Symfony\Component\HttpFoundation\Session\Session;
+ use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
- // creates a Session object from the HttpFoundation component
- $session = new Session();
+ // creates a RequestStack object using the current request
+ $requestStack = new RequestStack([$request]);
$csrfGenerator = new UriSafeTokenGenerator();
- $csrfStorage = new SessionTokenStorage($session);
+ $csrfStorage = new SessionTokenStorage($requestStack);
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
$formFactory = Forms::createFormFactoryBuilder()
@@ -138,6 +134,11 @@ The following snippet adds CSRF protection to the form factory::
->addExtension(new CsrfExtension($csrfManager))
->getFormFactory();
+.. versionadded:: 7.2
+
+ Support for passing requests to the constructor of the ``RequestStack``
+ class was introduced in Symfony 7.2.
+
Internally, this extension will automatically add a hidden field to every
form (called ``_token`` by default) whose value is automatically generated by
the CSRF generator and validated when binding the form.
@@ -207,7 +208,7 @@ to bootstrap or access Twig and add the :class:`Symfony\\Bridge\\Twig\\Extension
]));
$formEngine = new TwigRendererEngine([$defaultFormTheme], $twig);
$twig->addRuntimeLoader(new FactoryRuntimeLoader([
- FormRenderer::class => function () use ($formEngine, $csrfManager) {
+ FormRenderer::class => function () use ($formEngine, $csrfManager): FormRenderer {
return new FormRenderer($formEngine, $csrfManager);
},
]));
@@ -222,10 +223,6 @@ to bootstrap or access Twig and add the :class:`Symfony\\Bridge\\Twig\\Extension
// ...
->getFormFactory();
-.. versionadded:: 1.30
-
- The ``Twig\RuntimeLoader\FactoryRuntimeLoader`` was introduced in Twig 1.30.
-
The exact details of your `Twig Configuration`_ will vary, but the goal is
always to add the :class:`Symfony\\Bridge\\Twig\\Extension\\FormExtension`
to Twig, which gives you access to the Twig functions for rendering forms.
@@ -246,13 +243,13 @@ Translation
~~~~~~~~~~~
If you're using the Twig integration with one of the default form theme files
-(e.g. ``form_div_layout.html.twig``), there are 2 Twig filters (``trans``
-and ``transChoice``) that are used for translating form labels, errors, option
+(e.g. ``form_div_layout.html.twig``), there is a Twig filter (``trans``)
+that is used for translating form labels, errors, option
text and other strings.
-To add these Twig filters, you can either use the built-in
+To add the ``trans`` Twig filter, you can either use the built-in
:class:`Symfony\\Bridge\\Twig\\Extension\\TranslationExtension` that integrates
-with Symfony's Translation component, or add the 2 Twig filters yourself,
+with Symfony's Translation component, or add the Twig filter yourself,
via your own Twig extension.
To use the built-in integration, be sure that your project has Symfony's
@@ -281,7 +278,7 @@ to your ``Twig\Environment`` instance::
'en'
);
- // adds the TranslationExtension (gives us trans and transChoice filters)
+ // adds the TranslationExtension (it gives us trans filter)
$twig->addExtension(new TranslationExtension($translator));
$formFactory = Forms::createFormFactoryBuilder()
@@ -370,10 +367,6 @@ you need to. If your application uses global or static variables (not usually a
good idea), then you can store the object on some static class or do something
similar.
-Regardless of how you architect your application, remember that you
-should only have one form factory and that you'll need to be able to access
-it throughout your application.
-
.. _component-form-intro-create-simple-form:
Creating a simple Form
@@ -382,8 +375,9 @@ Creating a simple Form
.. tip::
If you're using the Symfony Framework, then the form factory is available
- automatically as a service called ``form.factory``. Also, the default
- base controller class has a :method:`Symfony\\Bundle\\FrameworkBundle\\Controller::createFormBuilder`
+ automatically as a service called ``form.factory``, you can inject it as
+ ``Symfony\Component\Form\FormFactoryInterface``. Also, the default
+ base controller class has a :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController::createFormBuilder`
method, which is a shortcut to fetch the form factory and call ``createBuilder()``
on it.
@@ -393,35 +387,20 @@ is created from the form factory.
.. configuration-block::
- .. code-block:: php-standalone
-
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\Extension\Core\Type\DateType;
-
- // ...
-
- $form = $formFactory->createBuilder()
- ->add('task', TextType::class)
- ->add('dueDate', DateType::class)
- ->getForm();
-
- var_dump($twig->render('new.html.twig', [
- 'form' => $form->createView(),
- ]));
-
.. code-block:: php-symfony
// src/Controller/TaskController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
+ use Symfony\Component\Form\Extension\Core\Type\TextType;
+ use Symfony\Component\HttpFoundation\Request;
+ use Symfony\Component\HttpFoundation\Response;
class TaskController extends AbstractController
{
- public function new(Request $request)
+ public function new(Request $request): Response
{
// createFormBuilder is a shortcut to get the "form factory"
// and then call "createBuilder()" on it
@@ -437,6 +416,22 @@ is created from the form factory.
}
}
+ .. code-block:: php-standalone
+
+ use Symfony\Component\Form\Extension\Core\Type\DateType;
+ use Symfony\Component\Form\Extension\Core\Type\TextType;
+
+ // ...
+
+ $form = $formFactory->createBuilder()
+ ->add('task', TextType::class)
+ ->add('dueDate', DateType::class)
+ ->getForm();
+
+ var_dump($twig->render('new.html.twig', [
+ 'form' => $form->createView(),
+ ]));
+
As you can see, creating a form is like writing a recipe: you call ``add()``
for each new field you want to create. The first argument to ``add()`` is the
name of your field, and the second is the fully qualified class name. The Form
@@ -453,35 +448,19 @@ an "edit" form), pass in the default data when creating your form builder:
.. configuration-block::
- .. code-block:: php-standalone
-
- use Symfony\Component\Form\Extension\Core\Type\FormType;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\Extension\Core\Type\DateType;
-
- // ...
-
- $defaults = [
- 'dueDate' => new \DateTime('tomorrow'),
- ];
-
- $form = $formFactory->createBuilder(FormType::class, $defaults)
- ->add('task', TextType::class)
- ->add('dueDate', DateType::class)
- ->getForm();
-
.. code-block:: php-symfony
// src/Controller/DefaultController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
+ use Symfony\Component\Form\Extension\Core\Type\TextType;
+ use Symfony\Component\HttpFoundation\Response;
class DefaultController extends AbstractController
{
- public function new(Request $request)
+ public function new(Request $request): Response
{
$defaults = [
'dueDate' => new \DateTime('tomorrow'),
@@ -496,6 +475,23 @@ an "edit" form), pass in the default data when creating your form builder:
}
}
+ .. code-block:: php-standalone
+
+ use Symfony\Component\Form\Extension\Core\Type\DateType;
+ use Symfony\Component\Form\Extension\Core\Type\FormType;
+ use Symfony\Component\Form\Extension\Core\Type\TextType;
+
+ // ...
+
+ $defaults = [
+ 'dueDate' => new \DateTime('tomorrow'),
+ ];
+
+ $form = $formFactory->createBuilder(FormType::class, $defaults)
+ ->add('task', TextType::class)
+ ->add('dueDate', DateType::class)
+ ->getForm();
+
.. tip::
In this example, the default data is an array. Later, when you use the
@@ -517,11 +513,11 @@ done by passing a special form "view" object to your template (notice the
{{ form_start(form) }}
{{ form_widget(form) }}
-
+
{{ form_end(form) }}
.. image:: /_images/form/simple-form.png
- :align: center
+ :alt: An HTML form showing a text box labelled "Task", three select boxes for a year, month and day labelled "Due date" and a button labelled "Create Task".
That's it! By printing ``form_widget(form)``, each field in the form is
rendered, along with a label and error message (if there is one). While this is
@@ -535,23 +531,10 @@ Changing a Form's Method and Action
By default, a form is submitted to the same URI that rendered the form with
an HTTP POST request. This behavior can be changed using the :ref:`form-option-action`
and :ref:`form-option-method` options (the ``method`` option is also used
-by ``handleRequest()`` to determine whether a form has been submitted):
+by :method:`Symfony\\Component\\Form\\Form::handleRequest` to determine whether a form has been submitted):
.. configuration-block::
- .. code-block:: php-standalone
-
- use Symfony\Component\Form\Extension\Core\Type\FormType;
-
- // ...
-
- $formBuilder = $formFactory->createBuilder(FormType::class, null, [
- 'action' => '/search',
- 'method' => 'GET',
- ]);
-
- // ...
-
.. code-block:: php-symfony
// src/Controller/DefaultController.php
@@ -559,10 +542,11 @@ by ``handleRequest()`` to determine whether a form has been submitted):
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\FormType;
+ use Symfony\Component\HttpFoundation\Response;
class DefaultController extends AbstractController
{
- public function search()
+ public function search(): Response
{
$formBuilder = $this->createFormBuilder(null, [
'action' => '/search',
@@ -573,46 +557,28 @@ by ``handleRequest()`` to determine whether a form has been submitted):
}
}
-.. _component-form-intro-handling-submission:
-
-Handling Form Submissions
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-To handle form submissions, use the :method:`Symfony\\Component\\Form\\Form::handleRequest`
-method:
-
-.. configuration-block::
-
.. code-block:: php-standalone
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\RedirectResponse;
- use Symfony\Component\Form\Extension\Core\Type\DateType;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
+ use Symfony\Component\Form\Extension\Core\Type\FormType;
// ...
- $form = $formFactory->createBuilder()
- ->add('task', TextType::class)
- ->add('dueDate', DateType::class)
- ->getForm();
-
- $request = Request::createFromGlobals();
-
- $form->handleRequest($request);
+ $formBuilder = $formFactory->createBuilder(FormType::class, null, [
+ 'action' => '/search',
+ 'method' => 'GET',
+ ]);
- if ($form->isSubmitted() && $form->isValid()) {
- $data = $form->getData();
+ // ...
- // ... perform some action, such as saving the data to the database
+.. _component-form-intro-handling-submission:
- $response = new RedirectResponse('/task/success');
- $response->prepare($request);
+Handling Form Submissions
+~~~~~~~~~~~~~~~~~~~~~~~~~
- return $response->send();
- }
+To handle form submissions, use the :method:`Symfony\\Component\\Form\\Form::handleRequest`
+method:
- // ...
+.. configuration-block::
.. code-block:: php-symfony
@@ -622,10 +588,11 @@ method:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
+ use Symfony\Component\HttpFoundation\Response;
class TaskController extends AbstractController
{
- public function new(Request $request)
+ public function new(Request $request): Response
{
$form = $this->createFormBuilder()
->add('task', TextType::class)
@@ -646,20 +613,58 @@ method:
}
}
+ .. code-block:: php-standalone
+
+ use Symfony\Component\Form\Extension\Core\Type\DateType;
+ use Symfony\Component\Form\Extension\Core\Type\TextType;
+ use Symfony\Component\HttpFoundation\RedirectResponse;
+ use Symfony\Component\HttpFoundation\Request;
+
+ // ...
+
+ $form = $formFactory->createBuilder()
+ ->add('task', TextType::class)
+ ->add('dueDate', DateType::class)
+ ->getForm();
+
+ $request = Request::createFromGlobals();
+
+ $form->handleRequest($request);
+
+ if ($form->isSubmitted() && $form->isValid()) {
+ $data = $form->getData();
+
+ // ... perform some action, such as saving the data to the database
+
+ $response = new RedirectResponse('/task/success');
+ $response->prepare($request);
+
+ return $response->send();
+ }
+
+ // ...
+
+.. warning::
+
+ The form's ``createView()`` method should be called *after* ``handleRequest()`` is
+ called. Otherwise, when using :doc:`form events `, changes done
+ in the ``*_SUBMIT`` events won't be applied to the view (like validation errors).
+
This defines a common form "workflow", which contains 3 different possibilities:
-1) On the initial GET request (i.e. when the user "surfs" to your page),
+#. On the initial GET request (i.e. when the user "surfs" to your page),
build your form and render it;
-If the request is a POST, process the submitted data (via ``handleRequest()``).
-Then:
+ If the request is a POST, process the submitted data (via :method:`Symfony\\Component\\Form\\Form::handleRequest`).
-2) if the form is invalid, re-render the form (which will now contain errors);
-3) if the form is valid, perform some action and redirect.
+ Then:
+
+#. if the form is invalid, re-render the form (which will now contain errors);
+#. if the form is valid, perform some action and redirect.
Luckily, you don't need to decide whether or not a form has been submitted.
-Pass the current request to the ``handleRequest()`` method. Then, the Form
-component will do all the necessary work for you.
+Just pass the current request to the :method:`Symfony\\Component\\Form\\Form::handleRequest`
+method. Then, the Form component will do all the necessary work for you.
.. _component-form-intro-validation:
@@ -671,39 +676,21 @@ option when building each field:
.. configuration-block::
- .. code-block:: php-standalone
-
- use Symfony\Component\Validator\Constraints\NotBlank;
- use Symfony\Component\Validator\Constraints\Type;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\Extension\Core\Type\DateType;
-
- $form = $formFactory->createBuilder()
- ->add('task', TextType::class, [
- 'constraints' => new NotBlank(),
- ])
- ->add('dueDate', DateType::class, [
- 'constraints' => [
- new NotBlank(),
- new Type(\DateTime::class),
- ]
- ])
- ->getForm();
-
.. code-block:: php-symfony
// src/Controller/DefaultController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\Validator\Constraints\NotBlank;
- use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
+ use Symfony\Component\HttpFoundation\Response;
+ use Symfony\Component\Validator\Constraints\NotBlank;
+ use Symfony\Component\Validator\Constraints\Type;
class DefaultController extends AbstractController
{
- public function new(Request $request)
+ public function new(Request $request): Response
{
$form = $this->createFormBuilder()
->add('task', TextType::class, [
@@ -713,13 +700,32 @@ option when building each field:
'constraints' => [
new NotBlank(),
new Type(\DateTime::class),
- ]
+ ],
])
->getForm();
// ...
}
}
+ .. code-block:: php-standalone
+
+ use Symfony\Component\Form\Extension\Core\Type\DateType;
+ use Symfony\Component\Form\Extension\Core\Type\TextType;
+ use Symfony\Component\Validator\Constraints\NotBlank;
+ use Symfony\Component\Validator\Constraints\Type;
+
+ $form = $formFactory->createBuilder()
+ ->add('task', TextType::class, [
+ 'constraints' => new NotBlank(),
+ ])
+ ->add('dueDate', DateType::class, [
+ 'constraints' => [
+ new NotBlank(),
+ new Type(\DateTime::class),
+ ],
+ ])
+ ->getForm();
+
When the form is bound, these validation constraints will be applied automatically
and the errors will display next to the fields on error.
@@ -747,11 +753,11 @@ method to access the list of errors. It returns a
// "firstName" field
$errors = $form['firstName']->getErrors();
- // a FormErrorIterator instance in a flattened structure
+ // a FormErrorIterator instance including child forms in a flattened structure
// use getOrigin() to determine the form causing the error
$errors = $form->getErrors(true);
- // a FormErrorIterator instance representing the form tree structure
+ // a FormErrorIterator instance including child forms without flattening the output structure
$errors = $form->getErrors(true, false);
Clearing Form Errors
@@ -763,8 +769,9 @@ method. This is useful when you'd like to validate the form without showing
validation errors to the user (i.e. during a partial AJAX submission or
:doc:`dynamic form modification `).
-Because clearing the errors makes the form valid, ``clearErrors()`` should only
-be called after testing whether the form is valid.
+Because clearing the errors makes the form valid,
+:method:`Symfony\\Component\\Form\\ClearableErrorsInterface::clearErrors`
+should only be called after testing whether the form is valid.
Learn more
----------
@@ -776,4 +783,4 @@ Learn more
/form/*
.. _Twig: https://twig.symfony.com
-.. _`Twig Configuration`: https://twig.symfony.com/doc/2.x/intro.html
+.. _`Twig Configuration`: https://twig.symfony.com/doc/3.x/intro.html
diff --git a/components/http_client.rst b/components/http_client.rst
deleted file mode 100644
index e0bf92b934c..00000000000
--- a/components/http_client.rst
+++ /dev/null
@@ -1,974 +0,0 @@
-.. index::
- single: HttpClient
- single: Components; HttpClient
-
-The HttpClient Component
-========================
-
- The HttpClient component is a low-level HTTP client with support for both
- PHP stream wrappers and cURL. It provides utilities to consume APIs and
- supports synchronous and asynchronous operations.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/http-client
-
-.. include:: /components/require_autoload.rst.inc
-
-Basic Usage
------------
-
-Use the :class:`Symfony\\Component\\HttpClient\\HttpClient` class to create the
-low-level HTTP client that makes requests, like the following ``GET`` request::
-
- use Symfony\Component\HttpClient\HttpClient;
-
- $client = HttpClient::create();
- $response = $client->request('GET', 'https://api.github.com/repos/symfony/symfony-docs');
-
- $statusCode = $response->getStatusCode();
- // $statusCode = 200
- $contentType = $response->getHeaders()['content-type'][0];
- // $contentType = 'application/json'
- $content = $response->getContent();
- // $content = '{"id":521583, "name":"symfony-docs", ...}'
- $content = $response->toArray();
- // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
-
-Performance
------------
-
-The component is built for maximum HTTP performance. By design, it is compatible
-with HTTP/2 and with doing concurrent asynchronous streamed and multiplexed
-requests/responses. Even when doing regular synchronous calls, this design
-allows keeping connections to remote hosts open between requests, improving
-performance by saving repetitive DNS resolution, SSL negotiation, etc.
-To leverage all these design benefits, the cURL extension is needed.
-
-Enabling cURL Support
-~~~~~~~~~~~~~~~~~~~~~
-
-This component supports both the native PHP streams and cURL to make the HTTP
-requests. Although both are interchangeable and provide the same features,
-including concurrent requests, HTTP/2 is only supported when using cURL.
-
-``HttpClient::create()`` selects the cURL transport if the `cURL PHP extension`_
-is enabled and falls back to PHP streams otherwise. If you prefer to select
-the transport explicitly, use the following classes to create the client::
-
- use Symfony\Component\HttpClient\CurlHttpClient;
- use Symfony\Component\HttpClient\NativeHttpClient;
-
- // uses native PHP streams
- $client = new NativeHttpClient();
-
- // uses the cURL PHP extension
- $client = new CurlHttpClient();
-
-When using this component in a full-stack Symfony application, this behavior is
-not configurable and cURL will be used automatically if the cURL PHP extension
-is installed and enabled. Otherwise, the native PHP streams will be used.
-
-HTTP/2 Support
-~~~~~~~~~~~~~~
-
-When requesting an ``https`` URL, HTTP/2 is enabled by default if libcurl >= 7.36
-is used. To force HTTP/2 for ``http`` URLs, you need to enable it explicitly via
-the ``http_version`` option::
-
- $client = HttpClient::create(['http_version' => '2.0']);
-
-Support for HTTP/2 PUSH works out of the box when libcurl >= 7.61 is used with
-PHP >= 7.2.17 / 7.3.4: pushed responses are put into a temporary cache and are
-used when a subsequent request is triggered for the corresponding URLs.
-
-Making Requests
----------------
-
-The client created with the ``HttpClient`` class provides a single ``request()``
-method to perform all kinds of HTTP requests::
-
- $response = $client->request('GET', 'https://...');
- $response = $client->request('POST', 'https://...');
- $response = $client->request('PUT', 'https://...');
- // ...
-
-Responses are always asynchronous, so that the call to the method returns
-immediately instead of waiting to receive the response::
-
- // code execution continues immediately; it doesn't wait to receive the response
- $response = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso');
-
- // getting the response headers waits until they arrive
- $contentType = $response->getHeaders()['content-type'][0];
-
- // trying to get the response contents will block the execution until
- // the full response contents are received
- $contents = $response->getContent();
-
-This component also supports :ref:`streaming responses `
-for full asynchronous applications.
-
-.. note::
-
- HTTP compression and chunked transfer encoding are automatically enabled when
- both your PHP runtime and the remote server support them.
-
-Authentication
-~~~~~~~~~~~~~~
-
-The HTTP client supports different authentication mechanisms. They can be
-defined globally when creating the client (to apply it to all requests) and to
-each request (which overrides any global authentication)::
-
- // Use the same authentication for all requests to https://example.com/
- $client = HttpClient::createForBaseUri('https://example.com/', [
- // HTTP Basic authentication (there are multiple ways of configuring it)
- 'auth_basic' => ['the-username'],
- 'auth_basic' => ['the-username', 'the-password'],
- 'auth_basic' => 'the-username:the-password',
-
- // HTTP Bearer authentication (also called token authentication)
- 'auth_bearer' => 'the-bearer-token',
-
- // Microsoft NTLM authentication (there are multiple ways of configuring it)
- 'auth_ntlm' => ['the-username'],
- 'auth_ntlm' => ['the-username', 'the-password'],
- 'auth_ntlm' => 'the-username:the-password',
- ]);
-
- $response = $client->request('GET', 'https://...', [
- // use a different HTTP Basic authentication only for this request
- 'auth_basic' => ['the-username', 'the-password'],
-
- // ...
- ]);
-
-.. note::
-
- The NTLM authentication mechanism requires using the cURL transport.
- By using ``HttpClient::createForBaseUri()``, we ensure that the auth credentials
- won't be sent to any other hosts than https://example.com/.
-
-Query String Parameters
-~~~~~~~~~~~~~~~~~~~~~~~
-
-You can either append them manually to the requested URL, or define them as an
-associative array via the ``query`` option, that will be merged with the URL::
-
- // it makes an HTTP GET request to https://httpbin.org/get?token=...&name=...
- $response = $client->request('GET', 'https://httpbin.org/get', [
- // these values are automatically encoded before including them in the URL
- 'query' => [
- 'token' => '...',
- 'name' => '...',
- ],
- ]);
-
-Headers
-~~~~~~~
-
-Use the ``headers`` option to define both the default headers added to all
-requests and the specific headers for each request::
-
- // this header is added to all requests made by this client
- $client = HttpClient::create(['headers' => [
- 'User-Agent' => 'My Fancy App',
- ]]);
-
- // this header is only included in this request and overrides the value
- // of the same header if defined globally by the HTTP client
- $response = $client->request('POST', 'https://...', [
- 'headers' => [
- 'Content-Type' => 'text/plain',
- ],
- ]);
-
-Uploading Data
-~~~~~~~~~~~~~~
-
-This component provides several methods for uploading data using the ``body``
-option. You can use regular strings, closures, iterables and resources and they'll be
-processed automatically when making the requests::
-
- $response = $client->request('POST', 'https://...', [
- // defining data using a regular string
- 'body' => 'raw data',
-
- // defining data using an array of parameters
- 'body' => ['parameter1' => 'value1', '...'],
-
- // using a closure to generate the uploaded data
- 'body' => function (int $size): string {
- // ...
- },
-
- // using a resource to get the data from it
- 'body' => fopen('/path/to/file', 'r'),
- ]);
-
-When uploading data with the ``POST`` method, if you don't define the
-``Content-Type`` HTTP header explicitly, Symfony assumes that you're uploading
-form data and adds the required
-``'Content-Type: application/x-www-form-urlencoded'`` header for you.
-
-When the ``body`` option is set as a closure, it will be called several times until
-it returns the empty string, which signals the end of the body. Each time, the
-closure should return a string smaller than the amount requested as argument.
-
-A generator or any ``Traversable`` can also be used instead of a closure.
-
-.. tip::
-
- When uploading JSON payloads, use the ``json`` option instead of ``body``. The
- given content will be JSON-encoded automatically and the request will add the
- ``Content-Type: application/json`` automatically too::
-
- $response = $client->request('POST', 'https://...', [
- 'json' => ['param1' => 'value1', '...'],
- ]);
-
- $decodedPayload = $response->toArray();
-
-To submit a form with file uploads, it is your responsibility to encode the body
-according to the ``multipart/form-data`` content-type. The
-:doc:`Symfony Mime ` component makes it a few lines of code::
-
- use Symfony\Component\Mime\Part\DataPart;
- use Symfony\Component\Mime\Part\Multipart\FormDataPart;
-
- $formFields = [
- 'regular_field' => 'some value',
- 'file_field' => DataPart::fromPath('/path/to/uploaded/file'),
- ];
- $formData = new FormDataPart($formFields);
- $client->request('POST', 'https://...', [
- 'headers' => $formData->getPreparedHeaders()->toArray(),
- 'body' => $formData->bodyToIterable(),
- ]);
-
-Cookies
-~~~~~~~
-
-The HTTP client provided by this component is stateless but handling cookies
-requires a stateful storage (because responses can update cookies and they must
-be used for subsequent requests). That's why this component doesn't handle
-cookies automatically.
-
-You can either handle cookies yourself using the ``Cookie`` HTTP header or use
-the :doc:`BrowserKit component ` which provides this
-feature and integrates seamlessly with the HttpClient component.
-
-Redirects
-~~~~~~~~~
-
-By default, the HTTP client follows redirects, up to a maximum of 20, when
-making a request. Use the ``max_redirects`` setting to configure this behavior
-(if the number of redirects is higher than the configured value, you'll get a
-:class:`Symfony\\Component\\HttpClient\\Exception\\RedirectionException`)::
-
- $response = $client->request('GET', 'https://...', [
- // 0 means to not follow any redirect
- 'max_redirects' => 0,
- ]);
-
-HTTP Proxies
-~~~~~~~~~~~~
-
-By default, this component honors the standard environment variables that your
-Operating System defines to direct the HTTP traffic through your local proxy.
-This means there is usually nothing to configure to have the client work with
-proxies, provided these env vars are properly configured.
-
-You can still set or override these settings using the ``proxy`` and ``no_proxy``
-options:
-
-* ``proxy`` should be set to the ``http://...`` URL of the proxy to get through
-
-* ``no_proxy`` disables the proxy for a comma-separated list of hosts that do not
- require it to get reached.
-
-Progress Callback
-~~~~~~~~~~~~~~~~~
-
-By providing a callable to the ``on_progress`` option, one can track
-uploads/downloads as they complete. This callback is guaranteed to be called on
-DNS resolution, on arrival of headers and on completion; additionally it is
-called when new data is uploaded or downloaded and at least once per second::
-
- $response = $client->request('GET', 'https://...', [
- 'on_progress' => function (int $dlNow, int $dlSize, array $info): void {
- // $dlNow is the number of bytes downloaded so far
- // $dlSize is the total size to be downloaded or -1 if it is unknown
- // $info is what $response->getInfo() would return at this very time
- },
- ]);
-
-Any exceptions thrown from the callback will be wrapped in an instance of
-``TransportExceptionInterface`` and will abort the request.
-
-Advanced Options
-~~~~~~~~~~~~~~~~
-
-The :class:`Symfony\\Contracts\\HttpClient\\HttpClientInterface` defines all the
-options you might need to take full control of the way the request is performed,
-including DNS pre-resolution, SSL parameters, public key pinning, etc.
-
-Processing Responses
---------------------
-
-The response returned by all HTTP clients is an object of type
-:class:`Symfony\\Contracts\\HttpClient\\ResponseInterface` which provides the
-following methods::
-
- $response = $client->request('GET', 'https://...');
-
- // gets the HTTP status code of the response
- $statusCode = $response->getStatusCode();
-
- // gets the HTTP headers as string[][] with the header names lower-cased
- $headers = $response->getHeaders();
-
- // gets the response body as a string
- $content = $response->getContent();
-
- // casts the response JSON contents to a PHP array
- $content = $response->toArray();
-
- // casts the response content to a PHP stream resource
- $content = $response->toStream();
-
- // cancels the request/response
- $response->cancel();
-
- // returns info coming from the transport layer, such as "response_headers",
- // "redirect_count", "start_time", "redirect_url", etc.
- $httpInfo = $response->getInfo();
- // you can get individual info too
- $startTime = $response->getInfo('start_time');
-
- // returns detailed logs about the requests and responses of the HTTP transaction
- $httpLogs = $response->getInfo('debug');
-
-.. note::
-
- ``$response->getInfo()`` is non-blocking: it returns *live* information
- about the response. Some of them might not be known yet (e.g. ``http_code``)
- when you'll call it.
-
-.. _http-client-streaming-responses:
-
-Streaming Responses
-~~~~~~~~~~~~~~~~~~~
-
-Call the ``stream()`` method of the HTTP client to get *chunks* of the
-response sequentially instead of waiting for the entire response::
-
- $url = 'https://releases.ubuntu.com/18.04.1/ubuntu-18.04.1-desktop-amd64.iso';
- $response = $client->request('GET', $url);
-
- // Responses are lazy: this code is executed as soon as headers are received
- if (200 !== $response->getStatusCode()) {
- throw new \Exception('...');
- }
-
- // get the response contents in chunk and save them in a file
- // response chunks implement Symfony\Contracts\HttpClient\ChunkInterface
- $fileHandler = fopen('/ubuntu.iso', 'w');
- foreach ($client->stream($response) as $chunk) {
- fwrite($fileHandler, $chunk->getContent());
- }
-
-.. note::
-
- By default, ``text/*``, JSON and XML response bodies are buffered in a local
- ``php://temp`` stream. You can control this behavior by using the ``buffer``
- option: set it to ``true``/``false`` to enable/disable buffering, or to a
- closure that should return the same based on the response headers it receives
- as argument.
-
-Canceling Responses
-~~~~~~~~~~~~~~~~~~~
-
-To abort a request (e.g. because it didn't complete in due time, or you want to
-fetch only the first bytes of the response, etc.), you can either use the
-``cancel()`` method of ``ResponseInterface``::
-
- $response->cancel()
-
-Or throw an exception from a progress callback::
-
- $response = $client->request('GET', 'https://...', [
- 'on_progress' => function (int $dlNow, int $dlSize, array $info): void {
- // ...
-
- throw new \MyException();
- },
- ]);
-
-The exception will be wrapped in an instance of ``TransportExceptionInterface``
-and will abort the request.
-
-In case the response was canceled using ``$response->cancel()``,
-``$response->getInfo('canceled')`` will return ``true``.
-
-Handling Exceptions
-~~~~~~~~~~~~~~~~~~~
-
-When the HTTP status code of the response is in the 300-599 range (i.e. 3xx,
-4xx or 5xx) your code is expected to handle it. If you don't do that, the
-``getHeaders()`` and ``getContent()`` methods throw an appropriate exception::
-
- // the response of this request will be a 403 HTTP error
- $response = $client->request('GET', 'https://httpbin.org/status/403');
-
- // this code results in a Symfony\Component\HttpClient\Exception\ClientException
- // because it doesn't check the status code of the response
- $content = $response->getContent();
-
- // pass FALSE as the optional argument to not throw an exception and return
- // instead the original response content (even if it's an error message)
- $content = $response->getContent(false);
-
-Concurrent Requests
--------------------
-
-Thanks to responses being lazy, requests are always managed concurrently.
-On a fast enough network, the following code makes 379 requests in less than
-half a second when cURL is used::
-
- use Symfony\Component\HttpClient\CurlHttpClient;
-
- $client = new CurlHttpClient();
-
- $responses = [];
-
- for ($i = 0; $i < 379; ++$i) {
- $uri = "https://http2.akamai.com/demo/tile-$i.png";
- $responses[] = $client->request('GET', $uri);
- }
-
- foreach ($responses as $response) {
- $content = $response->getContent();
- // ...
- }
-
-As you can read in the first "for" loop, requests are issued but are not consumed
-yet. That's the trick when concurrency is desired: requests should be sent
-first and be read later on. This will allow the client to monitor all pending
-requests while your code waits for a specific one, as done in each iteration of
-the above "foreach" loop.
-
-Multiplexing Responses
-~~~~~~~~~~~~~~~~~~~~~~
-
-If you look again at the snippet above, responses are read in requests' order.
-But maybe the 2nd response came back before the 1st? Fully asynchronous operations
-require being able to deal with the responses in whatever order they come back.
-
-In order to do so, the ``stream()`` method of HTTP clients accepts a list of
-responses to monitor. As mentioned :ref:`previously `,
-this method yields response chunks as they arrive from the network. By replacing
-the "foreach" in the snippet with this one, the code becomes fully async::
-
- foreach ($client->stream($responses) as $response => $chunk) {
- if ($chunk->isFirst()) {
- // headers of $response just arrived
- // $response->getHeaders() is now a non-blocking call
- } elseif ($chunk->isLast()) {
- // the full content of $response just completed
- // $response->getContent() is now a non-blocking call
- } else {
- // $chunk->getContent() will return a piece
- // of the response body that just arrived
- }
- }
-
-.. tip::
-
- Use the ``user_data`` option combined with ``$response->getInfo('user_data')``
- to track the identity of the responses in your foreach loops.
-
-Dealing with Network Timeouts
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-This component allows dealing with both request and response timeouts.
-
-A timeout can happen when e.g. DNS resolution takes too much time, when the TCP
-connection cannot be opened in the given time budget, or when the response
-content pauses for too long. This can be configured with the ``timeout`` request
-option::
-
- // A TransportExceptionInterface will be issued if nothing
- // happens for 2.5 seconds when accessing from the $response
- $response = $client->request('GET', 'https://...', ['timeout' => 2.5]);
-
-The ``default_socket_timeout`` PHP ini setting is used if the option is not set.
-
-The option can be overridden by using the 2nd argument of the ``stream()`` method.
-This allows monitoring several responses at once and applying the timeout to all
-of them in a group. If all responses become inactive for the given duration, the
-method will yield a special chunk whose ``isTimeout()`` will return ``true``::
-
- foreach ($client->stream($responses, 1.5) as $response => $chunk) {
- if ($chunk->isTimeout()) {
- // $response staled for more than 1.5 seconds
- }
- }
-
-A timeout is not necessarily an error: you can decide to stream again the
-response and get remaining contents that might come back in a new timeout, etc.
-
-.. tip::
-
- Passing ``0`` as timeout allows monitoring responses in a non-blocking way.
-
-.. note::
-
- Timeouts control how long one is willing to wait *while the HTTP transaction
- is idle*. Big responses can last as long as needed to complete, provided they
- remain active during the transfer and never pause for longer than specified.
-
- Use the ``max_duration`` option to limit the time a full request/response can last.
-
-Dealing with Network Errors
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Network errors (broken pipe, failed DNS resolution, etc.) are thrown as instances
-of :class:`Symfony\\Contracts\\HttpClient\\Exception\\TransportExceptionInterface`.
-
-First of all, you don't *have* to deal with them: letting errors bubble to your
-generic exception-handling stack might be really fine in most use cases.
-
-If you want to handle them, here is what you need to know:
-
-To catch errors, you need to wrap calls to ``$client->request()`` but also calls
-to any methods of the returned responses. This is because responses are lazy, so
-that network errors can happen when calling e.g. ``getStatusCode()`` too::
-
- try {
- // both lines can potentially throw
- $response = $client->request(...);
- $headers = $response->getHeaders();
- // ...
- } catch (TransportExceptionInterface $e) {
- // ...
- }
-
-.. note::
-
- Because ``$response->getInfo()`` is non-blocking, it shouldn't throw by design.
-
-When multiplexing responses, you can deal with errors for individual streams by
-catching ``TransportExceptionInterface`` in the foreach loop::
-
- foreach ($client->stream($responses) as $response => $chunk) {
- try {
- if ($chunk->isLast()) {
- // ... do something with $response
- }
- } catch (TransportExceptionInterface $e) {
- // ...
- }
- }
-
-Caching Requests and Responses
-------------------------------
-
-This component provides a :class:`Symfony\\Component\\HttpClient\\CachingHttpClient`
-decorator that allows caching responses and serving them from the local storage
-for next requests. The implementation leverages the
-:class:`Symfony\\Component\\HttpKernel\\HttpCache\\HttpCache` class under the hood
-so that the :doc:`HttpKernel component ` needs to be
-installed in your application::
-
- use Symfony\Component\HttpClient\CachingHttpClient;
- use Symfony\Component\HttpClient\HttpClient;
- use Symfony\Component\HttpKernel\HttpCache\Store;
-
- $store = new Store('/path/to/cache/storage/');
- $client = HttpClient::create();
- $client = new CachingHttpClient($client, $store);
-
- // this won't hit the network if the resource is already in the cache
- $response = $client->request('GET', 'https://example.com/cacheable-resource');
-
-``CachingHttpClient`` accepts a third argument to set the options of the ``HttpCache``.
-
-Scoping Client
---------------
-
-It's common that some of the HTTP client options depend on the URL of the
-request (e.g. you must set some headers when making requests to GitHub API but
-not for other hosts). If that's your case, this component provides a special
-HTTP client via the :class:`Symfony\\Component\\HttpClient\\ScopingHttpClient`
-class to autoconfigure the HTTP client based on the requested URL::
-
- use Symfony\Component\HttpClient\HttpClient;
- use Symfony\Component\HttpClient\ScopingHttpClient;
-
- $client = HttpClient::create();
- $client = new ScopingHttpClient($client, [
- // the options defined as values apply only to the URLs matching
- // the regular expressions defined as keys
- 'https://api\.github\.com/' => [
- 'headers' => [
- 'Accept' => 'application/vnd.github.v3+json',
- 'Authorization' => 'token '.$githubToken,
- ],
- ],
- // ...
- ]);
-
-You can define several scopes, so that each set of options is added only if a
-requested URL matches one of the regular expressions provided as keys.
-
-If the request URL is relative (because you use the ``base_uri`` option), the
-scoping HTTP client can't make a match. That's why you can define a third
-optional argument in its constructor which will be considered the default
-regular expression applied to relative URLs::
-
- // ...
-
- $client = new ScopingHttpClient($client,
- [
- 'https://api\.github\.com/' => [
- 'base_uri' => 'https://api.github.com/',
- // ...
- ],
- ],
- // this is the index in the previous array that defines
- // the base URI that shoud be used to resolve relative URLs
- 'https://api\.github\.com/'
- );
-
-The above example can be reduced to a simpler call::
-
- // ...
-
- $client = ScopingHttpClient::forBaseUri($client, 'https://api.github.com/', [
- // ...
- ]);
-
-This way, the provided options will be used only if the requested URL is relative
-or if it matches the ``https://api.github.com/`` base URI.
-
-Interoperability
-----------------
-
-The component is interoperable with four different abstractions for HTTP
-clients: `Symfony Contracts`_, `PSR-18`_, `HTTPlug`_ v1/v2 and native PHP streams.
-If your application uses libraries that need any of them, the component is compatible
-with all of them. They also benefit from :ref:`autowiring aliases `
-when the :ref:`framework bundle ` is used.
-
-If you are writing or maintaining a library that makes HTTP requests, you can
-decouple it from any specific HTTP client implementations by coding against
-either Symfony Contracts (recommended), PSR-18 or HTTPlug v2.
-
-Symfony Contracts
-~~~~~~~~~~~~~~~~~
-
-The interfaces found in the ``symfony/http-client-contracts`` package define
-the primary abstractions implemented by the component. Its entry point is the
-:class:`Symfony\\Contracts\\HttpClient\\HttpClientInterface`. That's the
-interface you need to code against when a client is needed::
-
- use Symfony\Contracts\HttpClient\HttpClientInterface;
-
- class MyApiLayer
- {
- private $client;
-
- public function __construct(HttpClientInterface $client)
- {
- $this->client = $client;
- }
-
- // [...]
- }
-
-All request options mentioned above (e.g. timeout management) are also defined
-in the wordings of the interface, so that any compliant implementations (like
-this component) is guaranteed to provide them. That's a major difference with
-the other abstractions, which provide none related to the transport itself.
-
-Another major feature covered by the Symfony Contracts is async/multiplexing,
-as described in the previous sections.
-
-PSR-18 and PSR-17
-~~~~~~~~~~~~~~~~~
-
-This component implements the `PSR-18`_ (HTTP Client) specifications via the
-:class:`Symfony\\Component\\HttpClient\\Psr18Client` class, which is an adapter
-to turn a Symfony ``HttpClientInterface`` into a PSR-18 ``ClientInterface``.
-This class also implements the relevant methods of `PSR-17`_ to ease creating
-request objects.
-
-To use it, you need the ``psr/http-client`` package and a `PSR-17`_ implementation:
-
-.. code-block:: terminal
-
- # installs the PSR-18 ClientInterface
- $ composer require psr/http-client
-
- # installs an efficient implementation of response and stream factories
- # with autowiring aliases provided by Symfony Flex
- $ composer require nyholm/psr7
-
- # alternatively, install the php-http/discovery package to auto-discover
- # any already installed implementations from common vendors:
- # composer require php-http/discovery
-
-Now you can make HTTP requests with the PSR-18 client as follows::
-
- use Symfony\Component\HttpClient\Psr18Client;
-
- $client = new Psr18Client();
-
- $url = 'https://symfony.com/versions.json';
- $request = $client->createRequest('GET', $url);
- $response = $client->sendRequest($request);
-
- $content = json_decode($response->getBody()->getContents(), true);
-
-HTTPlug
-~~~~~~~
-
-The `HTTPlug`_ v1 specification was published before PSR-18 and is superseded by
-it. As such, you should not use it in newly written code. The component is still
-interoperable with libraries that require it thanks to the
-:class:`Symfony\\Component\\HttpClient\\HttplugClient` class. Similarly to
-``Psr18Client`` implementing relevant parts of PSR-17, ``HttplugClient`` also
-implements the factory methods defined in the related ``php-http/message-factory``
-package.
-
-.. code-block:: terminal
-
- # Let's suppose php-http/httplug is already required by the lib you want to use
-
- # installs an efficient implementation of response and stream factories
- # with autowiring aliases provided by Symfony Flex
- $ composer require nyholm/psr7
-
- # alternatively, install the php-http/discovery package to auto-discover
- # any already installed implementations from common vendors:
- # composer require php-http/discovery
-
-Let's say you want to instantiate a class with the following constructor,
-that requires HTTPlug dependencies::
-
- use Http\Client\HttpClient;
- use Http\Message\RequestFactory;
- use Http\Message\StreamFactory;
-
- class SomeSdk
- {
- public function __construct(
- HttpClient $httpClient,
- RequestFactory $requestFactory,
- StreamFactory $streamFactory
- )
- // [...]
- }
-
-Because ``HttplugClient`` implements the three interfaces, you can use it this way::
-
- use Symfony\Component\HttpClient\HttplugClient;
-
- $httpClient = new HttplugClient();
- $apiClient = new SomeSdk($httpClient, $httpClient, $httpClient);
-
-If you'd like to work with promises, ``HttplugClient`` also implements the
-``HttpAsyncClient`` interface. To use it, you need to install the
-``guzzlehttp/promises`` package:
-
-.. code-block:: terminal
-
- $ composer require guzzlehttp/promises
-
-Then you're ready to go::
-
- use Psr\Http\Message\ResponseInterface;
- use Symfony\Component\HttpClient\HttplugClient;
-
- $httpClient = new HttplugClient();
- $request = $httpClient->createRequest('GET', 'https://my.api.com/');
- $promise = $httpClient->sendRequest($request)
- ->then(
- function (ResponseInterface $response) {
- echo 'Got status '.$response->getStatusCode();
-
- return $response;
- },
- function (\Throwable $exception) {
- echo 'Error: '.$exception->getMessage();
-
- throw $exception;
- }
- );
-
- // after you're done with sending several requests,
- // you must wait for them to complete concurrently
-
- // wait for a specific promise to resolve while monitoring them all
- $response = $promise->wait();
-
- // wait maximum 1 second for pending promises to resolve
- $httpClient->wait(1.0);
-
- // wait for all remaining promises to resolve
- $httpClient->wait();
-
-Native PHP Streams
-~~~~~~~~~~~~~~~~~~
-
-Responses implementing :class:`Symfony\\Contracts\\HttpClient\\ResponseInterface`
-can be cast to native PHP streams with
-:method:`Symfony\\Component\\HttpClient\\Response\\StreamWrapper::createResource``.
-This allows using them where native PHP streams are needed::
-
- use Symfony\Component\HttpClient\HttpClient;
- use Symfony\Component\HttpClient\Response\StreamWrapper;
-
- $client = HttpClient::create();
- $response = $client->request('GET', 'https://symfony.com/versions.json');
-
- $streamResource = StreamWrapper::createResource($response, $client);
-
- // alternatively and contrary to the previous one, this returns
- // a resource that is seekable and potentially stream_select()-able
- $streamResource = $response->toStream();
-
- echo stream_get_contents($streamResource); // outputs the content of the response
-
- // later on if you need to, you can access the response from the stream
- $response = stream_get_meta_data($streamResource)['wrapper_data']->getResponse();
-
-Symfony Framework Integration
------------------------------
-
-When using this component in a full-stack Symfony application, you can configure
-multiple clients with different configurations and inject them into your services.
-
-Configuration
-~~~~~~~~~~~~~
-
-Use the ``framework.http_client`` key to configure the default HTTP client used
-in the application. Check out the full
-:ref:`http_client config reference ` to learn about all
-the available config options:
-
-.. code-block:: yaml
-
- # config/packages/framework.yaml
- framework:
- # ...
- http_client:
- max_host_connections: 10
- default_options:
- max_redirects: 7
-
-If you want to define multiple HTTP clients, use this other expanded configuration:
-
-.. code-block:: yaml
-
- # config/packages/framework.yaml
- framework:
- # ...
- http_client:
- scoped_clients:
- crawler.client:
- headers: { 'X-Powered-By': 'ACME App' }
- http_version: '1.0'
- some_api.client:
- max_redirects: 5
-
-Injecting the HTTP Client into Services
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-If your application only needs one HTTP client, you can inject the default one
-into any services by type-hinting a constructor argument with the
-:class:`Symfony\\Contracts\\HttpClient\\HttpClientInterface`::
-
- use Symfony\Contracts\HttpClient\HttpClientInterface;
-
- class SomeService
- {
- private $client;
-
- public function __construct(HttpClientInterface $client)
- {
- $this->client = $client;
- }
- }
-
-If you have several clients, you must use any of the methods defined by Symfony
-to :ref:`choose a specific service `. Each client
-has a unique service named after its configuration.
-
-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.
-
-Testing HTTP Clients and Responses
-----------------------------------
-
-This component includes the ``MockHttpClient`` and ``MockResponse`` classes to
-use them in tests that need an HTTP client which doesn't make actual HTTP
-requests.
-
-The first way of using ``MockHttpClient`` is to pass a list of responses to its
-constructor. These will be yielded in order when requests are made::
-
- use Symfony\Component\HttpClient\MockHttpClient;
- use Symfony\Component\HttpClient\Response\MockResponse;
-
- $responses = [
- new MockResponse($body1, $info1),
- new MockResponse($body2, $info2),
- ];
-
- $client = new MockHttpClient($responses);
- // responses are returned in the same order as passed to MockHttpClient
- $response1 = $client->request('...'); // returns $responses[0]
- $response2 = $client->request('...'); // returns $responses[1]
-
-Another way of using ``MockHttpClient`` is to pass a callback that generates the
-responses dynamically when it's called::
-
- use Symfony\Component\HttpClient\MockHttpClient;
- use Symfony\Component\HttpClient\Response\MockResponse;
-
- $callback = function ($method, $url, $options) {
- return new MockResponse('...');
- };
-
- $client = new MockHttpClient($callback);
- $response = $client->request('...'); // calls $callback to get the response
-
-The responses provided to the mock client don't have to be instances of
-``MockResponse``. Any class implementing ``ResponseInterface`` will work (e.g.
-``$this->createMock(ResponseInterface::class)``).
-
-However, using ``MockResponse`` allows simulating chunked responses and timeouts::
-
- $body = function () {
- yield 'hello';
- // empty strings are turned into timeouts so that they are easy to test
- yield '';
- yield 'world';
- };
-
- $mockResponse = new MockResponse($body());
-
-.. _`cURL PHP extension`: https://php.net/curl
-.. _`PSR-17`: https://www.php-fig.org/psr/psr-17/
-.. _`PSR-18`: https://www.php-fig.org/psr/psr-18/
-.. _`HTTPlug`: https://github.com/php-http/httplug/#readme
-.. _`Symfony Contracts`: https://github.com/symfony/contracts
diff --git a/components/http_foundation.rst b/components/http_foundation.rst
index 85b879bc500..1cb87aafb24 100644
--- a/components/http_foundation.rst
+++ b/components/http_foundation.rst
@@ -1,8 +1,3 @@
-.. index::
- single: HTTP
- single: HttpFoundation
- single: Components; HttpFoundation
-
The HttpFoundation Component
============================
@@ -81,19 +76,21 @@ can be accessed via several public properties:
(``$request->headers->get('User-Agent')``).
Each property is a :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`
-instance (or a sub-class of), which is a data holder class:
+instance (or a subclass of), which is a data holder class:
-* ``request``: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;
+* ``request``: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag` or
+ :class:`Symfony\\Component\\HttpFoundation\\InputBag` if the data is
+ coming from ``$_POST`` parameters;
-* ``query``: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;
+* ``query``: :class:`Symfony\\Component\\HttpFoundation\\InputBag`;
-* ``cookies``: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;
+* ``cookies``: :class:`Symfony\\Component\\HttpFoundation\\InputBag`;
* ``attributes``: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;
-* ``files``: :class:`Symfony\\Component\\HttpFoundation\\FileBag`;
+* ``files``: :class:`Symfony\\Component\\HttpFoundation\\FileBag`;
-* ``server``: :class:`Symfony\\Component\\HttpFoundation\\ServerBag`;
+* ``server``: :class:`Symfony\\Component\\HttpFoundation\\ServerBag`;
* ``headers``: :class:`Symfony\\Component\\HttpFoundation\\HeaderBag`.
@@ -142,8 +139,18 @@ has some methods to filter the input values:
:method:`Symfony\\Component\\HttpFoundation\\ParameterBag::getInt`
Returns the parameter value converted to integer;
+:method:`Symfony\\Component\\HttpFoundation\\ParameterBag::getEnum`
+ Returns the parameter value converted to a PHP enum;
+
+:method:`Symfony\\Component\\HttpFoundation\\ParameterBag::getString`
+ Returns the parameter value as a string;
+
:method:`Symfony\\Component\\HttpFoundation\\ParameterBag::filter`
Filters the parameter by using the PHP :phpfunction:`filter_var` function.
+ If invalid values are found, a
+ :class:`Symfony\\Component\\HttpKernel\\Exception\\BadRequestHttpException`
+ is thrown. The ``FILTER_NULL_ON_FAILURE`` flag can be used to ignore invalid
+ values.
All getters take up to two arguments: the first one is the parameter name
and the second one is the default value to return if the parameter does not
@@ -161,18 +168,23 @@ exist::
// returns 'baz'
When PHP imports the request query, it handles request parameters like
-``foo[bar]=baz`` in a special way as it creates an array. So you can get the
-``foo`` parameter and you will get back an array with a ``bar`` element::
+``foo[bar]=baz`` in a special way as it creates an array. The ``get()`` method
+doesn't support returning arrays, so you need to use the following code::
// the query string is '?foo[bar]=baz'
- $request->query->get('foo');
+ // don't use $request->query->get('foo'); use the following instead:
+ $request->query->all('foo');
// returns ['bar' => 'baz']
+ // if the requested parameter does not exist, an empty array is returned:
+ $request->query->all('qux');
+ // returns []
+
$request->query->get('foo[bar]');
// returns null
- $request->query->get('foo')['bar'];
+ $request->query->all()['foo']['bar'];
// returns 'baz'
.. _component-foundation-attributes:
@@ -188,9 +200,21 @@ Finally, the raw data sent with the request body can be accessed using
$content = $request->getContent();
-For instance, this may be useful to process a JSON string sent to the
+For instance, this may be useful to process an XML string sent to the
application by a remote service using the HTTP POST method.
+If the request body is a JSON string, it can be accessed using
+:method:`Symfony\\Component\\HttpFoundation\\Request::toArray`::
+
+ $data = $request->toArray();
+
+If the request data could be ``$_POST`` data *or* a JSON string, you can use
+the :method:`Symfony\\Component\\HttpFoundation\\Request::getPayload` method
+which returns an instance of :class:`Symfony\\Component\\HttpFoundation\\InputBag`
+wrapping this data::
+
+ $data = $request->getPayload();
+
Identifying a Request
~~~~~~~~~~~~~~~~~~~~~
@@ -236,9 +260,9 @@ Accessing the Session
~~~~~~~~~~~~~~~~~~~~~
If you have a session attached to the request, you can access it via the
-:method:`Symfony\\Component\\HttpFoundation\\Request::getSession` method;
-the
-:method:`Symfony\\Component\\HttpFoundation\\Request::hasPreviousSession`
+``getSession()`` method of the :class:`Symfony\\Component\\HttpFoundation\\Request`
+or :class:`Symfony\\Component\\HttpFoundation\\RequestStack` class;
+the :method:`Symfony\\Component\\HttpFoundation\\Request::hasPreviousSession`
method tells you if the request contains a session which was started in one of
the previous requests.
@@ -272,6 +296,10 @@ this complexity and defines some methods for the most common tasks::
HeaderUtils::unquote('"foo \"bar\""');
// => 'foo "bar"'
+ // Parses a query string but maintains dots (PHP parse_str() replaces '.' by '_')
+ HeaderUtils::parseQuery('foo[bar.baz]=qux');
+ // => ['foo' => ['bar.baz' => 'qux']]
+
Accessing ``Accept-*`` Headers Data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -327,13 +355,115 @@ analysis purposes. Use the ``anonymize()`` method from the
use Symfony\Component\HttpFoundation\IpUtils;
$ipv4 = '123.234.235.236';
- $anonymousIpv4 = IPUtils::anonymize($ipv4);
+ $anonymousIpv4 = IpUtils::anonymize($ipv4);
// $anonymousIpv4 = '123.234.235.0'
$ipv6 = '2a01:198:603:10:396e:4789:8e99:890f';
- $anonymousIpv6 = IPUtils::anonymize($ipv6);
+ $anonymousIpv6 = IpUtils::anonymize($ipv6);
// $anonymousIpv6 = '2a01:198:603:10::'
+If you need even more anonymization, you can use the second and third parameters
+of the ``anonymize()`` method to specify the number of bytes that should be
+anonymized depending on the IP address format::
+
+ $ipv4 = '123.234.235.236';
+ $anonymousIpv4 = IpUtils::anonymize($ipv4, 3);
+ // $anonymousIpv4 = '123.0.0.0'
+
+ $ipv6 = '2a01:198:603:10:396e:4789:8e99:890f';
+ // (you must define the second argument (bytes to anonymize in IPv4 addresses)
+ // even when you are only anonymizing IPv6 addresses)
+ $anonymousIpv6 = IpUtils::anonymize($ipv6, 3, 10);
+ // $anonymousIpv6 = '2a01:198:603::'
+
+.. versionadded:: 7.2
+
+ The ``v4Bytes`` and ``v6Bytes`` parameters of the ``anonymize()`` method
+ were introduced in Symfony 7.2.
+
+Check If an IP Belongs to a CIDR Subnet
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you need to know if an IP address is included in a CIDR subnet, you can use
+the ``checkIp()`` method from :class:`Symfony\\Component\\HttpFoundation\\IpUtils`::
+
+ use Symfony\Component\HttpFoundation\IpUtils;
+
+ $ipv4 = '192.168.1.56';
+ $CIDRv4 = '192.168.1.0/16';
+ $isIpInCIDRv4 = IpUtils::checkIp($ipv4, $CIDRv4);
+ // $isIpInCIDRv4 = true
+
+ $ipv6 = '2001:db8:abcd:1234::1';
+ $CIDRv6 = '2001:db8:abcd::/48';
+ $isIpInCIDRv6 = IpUtils::checkIp($ipv6, $CIDRv6);
+ // $isIpInCIDRv6 = true
+
+Check if an IP Belongs to a Private Subnet
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you need to know if an IP address belongs to a private subnet, you can
+use the ``isPrivateIp()`` method from the
+:class:`Symfony\\Component\\HttpFoundation\\IpUtils` to do that::
+
+ use Symfony\Component\HttpFoundation\IpUtils;
+
+ $ipv4 = '192.168.1.1';
+ $isPrivate = IpUtils::isPrivateIp($ipv4);
+ // $isPrivate = true
+
+ $ipv6 = '2a01:198:603:10:396e:4789:8e99:890f';
+ $isPrivate = IpUtils::isPrivateIp($ipv6);
+ // $isPrivate = false
+
+Matching a Request Against a Set of Rules
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The HttpFoundation component provides some matcher classes that allow you to
+check if a given request meets certain conditions (e.g. it comes from some IP
+address, it uses a certain HTTP method, etc.):
+
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\AttributesRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\ExpressionRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\HeaderRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\HostRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\IpsRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\IsJsonRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\MethodRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\PathRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\PortRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\QueryParameterRequestMatcher`
+* :class:`Symfony\\Component\\HttpFoundation\\RequestMatcher\\SchemeRequestMatcher`
+
+You can use them individually or combine them using the
+:class:`Symfony\\Component\\HttpFoundation\\ChainRequestMatcher` class::
+
+ use Symfony\Component\HttpFoundation\ChainRequestMatcher;
+ use Symfony\Component\HttpFoundation\RequestMatcher\HostRequestMatcher;
+ use Symfony\Component\HttpFoundation\RequestMatcher\PathRequestMatcher;
+ use Symfony\Component\HttpFoundation\RequestMatcher\SchemeRequestMatcher;
+
+ // use only one criteria to match the request
+ $schemeMatcher = new SchemeRequestMatcher('https');
+ if ($schemeMatcher->matches($request)) {
+ // ...
+ }
+
+ // use a set of criteria to match the request
+ $matcher = new ChainRequestMatcher([
+ new HostRequestMatcher('example.com'),
+ new PathRequestMatcher('/admin'),
+ ]);
+
+ if ($matcher->matches($request)) {
+ // ...
+ }
+
+.. versionadded:: 7.1
+
+ The ``HeaderRequestMatcher`` and ``QueryParameterRequestMatcher`` were
+ introduced in Symfony 7.1.
+
Accessing other Data
~~~~~~~~~~~~~~~~~~~~
@@ -425,6 +555,14 @@ Sending the response to the client is done by calling the method
$response->send();
+The ``send()`` method takes an optional ``flush`` argument. If set to
+``false``, functions like ``fastcgi_finish_request()`` or
+``litespeed_finish_request()`` are not called. This is useful when debugging
+your application to see which exceptions are thrown in listeners of the
+:class:`Symfony\\Component\\HttpKernel\\Event\\TerminateEvent`. You can learn
+more about it in
+:ref:`the dedicated section about Kernel events `.
+
Setting Cookies
~~~~~~~~~~~~~~~
@@ -443,9 +581,27 @@ method takes an instance of
You can clear a cookie via the
:method:`Symfony\\Component\\HttpFoundation\\ResponseHeaderBag::clearCookie` method.
-Note you can create a
-:class:`Symfony\\Component\\HttpFoundation\\Cookie` object from a raw header
-value using :method:`Symfony\\Component\\HttpFoundation\\Cookie::fromString`.
+In addition to the ``Cookie::create()`` method, you can create a ``Cookie``
+object from a raw header value using :method:`Symfony\\Component\\HttpFoundation\\Cookie::fromString`
+method. You can also use the ``with*()`` methods to change some Cookie property (or
+to build the entire Cookie using a fluent interface). Each ``with*()`` method returns
+a new object with the modified property::
+
+ $cookie = Cookie::create('foo')
+ ->withValue('bar')
+ ->withExpires(strtotime('Fri, 20-May-2011 15:25:52 GMT'))
+ ->withDomain('.example.com')
+ ->withSecure(true);
+
+It is possible to define partitioned cookies, also known as `CHIPS`_, by using the
+:method:`Symfony\\Component\\HttpFoundation\\Cookie::withPartitioned` method::
+
+ $cookie = Cookie::create('foo')
+ ->withValue('bar')
+ ->withPartitioned();
+
+ // you can also set the partitioned argument to true when using the `create()` factory method
+ $cookie = Cookie::create('name', 'value', partitioned: true);
Managing the HTTP Cache
~~~~~~~~~~~~~~~~~~~~~~~
@@ -453,17 +609,19 @@ Managing the HTTP Cache
The :class:`Symfony\\Component\\HttpFoundation\\Response` class has a rich set
of methods to manipulate the HTTP headers related to the cache:
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setPublic`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setPrivate`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::expire`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setExpires`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setMaxAge`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setSharedMaxAge`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setTtl`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setClientTtl`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setLastModified`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setEtag`;
-* :method:`Symfony\\Component\\HttpFoundation\\Response::setVary`;
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setPublic`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setPrivate`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::expire`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setExpires`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setMaxAge`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setSharedMaxAge`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setStaleIfError`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setStaleWhileRevalidate`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setTtl`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setClientTtl`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setLastModified`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setEtag`
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setVary`
.. note::
@@ -477,13 +635,20 @@ can be used to set the most commonly used cache information in one method
call::
$response->setCache([
- 'etag' => 'abcdef',
- 'last_modified' => new \DateTime(),
- 'max_age' => 600,
- 's_maxage' => 600,
- 'private' => false,
- 'public' => true,
- 'immutable' => true,
+ 'must_revalidate' => false,
+ 'no_cache' => false,
+ 'no_store' => false,
+ 'no_transform' => false,
+ 'public' => true,
+ 'private' => false,
+ 'proxy_revalidate' => false,
+ 'max_age' => 600,
+ 's_maxage' => 600,
+ 'stale_if_error' => 86400,
+ 'stale_while_revalidate' => 60,
+ 'immutable' => true,
+ 'last_modified' => new \DateTime(),
+ 'etag' => 'abcdef',
]);
To check if the Response validators (``ETag``, ``Last-Modified``) match a
@@ -516,13 +681,24 @@ Streaming a Response
~~~~~~~~~~~~~~~~~~~~
The :class:`Symfony\\Component\\HttpFoundation\\StreamedResponse` class allows
-you to stream the Response back to the client. The response content is
-represented by a PHP callable instead of a string::
+you to stream the Response back to the client. The response content can be
+represented by a string iterable::
use Symfony\Component\HttpFoundation\StreamedResponse;
+ $chunks = ['Hello', ' World'];
+
$response = new StreamedResponse();
- $response->setCallback(function () {
+ $response->setChunks($chunks);
+ $response->send();
+
+For most complex use cases, the response content can be instead represented by
+a PHP callable::
+
+ use Symfony\Component\HttpFoundation\StreamedResponse;
+
+ $response = new StreamedResponse();
+ $response->setCallback(function (): void {
var_dump('Hello World');
flush();
sleep(2);
@@ -539,11 +715,107 @@ represented by a PHP callable instead of a string::
Additionally, PHP isn't the only layer that can buffer output. Your web
server might also buffer based on its configuration. Some servers, such as
- Nginx, let you disable buffering at the config level or by adding a special HTTP
+ nginx, let you disable buffering at the config level or by adding a special HTTP
header in the response::
- // disables FastCGI buffering in Nginx only for this response
- $response->headers->set('X-Accel-Buffering', 'no')
+ // disables FastCGI buffering in nginx only for this response
+ $response->headers->set('X-Accel-Buffering', 'no');
+
+.. versionadded:: 7.3
+
+ Support for using string iterables was introduced in Symfony 7.3.
+
+Streaming a JSON Response
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The :class:`Symfony\\Component\\HttpFoundation\\StreamedJsonResponse` allows to
+stream large JSON responses using PHP generators to keep the used resources low.
+
+The class constructor expects an array which represents the JSON structure and
+includes the list of contents to stream. In addition to PHP generators, which are
+recommended to minimize memory usage, it also supports any kind of PHP Traversable
+containing JSON serializable data::
+
+ use Symfony\Component\HttpFoundation\StreamedJsonResponse;
+
+ // any method or function returning a PHP Generator
+ function loadArticles(): \Generator {
+ yield ['title' => 'Article 1'];
+ yield ['title' => 'Article 2'];
+ yield ['title' => 'Article 3'];
+ };
+
+ $response = new StreamedJsonResponse(
+ // JSON structure with generators in which will be streamed as a list
+ [
+ '_embedded' => [
+ 'articles' => loadArticles(),
+ ],
+ ],
+ );
+
+When loading data via Doctrine, you can use the ``toIterable()`` method to
+fetch results row by row and minimize resources consumption.
+See the `Doctrine Batch processing`_ documentation for more::
+
+ public function __invoke(): Response
+ {
+ return new StreamedJsonResponse(
+ [
+ '_embedded' => [
+ 'articles' => $this->loadArticles(),
+ ],
+ ],
+ );
+ }
+
+ public function loadArticles(): \Generator
+ {
+ // get the $entityManager somehow (e.g. via constructor injection)
+ $entityManager = ...
+
+ $queryBuilder = $entityManager->createQueryBuilder();
+ $queryBuilder->from(Article::class, 'article');
+ $queryBuilder->select('article.id')
+ ->addSelect('article.title')
+ ->addSelect('article.description');
+
+ return $queryBuilder->getQuery()->toIterable();
+ }
+
+If you return a lot of data, consider calling the :phpfunction:`flush` function
+after some specific item count to send the contents to the browser::
+
+ public function loadArticles(): \Generator
+ {
+ // ...
+
+ $count = 0;
+ foreach ($queryBuilder->getQuery()->toIterable() as $article) {
+ yield $article;
+
+ if (0 === ++$count % 100) {
+ flush();
+ }
+ }
+ }
+
+Alternatively, you can also pass any iterable to ``StreamedJsonResponse``,
+including generators::
+
+ public function loadArticles(): \Generator
+ {
+ yield ['title' => 'Article 1'];
+ yield ['title' => 'Article 2'];
+ yield ['title' => 'Article 3'];
+ }
+
+ public function __invoke(): Response
+ {
+ // ...
+
+ return new StreamedJsonResponse(loadArticles());
+ }
.. _component-http-foundation-serving-files:
@@ -580,9 +852,10 @@ Alternatively, if you are serving a static file, you can use a
The ``BinaryFileResponse`` will automatically handle ``Range`` and
``If-Range`` headers from the request. It also supports ``X-Sendfile``
-(see for `Nginx`_ and `Apache`_). To make use of it, you need to determine
-whether or not the ``X-Sendfile-Type`` header should be trusted and call
-:method:`Symfony\\Component\\HttpFoundation\\BinaryFileResponse::trustXSendfileTypeHeader`
+(see `FrankenPHP X-Sendfile and X-Accel-Redirect headers`_,
+`nginx X-Accel-Redirect header`_ and `Apache mod_xsendfile module`_). To make use
+of it, you need to determine whether or not the ``X-Sendfile-Type`` header should
+be trusted and call :method:`Symfony\\Component\\HttpFoundation\\BinaryFileResponse::trustXSendfileTypeHeader`
if it should::
BinaryFileResponse::trustXSendfileTypeHeader();
@@ -617,10 +890,27 @@ or change its ``Content-Disposition``::
'filename.txt'
);
-It is possible to delete the file after the request is sent with the
+It is possible to delete the file after the response is sent with the
:method:`Symfony\\Component\\HttpFoundation\\BinaryFileResponse::deleteFileAfterSend` method.
Please note that this will not work when the ``X-Sendfile`` header is set.
+Alternatively, ``BinaryFileResponse`` supports instances of ``\SplTempFileObject``.
+This is useful when you want to serve a file that has been created in memory
+and that will be automatically deleted after the response is sent::
+
+ use Symfony\Component\HttpFoundation\BinaryFileResponse;
+
+ $file = new \SplTempFileObject();
+ $file->fwrite('Hello World');
+ $file->rewind();
+
+ $response = new BinaryFileResponse($file);
+
+.. versionadded:: 7.1
+
+ The support for ``\SplTempFileObject`` in ``BinaryFileResponse``
+ was introduced in Symfony 7.1.
+
If the size of the served file is unknown (e.g. because it's being generated on the fly,
or because a PHP stream filter is registered on it, etc.), you can pass a ``Stream``
instance to ``BinaryFileResponse``. This will disable ``Range`` and ``Content-Length``
@@ -629,7 +919,7 @@ handling, switching to chunked encoding instead::
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Stream;
- $stream = new Stream('path/to/stream');
+ $stream = new Stream('path/to/stream');
$response = new BinaryFileResponse($stream);
.. note::
@@ -664,9 +954,11 @@ class, which can make this even easier::
// if you know the data to send when creating the response
$response = new JsonResponse(['data' => 123]);
- // if you don't know the data to send when creating the response
+ // if you don't know the data to send or if you want to customize the encoding options
$response = new JsonResponse();
// ...
+ // configure any custom encoding options (if needed, it must be called before "setData()")
+ //$response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION);
$response->setData(['data' => 123]);
// if the data to send is already encoded in JSON
@@ -675,10 +967,10 @@ class, which can make this even easier::
The ``JsonResponse`` class sets the ``Content-Type`` header to
``application/json`` and encodes your data to JSON when needed.
-.. caution::
+.. danger::
To avoid XSSI `JSON Hijacking`_, you should pass an associative array
- as the outer-most array to ``JsonResponse`` and not an indexed array so
+ as the outermost array to ``JsonResponse`` and not an indexed array so
that the final result is an object (e.g. ``{"object": "not inside an array"}``)
instead of an array (e.g. ``[{"object": "inside an array"}]``). Read
the `OWASP guidelines`_ for more information.
@@ -686,6 +978,16 @@ The ``JsonResponse`` class sets the ``Content-Type`` header to
Only methods that respond to GET requests are vulnerable to XSSI 'JSON Hijacking'.
Methods responding to POST requests only remain unaffected.
+.. warning::
+
+ The ``JsonResponse`` constructor exhibits non-standard JSON encoding behavior
+ and will treat ``null`` as an empty object if passed as a constructor argument,
+ despite null being a `valid JSON top-level value`_.
+
+ This behavior cannot be changed without backwards-compatibility concerns, but
+ it's possible to call ``setData`` and pass the value there to opt-out of the
+ behavior.
+
JSONP Callback
~~~~~~~~~~~~~~
@@ -704,7 +1006,64 @@ the response content will look like this:
Session
-------
-The session information is in its own document: :doc:`/components/http_foundation/sessions`.
+The session information is in its own document: :doc:`/session`.
+
+Safe Content Preference
+-----------------------
+
+Some web sites have a "safe" mode to assist those who don't want to be exposed
+to content to which they might object. The `RFC 8674`_ specification defines a
+way for user agents to ask for safe content to a server.
+
+The specification does not define what content might be considered objectionable,
+so the concept of "safe" is not precisely defined. Rather, the term is interpreted
+by the server and within the scope of each web site that chooses to act upon this information.
+
+Symfony offers two methods to interact with this preference:
+
+* :method:`Symfony\\Component\\HttpFoundation\\Request::preferSafeContent`;
+* :method:`Symfony\\Component\\HttpFoundation\\Response::setContentSafe`;
+
+The following example shows how to detect if the user agent prefers "safe" content::
+
+ if ($request->preferSafeContent()) {
+ $response = new Response($alternativeContent);
+ // this informs the user we respected their preferences
+ $response->setContentSafe();
+
+ return $response;
+
+Generating Relative and Absolute URLs
+-------------------------------------
+
+Generating absolute and relative URLs for a given path is a common need
+in some applications. In Twig templates you can use the
+:ref:`absolute_url() ` and
+:ref:`relative_path() ` functions to do that.
+
+The :class:`Symfony\\Component\\HttpFoundation\\UrlHelper` class provides the
+same functionality for PHP code via the ``getAbsoluteUrl()`` and ``getRelativePath()``
+methods. You can inject this as a service anywhere in your application::
+
+ // src/Normalizer/UserApiNormalizer.php
+ namespace App\Normalizer;
+
+ use Symfony\Component\HttpFoundation\UrlHelper;
+
+ class UserApiNormalizer
+ {
+ public function __construct(
+ private UrlHelper $urlHelper,
+ ) {
+ }
+
+ public function normalize($user): array
+ {
+ return [
+ 'avatar' => $this->urlHelper->getAbsoluteUrl($user->avatar()->path()),
+ ];
+ }
+ }
Learn More
----------
@@ -713,13 +1072,17 @@ Learn More
:maxdepth: 1
:glob:
- /components/http_foundation/*
/controller
/controller/*
- /session/*
+ /session
/http_cache/*
-.. _Nginx: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/
-.. _Apache: https://tn123.org/mod_xsendfile/
-.. _`JSON Hijacking`: http://haacked.com/archive/2009/06/25/json-hijacking.aspx
-.. _OWASP guidelines: https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside
+.. _`FrankenPHP X-Sendfile and X-Accel-Redirect headers`: https://frankenphp.dev/docs/x-sendfile/
+.. _`nginx X-Accel-Redirect header`: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_headers
+.. _`Apache mod_xsendfile module`: https://github.com/nmaier/mod_xsendfile
+.. _`JSON Hijacking`: https://haacked.com/archive/2009/06/25/json-hijacking.aspx/
+.. _`valid JSON top-level value`: https://www.json.org/json-en.html
+.. _OWASP guidelines: https://cheatsheetseries.owasp.org/cheatsheets/AJAX_Security_Cheat_Sheet.html#always-return-json-with-an-object-on-the-outside
+.. _RFC 8674: https://tools.ietf.org/html/rfc8674
+.. _Doctrine Batch processing: https://www.doctrine-project.org/projects/doctrine-orm/en/2.14/reference/batch-processing.html#iterating-results
+.. _`CHIPS`: https://developer.mozilla.org/en-US/docs/Web/Privacy/Partitioned_cookies
diff --git a/components/http_foundation/session_configuration.rst b/components/http_foundation/session_configuration.rst
deleted file mode 100644
index 547a98ad917..00000000000
--- a/components/http_foundation/session_configuration.rst
+++ /dev/null
@@ -1,291 +0,0 @@
-.. index::
- single: HTTP
- single: HttpFoundation, Sessions
-
-Configuring Sessions and Save Handlers
-======================================
-
-This article deals with how to configure session management and fine tune it
-to your specific needs. This documentation covers save handlers, which
-store and retrieve session data, and configuring session behavior.
-
-Save Handlers
-~~~~~~~~~~~~~
-
-The PHP session workflow has 6 possible operations that may occur. The normal
-session follows ``open``, ``read``, ``write`` and ``close``, with the possibility
-of ``destroy`` and ``gc`` (garbage collection which will expire any old sessions:
-``gc`` is called randomly according to PHP's configuration and if called, it is
-invoked after the ``open`` operation). You can read more about this at
-`php.net/session.customhandler`_
-
-Native PHP Save Handlers
-------------------------
-
-So-called native handlers, are save handlers which are either compiled into
-PHP or provided by PHP extensions, such as PHP-Sqlite, PHP-Memcached and so on.
-
-All native save handlers are internal to PHP and as such, have no public facing API.
-They must be configured by ``php.ini`` directives, usually ``session.save_path`` and
-potentially other driver specific directives. Specific details can be found in
-the docblock of the ``setOptions()`` method of each class. For instance, the one
-provided by the Memcached extension can be found on `php.net/memcached.setoption`_
-
-While native save handlers can be activated by directly using
-``ini_set('session.save_handler', $name);``, Symfony provides a convenient way to
-activate these in the same way as it does for custom handlers.
-
-Symfony provides drivers for the following native save handler as an example:
-
-* :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\NativeFileSessionHandler`
-
-Example usage::
-
- use Symfony\Component\HttpFoundation\Session\Session;
- use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler;
- use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
-
- $sessionStorage = new NativeSessionStorage([], new NativeFileSessionHandler());
- $session = new Session($sessionStorage);
-
-.. note::
-
- With the exception of the ``files`` handler which is built into PHP and
- always available, the availability of the other handlers depends on those
- PHP extensions being active at runtime.
-
-.. note::
-
- Native save handlers provide a quick solution to session storage, however,
- in complex systems where you need more control, custom save handlers may
- provide more freedom and flexibility. Symfony provides several implementations
- which you may further customize as required.
-
-Custom Save Handlers
---------------------
-
-Custom handlers are those which completely replace PHP's built-in session save
-handlers by providing six callback functions which PHP calls internally at
-various points in the session workflow.
-
-The Symfony HttpFoundation component provides some by default and these can
-serve as examples if you wish to write your own.
-
-* :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\PdoSessionHandler`
-* :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\MemcachedSessionHandler`
-* :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\MigratingSessionHandler`
-* :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\RedisSessionHandler`
-* :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\MongoDbSessionHandler`
-* :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\NullSessionHandler`
-
-Example usage::
-
- use Symfony\Component\HttpFoundation\Session\Session;
- use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
- use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
-
- $pdo = new \PDO(...);
- $sessionStorage = new NativeSessionStorage([], new PdoSessionHandler($pdo));
- $session = new Session($sessionStorage);
-
-Migrating Between Save Handlers
--------------------------------
-
-If your application changes the way sessions are stored, use the
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\MigratingSessionHandler`
-to migrate between old and new save handlers without losing session data.
-
-This is the recommended migration workflow:
-
-#. Switch to the migrating handler, with your new handler as the write-only one.
- The old handler behaves as usual and sessions get written to the new one::
-
- $sessionStorage = new MigratingSessionHandler($oldSessionStorage, $newSessionStorage);
-
-#. After your session gc period, verify that the data in the new handler is correct.
-#. Update the migrating handler to use the old handler as the write-only one, so
- the sessions will now be read from the new handler. This step allows easier rollbacks::
-
- $sessionStorage = new MigratingSessionHandler($newSessionStorage, $oldSessionStorage);
-
-#. After verifying that the sessions in your application are working, switch
- from the migrating handler to the new handler.
-
-Configuring PHP Sessions
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-The :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage`
-can configure most of the ``php.ini`` configuration directives which are documented
-at `php.net/session.configuration`_.
-
-To configure these settings, pass the keys (omitting the initial ``session.`` part
-of the key) as a key-value array to the ``$options`` constructor argument.
-Or set them via the
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage::setOptions`
-method.
-
-For the sake of clarity, some key options are explained in this documentation.
-
-Session Cookie Lifetime
-~~~~~~~~~~~~~~~~~~~~~~~
-
-For security, session tokens are generally recommended to be sent as session cookies.
-You can configure the lifetime of session cookies by specifying the lifetime
-(in seconds) using the ``cookie_lifetime`` key in the constructor's ``$options``
-argument in :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage`.
-
-Setting a ``cookie_lifetime`` to ``0`` will cause the cookie to live only as
-long as the browser remains open. Generally, ``cookie_lifetime`` would be set to
-a relatively large number of days, weeks or months. It is not uncommon to set
-cookies for a year or more depending on the application.
-
-Since session cookies are just a client-side token, they are less important in
-controlling the fine details of your security settings which ultimately can only
-be securely controlled from the server side.
-
-.. note::
-
- The ``cookie_lifetime`` setting is the number of seconds the cookie should live
- for, it is not a Unix timestamp. The resulting session cookie will be stamped
- with an expiry time of ``time()`` + ``cookie_lifetime`` where the time is taken
- from the server.
-
-Configuring Garbage Collection
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When a session opens, PHP will call the ``gc`` handler randomly according to the
-probability set by ``session.gc_probability`` / ``session.gc_divisor``. For
-example if these were set to ``5/100`` respectively, it would mean a probability
-of 5%. Similarly, ``3/4`` would mean a 3 in 4 chance of being called, i.e. 75%.
-
-If the garbage collection handler is invoked, PHP will pass the value stored in
-the ``php.ini`` directive ``session.gc_maxlifetime``. The meaning in this context is
-that any stored session that was saved more than ``gc_maxlifetime`` ago should be
-deleted. This allows one to expire records based on idle time.
-
-However, some operating systems (e.g. Debian) do their own session handling and set
-the ``session.gc_probability`` variable to ``0`` to stop PHP doing garbage
-collection. That's why Symfony now overwrites this value to ``1``.
-
-If you wish to use the original value set in your ``php.ini``, add the following
-configuration:
-
-.. code-block:: yaml
-
- # config/packages/framework.yaml
- framework:
- session:
- gc_probability: null
-
-You can configure these settings by passing ``gc_probability``, ``gc_divisor``
-and ``gc_maxlifetime`` in an array to the constructor of
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage`
-or to the :method:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage::setOptions`
-method.
-
-Session Lifetime
-~~~~~~~~~~~~~~~~
-
-When a new session is created, meaning Symfony issues a new session cookie
-to the client, the cookie will be stamped with an expiry time. This is
-calculated by adding the PHP runtime configuration value in
-``session.cookie_lifetime`` with the current server time.
-
-.. note::
-
- PHP will only issue a cookie once. The client is expected to store that cookie
- for the entire lifetime. A new cookie will only be issued when the session is
- destroyed, the browser cookie is deleted, or the session ID is regenerated
- using the ``migrate()`` or ``invalidate()`` methods of the ``Session`` class.
-
- The initial cookie lifetime can be set by configuring ``NativeSessionStorage``
- using the ``setOptions(['cookie_lifetime' => 1234])`` method.
-
-.. note::
-
- A cookie lifetime of ``0`` means the cookie expires when the browser is closed.
-
-Session Idle Time/Keep Alive
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-There are often circumstances where you may want to protect, or minimize
-unauthorized use of a session when a user steps away from their terminal while
-logged in by destroying the session after a certain period of idle time. For
-example, it is common for banking applications to log the user out after just
-5 to 10 minutes of inactivity. Setting the cookie lifetime here is not
-appropriate because that can be manipulated by the client, so we must do the expiry
-on the server side. The easiest way is to implement this via garbage collection
-which runs reasonably frequently. The ``cookie_lifetime`` would be set to a
-relatively high value, and the garbage collection ``gc_maxlifetime`` would be set
-to destroy sessions at whatever the desired idle period is.
-
-The other option is specifically check if a session has expired after the
-session is started. The session can be destroyed as required. This method of
-processing can allow the expiry of sessions to be integrated into the user
-experience, for example, by displaying a message.
-
-Symfony records some basic metadata about each session to give you complete
-freedom in this area.
-
-Session Cache Limiting
-~~~~~~~~~~~~~~~~~~~~~~
-
-To avoid users seeing stale data, it's common for session-enabled resources to be
-sent with headers that disable caching. For this purpose PHP Sessions has the
-``sessions.cache_limiter`` option, which determines which headers, if any, will be
-sent with the response when the session in started.
-
-Upon construction,
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage`
-sets this global option to ``""`` (send no headers) in case the developer wishes to
-use a :class:`Symfony\\Component\\HttpFoundation\\Response` object to manage
-response headers.
-
-.. caution::
-
- If you rely on PHP Sessions to manage HTTP caching, you *must* manually set the
- ``cache_limiter`` option in
- :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage`
- to a non-empty value.
-
- For example, you may set it to PHP's default value during construction:
-
- Example usage::
-
- use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
-
- $options['cache_limiter'] = session_cache_limiter();
- $sessionStorage = new NativeSessionStorage($options);
-
-Session Metadata
-~~~~~~~~~~~~~~~~
-
-Sessions are decorated with some basic metadata to enable fine control over the
-security settings. The session object has a getter for the metadata,
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::getMetadataBag` which
-exposes an instance of :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\MetadataBag`::
-
- $session->getMetadataBag()->getCreated();
- $session->getMetadataBag()->getLastUsed();
-
-Both methods return a Unix timestamp (relative to the server).
-
-This metadata can be used to explicitly expire a session on access, e.g.::
-
- $session->start();
- if (time() - $session->getMetadataBag()->getLastUsed() > $maxIdleTime) {
- $session->invalidate();
- throw new SessionExpired(); // redirect to expired session page
- }
-
-It is also possible to tell what the ``cookie_lifetime`` was set to for a
-particular cookie by reading the ``getLifetime()`` method::
-
- $session->getMetadataBag()->getLifetime();
-
-The expiry time of the cookie can be determined by adding the created
-timestamp and the lifetime.
-
-.. _`php.net/session.customhandler`: https://php.net/session.customhandler
-.. _`php.net/session.configuration`: https://php.net/session.configuration
-.. _`php.net/memcached.setoption`: https://php.net/memcached.setoption
diff --git a/components/http_foundation/session_php_bridge.rst b/components/http_foundation/session_php_bridge.rst
deleted file mode 100644
index 00f57e59e4f..00000000000
--- a/components/http_foundation/session_php_bridge.rst
+++ /dev/null
@@ -1,48 +0,0 @@
-.. index::
- single: HTTP
- single: HttpFoundation, Sessions
-
-Integrating with Legacy Sessions
-================================
-
-Sometimes it may be necessary to integrate Symfony into a legacy application
-where you do not initially have the level of control you require.
-
-As stated elsewhere, Symfony Sessions are designed to replace the use of
-PHP's native ``session_*()`` functions and use of the ``$_SESSION``
-superglobal. Additionally, it is mandatory for Symfony to start the session.
-
-However, when there really are circumstances where this is not possible, you
-can use a special storage bridge
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\PhpBridgeSessionStorage`
-which is designed to allow Symfony to work with a session started outside of
-the Symfony HttpFoundation component. You are warned that things can interrupt
-this use-case unless you are careful: for example the legacy application
-erases ``$_SESSION``.
-
-A typical use of this might look like this::
-
- use Symfony\Component\HttpFoundation\Session\Session;
- use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
-
- // legacy application configures session
- ini_set('session.save_handler', 'files');
- ini_set('session.save_path', '/tmp');
- session_start();
-
- // Get Symfony to interface with this existing session
- $session = new Session(new PhpBridgeSessionStorage());
-
- // symfony will now interface with the existing PHP session
- $session->start();
-
-This will allow you to start using the Symfony Session API and allow migration
-of your application to Symfony sessions.
-
-.. note::
-
- Symfony sessions store data like attributes in special 'Bags' which use a
- key in the ``$_SESSION`` superglobal. This means that a Symfony session
- cannot access arbitrary keys in ``$_SESSION`` that may be set by the legacy
- application, although all the ``$_SESSION`` contents will be saved when
- the session is saved.
diff --git a/components/http_foundation/session_testing.rst b/components/http_foundation/session_testing.rst
deleted file mode 100644
index 7d8a570c17e..00000000000
--- a/components/http_foundation/session_testing.rst
+++ /dev/null
@@ -1,58 +0,0 @@
-.. index::
- single: HTTP
- single: HttpFoundation, Sessions
-
-Testing with Sessions
-=====================
-
-Symfony is designed from the ground up with code-testability in mind. In order
-to test your code which utilizes sessions, we provide two separate mock storage
-mechanisms for both unit testing and functional testing.
-
-Testing code using real sessions is tricky because PHP's workflow state is global
-and it is not possible to have multiple concurrent sessions in the same PHP
-process.
-
-The mock storage engines simulate the PHP session workflow without actually
-starting one allowing you to test your code without complications. You may also
-run multiple instances in the same PHP process.
-
-The mock storage drivers do not read or write the system globals
-``session_id()`` or ``session_name()``. Methods are provided to simulate this if
-required:
-
-* :method:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\SessionStorageInterface::getId`: Gets the
- session ID.
-
-* :method:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\SessionStorageInterface::setId`: Sets the
- session ID.
-
-* :method:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\SessionStorageInterface::getName`: Gets the
- session name.
-
-* :method:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\SessionStorageInterface::setName`: Sets the
- session name.
-
-Unit Testing
-------------
-
-For unit testing where it is not necessary to persist the session, you should
-swap out the default storage engine with
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\MockArraySessionStorage`::
-
- use Symfony\Component\HttpFoundation\Session\Session;
- use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
-
- $session = new Session(new MockArraySessionStorage());
-
-Functional Testing
-------------------
-
-For functional testing where you may need to persist session data across
-separate PHP processes, change the storage engine to
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\MockFileSessionStorage`::
-
- use Symfony\Component\HttpFoundation\Session\Session;
- use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
-
- $session = new Session(new MockFileSessionStorage());
diff --git a/components/http_foundation/sessions.rst b/components/http_foundation/sessions.rst
deleted file mode 100644
index 7cb56159d71..00000000000
--- a/components/http_foundation/sessions.rst
+++ /dev/null
@@ -1,343 +0,0 @@
-.. index::
- single: HTTP
- single: HttpFoundation, Sessions
-
-Session Management
-==================
-
-The Symfony HttpFoundation component has a very powerful and flexible session
-subsystem which is designed to provide session management through a clear
-object-oriented interface using a variety of session storage drivers.
-
-Sessions are used via the :class:`Symfony\\Component\\HttpFoundation\\Session\\Session`
-implementation of :class:`Symfony\\Component\\HttpFoundation\\Session\\SessionInterface` interface.
-
-.. caution::
-
- Make sure your PHP session isn't already started before using the Session
- class. If you have a legacy session system that starts your session, see
- :doc:`Legacy Sessions `.
-
-Quick example::
-
- use Symfony\Component\HttpFoundation\Session\Session;
-
- $session = new Session();
- $session->start();
-
- // set and get session attributes
- $session->set('name', 'Drak');
- $session->get('name');
-
- // set flash messages
- $session->getFlashBag()->add('notice', 'Profile updated');
-
- // retrieve messages
- foreach ($session->getFlashBag()->get('notice', []) as $message) {
- echo ''.$message.'
';
- }
-
-.. note::
-
- Symfony sessions are designed to replace several native PHP functions.
- Applications should avoid using ``session_start()``, ``session_regenerate_id()``,
- ``session_id()``, ``session_name()``, and ``session_destroy()`` and instead
- use the APIs in the following section.
-
-.. note::
-
- While it is recommended to explicitly start a session, a session will actually
- start on demand, that is, if any session request is made to read/write session
- data.
-
-.. caution::
-
- Symfony sessions are incompatible with ``php.ini`` directive ``session.auto_start = 1``
- This directive should be turned off in ``php.ini``, in the webserver directives or
- in ``.htaccess``.
-
-Session API
-~~~~~~~~~~~
-
-The :class:`Symfony\\Component\\HttpFoundation\\Session\\Session` class implements
-:class:`Symfony\\Component\\HttpFoundation\\Session\\SessionInterface`.
-
-The :class:`Symfony\\Component\\HttpFoundation\\Session\\Session` has the
-following API, divided into a couple of groups.
-
-Session Workflow
-................
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::start`
- Starts the session - do not use ``session_start()``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::migrate`
- Regenerates the session ID - do not use ``session_regenerate_id()``.
- This method can optionally change the lifetime of the new cookie that will
- be emitted by calling this method.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::invalidate`
- Clears all session data and regenerates session ID. Do not use ``session_destroy()``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::getId`
- Gets the session ID. Do not use ``session_id()``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::setId`
- Sets the session ID. Do not use ``session_id()``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::getName`
- Gets the session name. Do not use ``session_name()``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::setName`
- Sets the session name. Do not use ``session_name()``.
-
-Session Attributes
-..................
-
-The session attributes are stored internally in a "Bag", a PHP object that acts
-like an array. They can be set, removed, checked, etc. using the methods
-explained later in this article for the ``AttributeBagInterface`` class. See
-:ref:`attribute-bag-interface`.
-
-In addition, a few methods exist for "Bag" management:
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::registerBag`
- Registers a :class:`Symfony\\Component\\HttpFoundation\\Session\\SessionBagInterface`.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::getBag`
- Gets a :class:`Symfony\\Component\\HttpFoundation\\Session\\SessionBagInterface` by
- bag name.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::getFlashBag`
- Gets the :class:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface`.
- This is just a shortcut for convenience.
-
-Session Metadata
-................
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Session::getMetadataBag`
- Gets the :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\MetadataBag`
- which contains information about the session.
-
-Session Data Management
-~~~~~~~~~~~~~~~~~~~~~~~
-
-PHP's session management requires the use of the ``$_SESSION`` super-global,
-however, this interferes somewhat with code testability and encapsulation in an
-OOP paradigm. To help overcome this, Symfony uses *session bags* linked to the
-session to encapsulate a specific dataset of attributes or flash messages.
-
-This approach also mitigates namespace pollution within the ``$_SESSION``
-super-global because each bag stores all its data under a unique namespace.
-This allows Symfony to peacefully co-exist with other applications or libraries
-that might use the ``$_SESSION`` super-global and all data remains completely
-compatible with Symfony's session management.
-
-Symfony provides two kinds of storage bags, with two separate implementations.
-Everything is written against interfaces so you may extend or create your own
-bag types if necessary.
-
-:class:`Symfony\\Component\\HttpFoundation\\Session\\SessionBagInterface` has
-the following API which is intended mainly for internal purposes:
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\SessionBagInterface::getStorageKey`
- Returns the key which the bag will ultimately store its array under in ``$_SESSION``.
- Generally this value can be left at its default and is for internal use.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\SessionBagInterface::initialize`
- This is called internally by Symfony session storage classes to link bag data
- to the session.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\SessionBagInterface::getName`
- Returns the name of the session bag.
-
-.. _attribute-bag-interface:
-
-Attributes
-~~~~~~~~~~
-
-The purpose of the bags implementing the :class:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface`
-is to handle session attribute storage. This might include things like user ID,
-and "Remember Me" login settings or other user based state information.
-
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBag`
- This is the standard default implementation.
-
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\NamespacedAttributeBag`
- This implementation allows for attributes to be stored in a structured namespace.
-
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface`
-has the API
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface::set`
- Sets an attribute by name (``set('name', 'value')``).
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface::get`
- Gets an attribute by name (``get('name')``) and can define a default
- value when the attribute doesn't exist (``get('name', 'default_value')``).
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface::all`
- Gets all attributes as an associative array of ``name => value``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface::has`
- Returns ``true`` if the attribute exists.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface::replace`
- Sets multiple attributes at once using an associative array (``name => value``).
- If the attributes existed, they are replaced; if not, they are created.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface::remove`
- Deletes an attribute by name and returns its value.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface::clear`
- Deletes all attributes.
-
-Example::
-
- use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
- use Symfony\Component\HttpFoundation\Session\Session;
- use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
-
- $session = new Session(new NativeSessionStorage(), new AttributeBag());
- $session->set('token', 'a6c1e0b6');
- // ...
- $token = $session->get('token');
- // if the attribute may or may not exist, you can define a default value for it
- $token = $session->get('attribute-name', 'default-attribute-value');
- // ...
- $session->clear();
-
-.. _namespaced-attributes:
-
-Namespaced Attributes
-.....................
-
-Any plain key-value storage system is limited in the extent to which
-complex data can be stored since each key must be unique. You can achieve
-namespacing by introducing a naming convention to the keys so different parts of
-your application could operate without clashing. For example, ``module1.foo`` and
-``module2.foo``. However, sometimes this is not very practical when the attributes
-data is an array, for example a set of tokens. In this case, managing the array
-becomes a burden because you have to retrieve the array then process it and
-store it again::
-
- $tokens = [
- 'tokens' => [
- 'a' => 'a6c1e0b6',
- 'b' => 'f4a7b1f3',
- ],
- ];
-
-So any processing of this might quickly get ugly, even adding a token to the array::
-
- $tokens = $session->get('tokens');
- $tokens['c'] = $value;
- $session->set('tokens', $tokens);
-
-With structured namespacing, the key can be translated to the array
-structure like this using a namespace character (which defaults to ``/``)::
-
- // ...
- use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
-
- $session = new Session(new NativeSessionStorage(), new NamespacedAttributeBag());
- $session->set('tokens/c', $value);
-
-Flash Messages
-~~~~~~~~~~~~~~
-
-The purpose of the :class:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface`
-is to provide a way of setting and retrieving messages on a per session basis.
-The usual workflow would be to set flash messages in a request and to display them
-after a page redirect. For example, a user submits a form which hits an update
-controller, and after processing the controller redirects the page to either the
-updated page or an error page. Flash messages set in the previous page request
-would be displayed immediately on the subsequent page load for that session.
-This is however just one application for flash messages.
-
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\AutoExpireFlashBag`
- In this implementation, messages set in one page-load will
- be available for display only on the next page load. These messages will auto
- expire regardless of if they are retrieved or not.
-
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBag`
- In this implementation, messages will remain in the session until
- they are explicitly retrieved or cleared. This makes it possible to use ESI
- caching.
-
-:class:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface`
-has the API
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::add`
- Adds a flash message to the stack of specified type.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::set`
- Sets flashes by type; This method conveniently takes both single messages as
- a ``string`` or multiple messages in an ``array``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::get`
- Gets flashes by type and clears those flashes from the bag.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::setAll`
- Sets all flashes, accepts a keyed array of arrays ``type => [messages]``.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::all`
- Gets all flashes (as a keyed array of arrays) and clears the flashes from the bag.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::peek`
- Gets flashes by type (read only).
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::peekAll`
- Gets all flashes (read only) as keyed array of arrays.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::has`
- Returns true if the type exists, false if not.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::keys`
- Returns an array of the stored flash types.
-
-:method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::clear`
- Clears the bag.
-
-For simple applications it is usually sufficient to have one flash message per
-type, for example a confirmation notice after a form is submitted. However,
-flash messages are stored in a keyed array by flash ``$type`` which means your
-application can issue multiple messages for a given type. This allows the API
-to be used for more complex messaging in your application.
-
-Examples of setting multiple flashes::
-
- use Symfony\Component\HttpFoundation\Session\Session;
-
- $session = new Session();
- $session->start();
-
- // add flash messages
- $session->getFlashBag()->add(
- 'warning',
- 'Your config file is writable, it should be set read-only'
- );
- $session->getFlashBag()->add('error', 'Failed to update name');
- $session->getFlashBag()->add('error', 'Another error');
-
-Displaying the flash messages might look as follows.
-
-Display one type of message::
-
- // display warnings
- foreach ($session->getFlashBag()->get('warning', []) as $message) {
- echo ''.$message.'
';
- }
-
- // display errors
- foreach ($session->getFlashBag()->get('error', []) as $message) {
- echo ''.$message.'
';
- }
-
-Compact method to process display all flashes at once::
-
- foreach ($session->getFlashBag()->all() as $type => $messages) {
- foreach ($messages as $message) {
- echo ''.$message.'
';
- }
- }
diff --git a/components/http_kernel.rst b/components/http_kernel.rst
index a82bf961965..62d1e92d89b 100644
--- a/components/http_kernel.rst
+++ b/components/http_kernel.rst
@@ -1,15 +1,10 @@
-.. index::
- single: HTTP
- single: HttpKernel
- single: Components; HttpKernel
-
The HttpKernel Component
========================
The HttpKernel component provides a structured process for converting
a ``Request`` into a ``Response`` by making use of the EventDispatcher
- component. It's flexible enough to create a full-stack framework (Symfony),
- a micro-framework (Silex) or an advanced CMS system (Drupal).
+ component. It's flexible enough to create a full-stack framework (Symfony)
+ or an advanced CMS (Drupal).
Installation
------------
@@ -20,8 +15,10 @@ Installation
.. include:: /components/require_autoload.rst.inc
-The Workflow of a Request
--------------------------
+.. _the-workflow-of-a-request:
+
+The Request-Response Lifecycle
+------------------------------
.. seealso::
@@ -31,11 +28,10 @@ The Workflow of a Request
:doc:`/event_dispatcher` articles to learn about how to use it to create
controllers and define events in Symfony applications.
-
Every HTTP web interaction begins with a request and ends with a response.
Your job as a developer is to create PHP code that reads the request information
(e.g. the URL) and creates and returns a response (e.g. an HTML page or JSON string).
-This is a simplified overview of the request workflow in Symfony applications:
+This is a simplified overview of the request-response lifecycle in Symfony applications:
#. The **user** asks for a **resource** in a **browser**;
#. The **browser** sends a **request** to the **server**;
@@ -65,21 +61,23 @@ that system::
*/
public function handle(
Request $request,
- $type = self::MASTER_REQUEST,
- $catch = true
- );
+ int $type = self::MAIN_REQUEST,
+ bool $catch = true
+ ): Response;
}
Internally, :method:`HttpKernel::handle() ` -
the concrete implementation of :method:`HttpKernelInterface::handle() ` -
-defines a workflow that starts with a :class:`Symfony\\Component\\HttpFoundation\\Request`
+defines a lifecycle that starts with a :class:`Symfony\\Component\\HttpFoundation\\Request`
and ends with a :class:`Symfony\\Component\\HttpFoundation\\Response`.
.. raw:: html
-
+
-The exact details of this workflow are the key to understanding how the kernel
+The exact details of this lifecycle are the key to understanding how the kernel
(and the Symfony Framework or any other library that uses the kernel) works.
HttpKernel: Driven by Events
@@ -131,17 +129,10 @@ listeners to the events discussed below::
// trigger the kernel.terminate event
$kernel->terminate($request, $response);
-See ":ref:`http-kernel-working-example`" for a more concrete implementation.
+See ":ref:`A full working example `" for a more concrete implementation.
For general information on adding listeners to the events below, see
-:ref:`http-kernel-creating-listener`.
-
-.. caution::
-
- As of 3.1 the :class:`Symfony\\Component\\HttpKernel\\HttpKernel` accepts a
- fourth argument, which must be an instance of
- :class:`Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolverInterface`.
- In 4.0 this argument will become mandatory.
+:ref:`Creating an Event Listener `.
.. seealso::
@@ -200,8 +191,8 @@ attributes).
is the :class:`Symfony\\Component\\HttpKernel\\EventListener\\RouterListener`.
This class executes the routing layer, which returns an *array* of information
about the matched request, including the ``_controller`` and any placeholders
- that are in the route's pattern (e.g. ``{slug}``). See
- :doc:`Routing component `.
+ that are in the route's pattern (e.g. ``{slug}``). See the
+ :doc:`Routing documentation `.
This array of information is stored in the :class:`Symfony\\Component\\HttpFoundation\\Request`
object's ``attributes`` array. Adding the routing information here doesn't
@@ -236,7 +227,7 @@ This implementation is explained more in the sidebar below::
interface ControllerResolverInterface
{
- public function getController(Request $request);
+ public function getController(Request $request): callable|false;
}
Internally, the ``HttpKernel::handle()`` method first calls
@@ -249,7 +240,7 @@ on the request's information.
The Symfony Framework uses the built-in
:class:`Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver`
- class (actually, it uses a sub-class with some extra functionality
+ class (actually, it uses a subclass with some extra functionality
mentioned below). This class leverages the information that was placed
on the ``Request`` object's ``attributes`` property during the ``RouterListener``.
@@ -270,11 +261,6 @@ on the request's information.
b) A new instance of your controller class is instantiated with no
constructor arguments.
- c) If the controller implements :class:`Symfony\\Component\\DependencyInjection\\ContainerAwareInterface`,
- ``setContainer()`` is called on the controller object and the container
- is passed to it. This step is also specific to the :class:`Symfony\\Bundle\\FrameworkBundle\\Controller\\ControllerResolver`
- sub-class used by the Symfony Framework.
-
.. _component-http-kernel-kernel-controller:
3) The ``kernel.controller`` Event
@@ -289,7 +275,11 @@ After the controller callable has been determined, ``HttpKernel::handle()``
dispatches the ``kernel.controller`` event. Listeners to this event might initialize
some part of the system that needs to be initialized after certain things
have been determined (e.g. the controller, routing information) but before
-the controller is executed. For some examples, see the Symfony section below.
+the controller is executed.
+
+Another typical use-case for this event is to retrieve the attributes from
+the controller using the :method:`Symfony\\Component\\HttpKernel\\Event\\ControllerEvent::getAttributes`
+method. See the Symfony section below for some examples.
Listeners to this event can also change the controller callable completely
by calling :method:`ControllerEvent::setController `
@@ -297,18 +287,15 @@ on the event object that's passed to listeners on this event.
.. sidebar:: ``kernel.controller`` in the Symfony Framework
- There are a few minor listeners to the ``kernel.controller`` event in
- the Symfony Framework, and many deal with collecting profiler data when
- the profiler is enabled.
+ An interesting listener to ``kernel.controller`` in the Symfony
+ Framework is :class:`Symfony\\Component\\HttpKernel\\EventListener\\CacheAttributeListener`.
+ This class fetches ``#[Cache]`` attribute configuration from the
+ controller and uses it to configure :doc:`HTTP caching `
+ on the response.
- One interesting listener comes from the `SensioFrameworkExtraBundle`_. This
- listener's `@ParamConverter`_ functionality allows you to pass a full object
- (e.g. a ``Post`` object) to your controller instead of a scalar value (e.g.
- an ``id`` parameter that was on your route). The listener -
- ``ParamConverterListener`` - uses reflection to look at each of the
- arguments of the controller and tries to use different methods to convert
- those to objects, which are then stored in the ``attributes`` property of
- the ``Request`` object. Read the next section to see why this is important.
+ There are a few other minor listeners to the ``kernel.controller`` event in
+ the Symfony Framework that deal with collecting profiler data when the
+ profiler is enabled.
4) Getting the Controller Arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -347,10 +334,10 @@ of arguments that should be passed when executing that callable.
available through the `variadic`_ argument.
This functionality is provided by resolvers implementing the
- :class:`Symfony\\Component\\HttpKernel\\Controller\\ArgumentValueResolverInterface`.
+ :class:`Symfony\\Component\\HttpKernel\\Controller\\ValueResolverInterface`.
There are four implementations which provide the default behavior of
Symfony but customization is the key here. By implementing the
- ``ArgumentValueResolverInterface`` yourself and passing this to the
+ ``ValueResolverInterface`` yourself and passing this to the
``ArgumentResolver``, you can extend this functionality.
.. _component-http-kernel-calling-controller:
@@ -358,7 +345,7 @@ of arguments that should be passed when executing that callable.
5) Calling the Controller
~~~~~~~~~~~~~~~~~~~~~~~~~
-The next step ``HttpKernel::handle()`` does is executing the controller.
+The next step of ``HttpKernel::handle()`` is executing the controller.
The job of the controller is to build the response for the given resource.
This could be an HTML page, a JSON string or anything else. Unlike every
@@ -409,12 +396,12 @@ return a ``Response``.
.. sidebar:: ``kernel.view`` in the Symfony Framework
- There is no default listener inside the Symfony Framework for the ``kernel.view``
- event. However, `SensioFrameworkExtraBundle`_ *does* add a listener to this
- event. If your controller returns an array, and you place the `@Template`_
- annotation above the controller, then this listener renders a template,
- passes the array you returned from your controller to that template, and
- creates a ``Response`` containing the returned content from that template.
+ There is a default listener inside the Symfony Framework for the ``kernel.view``
+ event. If your controller action returns an array, and you apply the
+ :ref:`#[Template] attribute ` to that
+ controller action, then this listener renders a template, passes the array
+ you returned from your controller to that template, and creates a ``Response``
+ containing the returned content from that template.
Additionally, a popular community bundle `FOSRestBundle`_ implements
a listener on this event which aims to give you a robust view layer
@@ -484,11 +471,11 @@ you will trigger the ``kernel.terminate`` event where you can perform certain
actions that you may have delayed in order to return the response as quickly
as possible to the client (e.g. sending emails).
-.. caution::
+.. warning::
Internally, the HttpKernel makes use of the :phpfunction:`fastcgi_finish_request`
- PHP function. This means that at the moment, only the `PHP FPM`_ server
- API is able to send a response to the client while the server's PHP process
+ PHP function. This means that at the moment, only the `PHP FPM`_ API and the
+ `FrankenPHP`_ server are able to send a response to the client while the server's PHP process
still performs some tasks. With all other server APIs, listeners to ``kernel.terminate``
are still executed, but the response is not sent to the client until they
are all completed.
@@ -498,16 +485,10 @@ as possible to the client (e.g. sending emails).
Using the ``kernel.terminate`` event is optional, and should only be
called if your kernel implements :class:`Symfony\\Component\\HttpKernel\\TerminableInterface`.
-.. sidebar:: ``kernel.terminate`` in the Symfony Framework
-
- If you use the :ref:`memory spooling ` option of the
- default Symfony mailer, then the `EmailSenderListener`_ is activated, which
- actually delivers any emails that you scheduled to send during the request.
-
.. _component-http-kernel-kernel-exception:
-Handling Exceptions: the ``kernel.exception`` Event
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+9) Handling Exceptions: the ``kernel.exception`` Event
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Typical Purposes**: Handle some type of exception and create an appropriate
``Response`` to return for the exception
@@ -515,28 +496,41 @@ Handling Exceptions: the ``kernel.exception`` Event
:ref:`Kernel Events Information Table `
If an exception is thrown at any point inside ``HttpKernel::handle()``, another
-event - ``kernel.exception`` is thrown. Internally, the body of the ``handle()``
-function is wrapped in a try-catch block. When any exception is thrown, the
+event - ``kernel.exception`` is dispatched. Internally, the body of the ``handle()``
+method is wrapped in a try-catch block. When any exception is thrown, the
``kernel.exception`` event is dispatched so that your system can somehow respond
to the exception.
.. raw:: html
-
+
Each listener to this event is passed a :class:`Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent`
object, which you can use to access the original exception via the
-:method:`Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent::getException`
+:method:`Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent::getThrowable`
method. A typical listener on this event will check for a certain type of
exception and create an appropriate error ``Response``.
For example, to generate a 404 page, you might throw a special type of exception
and then add a listener on this event that looks for this exception and
creates and returns a 404 ``Response``. In fact, the HttpKernel component
-comes with an :class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener`,
+comes with an :class:`Symfony\\Component\\HttpKernel\\EventListener\\ErrorListener`,
which if you choose to use, will do this and more by default (see the sidebar
below for more details).
+The :class:`Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent` exposes the
+:method:`Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent::isKernelTerminating`
+method, which you can use to determine if the kernel is currently terminating
+at the moment the exception was thrown.
+
+.. versionadded:: 7.1
+
+ The
+ :method:`Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent::isKernelTerminating`
+ method was introduced in Symfony 7.1.
+
.. note::
When setting a response for the ``kernel.exception`` event, the propagation
@@ -547,14 +541,14 @@ below for more details).
There are two main listeners to ``kernel.exception`` when using the
Symfony Framework.
- **ExceptionListener in the HttpKernel Component**
+ **ErrorListener in the HttpKernel Component**
The first comes core to the HttpKernel component
- and is called :class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener`.
+ and is called :class:`Symfony\\Component\\HttpKernel\\EventListener\\ErrorListener`.
The listener has several goals:
1) The thrown exception is converted into a
- :class:`Symfony\\Component\\ErrorRenderer\\Exception\\FlattenException`
+ :class:`Symfony\\Component\\ErrorHandler\\Exception\\FlattenException`
object, which contains all the information about the request, but which
can be printed and serialized.
@@ -596,7 +590,7 @@ on creating and attaching event listeners, see :doc:`/components/event_dispatche
The name of each of the "kernel" events is defined as a constant on the
:class:`Symfony\\Component\\HttpKernel\\KernelEvents` class. Additionally, each
-event listener is passed a single argument, which is some sub-class of :class:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent`.
+event listener is passed a single argument, which is some subclass of :class:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent`.
This object contains information about the current state of the system and
each event has their own event object:
@@ -643,7 +637,7 @@ else that can be used to create a working example::
$routes = new RouteCollection();
$routes->add('hello', new Route('/hello/{name}', [
- '_controller' => function (Request $request) {
+ '_controller' => function (Request $request): Response {
return new Response(
sprintf("Hello %s", $request->get('name'))
);
@@ -673,7 +667,7 @@ Sub Requests
------------
In addition to the "main" request that's sent into ``HttpKernel::handle()``,
-you can also send so-called "sub request". A sub request looks and acts like
+you can also send a so-called "sub request". A sub request looks and acts like
any other request, but typically serves to render just one small portion of
a page instead of a full page. You'll most commonly make sub-requests from
your controller (or perhaps from inside a template, that's being rendered by
@@ -681,7 +675,9 @@ your controller).
.. raw:: html
-
+
To execute a sub request, use ``HttpKernel::handle()``, but change the second
argument as follows::
@@ -701,45 +697,51 @@ argument as follows::
This creates another full request-response cycle where this new ``Request`` is
transformed into a ``Response``. The only difference internally is that some
-listeners (e.g. security) may only act upon the master request. Each listener
-is passed some sub-class of :class:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent`,
-whose :method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::isMasterRequest`
-can be used to check if the current request is a "master" or "sub" request.
+listeners (e.g. security) may only act upon the main request. Each listener
+is passed some subclass of :class:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent`,
+whose :method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::isMainRequest`
+method can be used to check if the current request is a "main" or "sub" request.
-For example, a listener that only needs to act on the master request may
+For example, a listener that only needs to act on the main request may
look like this::
use Symfony\Component\HttpKernel\Event\RequestEvent;
// ...
- public function onKernelRequest(RequestEvent $event)
+ public function onKernelRequest(RequestEvent $event): void
{
- if (!$event->isMasterRequest()) {
+ if (!$event->isMainRequest()) {
return;
}
// ...
}
+.. note::
+
+ The default value of the ``_format`` request attribute is ``html``. If your
+ sub request returns a different format (e.g. ``json``) you can set it by
+ defining the ``_format`` attribute explicitly on the request::
+
+ $request->attributes->set('_format', 'json');
+
.. _http-kernel-resource-locator:
Locating Resources
------------------
The HttpKernel component is responsible of the bundle mechanism used in Symfony
-applications. The key feature of the bundles is that they allow to override any
-resource used by the application (config files, templates, controllers,
-translation files, etc.)
+applications. One of the key features of the bundles is that you can use logic
+paths instead of physical paths to refer to any of their resources (config files,
+templates, controllers, translation files, etc.)
-This overriding mechanism works because resources are referenced not by their
-physical path but by their logical path. For example, the ``services.xml`` file
-stored in the ``Resources/config/`` directory of a bundle called FooBundle is
-referenced as ``@FooBundle/Resources/config/services.xml``. This logical path
-will work when the application overrides that file and even if you change the
-directory of FooBundle.
+This allows to import resources even if you don't know where in the filesystem a
+bundle will be installed. For example, the ``services.xml`` file stored in the
+``Resources/config/`` directory of a bundle called FooBundle can be referenced as
+``@FooBundle/Resources/config/services.xml`` instead of ``__DIR__/Resources/config/services.xml``.
-The HttpKernel component provides a method called :method:`Symfony\\Component\\HttpKernel\\Kernel::locateResource`
-which can be used to transform logical paths into physical paths::
+This is possible thanks to the :method:`Symfony\\Component\\HttpKernel\\Kernel::locateResource`
+method provided by the kernel, which transforms logical paths into physical paths::
$path = $kernel->locateResource('@FooBundle/Resources/config/services.xml');
@@ -752,11 +754,8 @@ Learn more
/reference/events
-.. _reflection: https://php.net/manual/en/book.reflection.php
+.. _reflection: https://www.php.net/manual/en/book.reflection.php
.. _FOSRestBundle: https://github.com/friendsofsymfony/FOSRestBundle
-.. _`PHP FPM`: https://php.net/manual/en/install.fpm.php
-.. _`SensioFrameworkExtraBundle`: https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/index.html
-.. _`@ParamConverter`: https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
-.. _`@Template`: https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/view.html
-.. _`EmailSenderListener`: https://github.com/symfony/swiftmailer-bundle/blob/master/EventListener/EmailSenderListener.php
-.. _variadic: http://php.net/manual/en/functions.arguments.php
+.. _`PHP FPM`: https://www.php.net/manual/en/install.fpm.php
+.. _variadic: https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
+.. _`FrankenPHP`: https://frankenphp.dev
diff --git a/components/index.rst b/components/index.rst
deleted file mode 100644
index 14f7e7b6f51..00000000000
--- a/components/index.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-The Components
-==============
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- using_components
- *
diff --git a/components/inflector.rst b/components/inflector.rst
deleted file mode 100644
index 5e9f4325884..00000000000
--- a/components/inflector.rst
+++ /dev/null
@@ -1,64 +0,0 @@
-.. index::
- single: Inflector
- single: Components; Inflector
-
-The Inflector Component
-=======================
-
- The Inflector component converts English words between their singular and
- plural forms.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/inflector
-
-.. include:: /components/require_autoload.rst.inc
-
-When you May Need an Inflector
-------------------------------
-
-In some scenarios such as code generation and code introspection, it's usually
-required to convert words from/to singular/plural. For example, if you need to
-know which property is associated with an *adder* method, you must convert from
-plural to singular (``addStories()`` method -> ``$story`` property).
-
-Although most human languages define simple pluralization rules, they also
-define lots of exceptions. For example, the general rule in English is to add an
-``s`` at the end of the word (``book`` -> ``books``) but there are lots of
-exceptions even for common words (``woman`` -> ``women``, ``life`` -> ``lives``,
-``news`` -> ``news``, ``radius`` -> ``radii``, etc.)
-
-This component abstracts all those pluralization rules so you can convert
-from/to singular/plural with confidence. However, due to the complexity of the
-human languages, this component only provides support for the English language.
-
-Usage
------
-
-The Inflector component provides two static methods to convert from/to
-singular/plural::
-
- use Symfony\Component\Inflector\Inflector;
-
- Inflector::singularize('alumni'); // 'alumnus'
- Inflector::singularize('knives'); // 'knife'
- Inflector::singularize('mice'); // 'mouse'
-
- Inflector::pluralize('grandchild'); // 'grandchildren'
- Inflector::pluralize('news'); // 'news'
- Inflector::pluralize('bacterium'); // 'bacteria'
-
-Sometimes it's not possible to determine a unique singular/plural form for the
-given word. In those cases, the methods return an array with all the possible
-forms::
-
- use Symfony\Component\Inflector\Inflector;
-
- Inflector::singularize('indices'); // ['index', 'indix', 'indice']
- Inflector::singularize('leaves'); // ['leaf', 'leave', 'leaff']
-
- Inflector::pluralize('matrix'); // ['matricies', 'matrixes']
- Inflector::pluralize('person'); // ['persons', 'people']
diff --git a/components/intl.rst b/components/intl.rst
index 81c72bfee08..ba3cbdcb959 100644
--- a/components/intl.rst
+++ b/components/intl.rst
@@ -1,17 +1,7 @@
-.. index::
- single: Intl
- single: Components; Intl
-
The Intl Component
==================
This component provides access to the localization data of the `ICU library`_.
- It also provides a PHP replacement layer for the C `intl extension`_.
-
-.. caution::
-
- The replacement layer is limited to the locale "en". If you want to use
- other locales, you should `install the intl extension`_ instead.
.. seealso::
@@ -28,30 +18,6 @@ Installation
.. include:: /components/require_autoload.rst.inc
-If you install the component via Composer, the following classes and functions
-of the intl extension will be automatically provided if the intl extension is
-not loaded:
-
-* :phpclass:`Collator`
-* :phpclass:`IntlDateFormatter`
-* :phpclass:`Locale`
-* :phpclass:`NumberFormatter`
-* :phpfunction:`intl_error_name`
-* :phpfunction:`intl_is_failure`
-* :phpfunction:`intl_get_error_code`
-* :phpfunction:`intl_get_error_message`
-
-When the intl extension is not available, the following classes are used to
-replace the intl classes:
-
-* :class:`Symfony\\Component\\Intl\\Collator\\Collator`
-* :class:`Symfony\\Component\\Intl\\DateFormatter\\IntlDateFormatter`
-* :class:`Symfony\\Component\\Intl\\Locale\\Locale`
-* :class:`Symfony\\Component\\Intl\\NumberFormatter\\NumberFormatter`
-* :class:`Symfony\\Component\\Intl\\Globals\\IntlGlobals`
-
-Composer automatically exposes these classes in the global namespace.
-
Accessing ICU Data
------------------
@@ -66,8 +32,8 @@ This component provides the following ICU data:
Language and Script Names
~~~~~~~~~~~~~~~~~~~~~~~~~
-The ``Languages`` class provides access to the name of all languages
-according to the `ISO 639-1 alpha-2`_ list and the `ISO 639-2 alpha-3`_ list::
+The :class:`Symfony\\Component\\Intl\\Languages` class provides access to the name of all languages
+according to the `ISO 639-1 alpha-2`_ list and the `ISO 639-2 alpha-3 (2T)`_ list::
use Symfony\Component\Intl\Languages;
@@ -108,7 +74,7 @@ to catching the exception, you can also check if a given language code is valid:
$isValidLanguage = Languages::exists($languageCode);
-Or if you have a alpha3 language code you want to check::
+Or if you have an alpha3 language code you want to check::
$isValidLanguage = Languages::alpha3CodeExists($alpha3Code);
@@ -118,7 +84,7 @@ You may convert codes between two-letter alpha2 and three-letter alpha3 codes::
$alpha2Code = Languages::getAlpha2Code($alpha3Code);
-The ``Scripts`` class provides access to the optional four-letter script code
+The :class:`Symfony\\Component\\Intl\\Scripts` class provides access to the optional four-letter script code
that can follow the language code according to the `Unicode ISO 15924 Registry`_
(e.g. ``HANS`` in ``zh_HANS`` for simplified Chinese and ``HANT`` in ``zh_HANT``
for traditional Chinese)::
@@ -152,9 +118,9 @@ to catching the exception, you can also check if a given script code is valid::
Country Names
~~~~~~~~~~~~~
-The ``Countries`` class provides access to the name of all countries according
-to the `ISO 3166-1 alpha-2`_ list and the `ISO 3166-1 alpha-3`_ list
-of officially recognized countries and territories::
+The :class:`Symfony\\Component\\Intl\\Countries` class provides access to the
+name of all countries according to the `ISO 3166-1 alpha-2`_ list and the
+`ISO 3166-1 alpha-3`_ list of officially recognized countries and territories::
use Symfony\Component\Intl\Countries;
@@ -195,7 +161,7 @@ to catching the exception, you can also check if a given country code is valid::
$isValidCountry = Countries::exists($alpha2Code);
-Or if you have a alpha3 country code you want to check::
+Or if you have an alpha3 country code you want to check::
$isValidCountry = Countries::alpha3CodeExists($alpha3Code);
@@ -205,13 +171,45 @@ You may convert codes between two-letter alpha2 and three-letter alpha3 codes::
$alpha2Code = Countries::getAlpha2Code($alpha3Code);
+Numeric Country Codes
+~~~~~~~~~~~~~~~~~~~~~
+
+The `ISO 3166-1 numeric`_ standard defines three-digit country codes to represent
+countries, dependent territories, and special areas of geographical interest.
+
+The main advantage over the ISO 3166-1 alphabetic codes (alpha-2 and alpha-3) is
+that these numeric codes are independent from the writing system. The alphabetic
+codes use the 26-letter English alphabet, which might be unavailable or difficult
+to use for people and systems using non-Latin scripts (e.g. Arabic or Japanese).
+
+The :class:`Symfony\\Component\\Intl\\Countries` class provides access to these
+numeric country codes::
+
+ use Symfony\Component\Intl\Countries;
+
+ \Locale::setDefault('en');
+
+ $numericCodes = Countries::getNumericCodes();
+ // ('alpha2Code' => 'numericCode')
+ // => ['AA' => '958', 'AD' => '020', ...]
+
+ $numericCode = Countries::getNumericCode('FR');
+ // => '250'
+
+ $alpha2 = Countries::getAlpha2FromNumeric('250');
+ // => 'FR'
+
+ $exists = Countries::numericCodeExists('250');
+ // => true
+
Locales
~~~~~~~
-A locale is the combination of a language and a region. For example, "Chinese"
-is the language and ``zh_Hans_MO`` is the locale for "Chinese" (language) +
-"Simplified" (script) + "Macau SAR China" (region). The ``Locales`` class
-provides access to the name of all locales::
+A locale is the combination of a language, a region and some parameters that
+define the interface preferences of the user. For example, "Chinese" is the
+language and ``zh_Hans_MO`` is the locale for "Chinese" (language) + "Simplified"
+(script) + "Macau SAR China" (region). The :class:`Symfony\\Component\\Intl\\Locales`
+class provides access to the name of all locales::
use Symfony\Component\Intl\Locales;
@@ -242,8 +240,8 @@ to catching the exception, you can also check if a given locale code is valid::
Currencies
~~~~~~~~~~
-The ``Currencies`` class provides access to the name of all currencies as well
-as some of their information (symbol, fraction digits, etc.)::
+The :class:`Symfony\\Component\\Intl\\Currencies` class provides access to the name
+of all currencies as well as some of their information (symbol, fraction digits, etc.)::
use Symfony\Component\Intl\Currencies;
@@ -259,15 +257,37 @@ as some of their information (symbol, fraction digits, etc.)::
$symbol = Currencies::getSymbol('INR');
// => '₹'
- $fractionDigits = Currencies::getFractionDigits('INR');
- // => 2
+The fraction digits methods return the number of decimal digits to display when
+formatting numbers with this currency. Depending on the currency, this value
+can change if the number is used in cash transactions or in other scenarios
+(e.g. accounting)::
+
+ // Indian rupee defines the same value for both
+ $fractionDigits = Currencies::getFractionDigits('INR'); // returns: 2
+ $cashFractionDigits = Currencies::getCashFractionDigits('INR'); // returns: 2
- $roundingIncrement = Currencies::getRoundingIncrement('INR');
- // => 0
+ // Swedish krona defines different values
+ $fractionDigits = Currencies::getFractionDigits('SEK'); // returns: 2
+ $cashFractionDigits = Currencies::getCashFractionDigits('SEK'); // returns: 0
-All methods (except for ``getFractionDigits()`` and ``getRoundingIncrement()``)
-accept the translation locale as the last, optional parameter, which defaults to
-the current default locale::
+Some currencies require to round numbers to the nearest increment of some value
+(e.g. 5 cents). This increment might be different if numbers are formatted for
+cash transactions or other scenarios (e.g. accounting)::
+
+ // Indian rupee defines the same value for both
+ $roundingIncrement = Currencies::getRoundingIncrement('INR'); // returns: 0
+ $cashRoundingIncrement = Currencies::getCashRoundingIncrement('INR'); // returns: 0
+
+ // Canadian dollar defines different values because they have eliminated
+ // the smaller coins (1-cent and 2-cent) and prices in cash must be rounded to
+ // 5 cents (e.g. if price is 7.42 you pay 7.40; if price is 7.48 you pay 7.50)
+ $roundingIncrement = Currencies::getRoundingIncrement('CAD'); // returns: 0
+ $cashRoundingIncrement = Currencies::getCashRoundingIncrement('CAD'); // returns: 5
+
+All methods (except for ``getFractionDigits()``, ``getCashFractionDigits()``,
+``getRoundingIncrement()`` and ``getCashRoundingIncrement()``) accept the
+translation locale as the last, optional parameter, which defaults to the
+current default locale::
$currencies = Currencies::getNames('de');
// => ['AFN' => 'Afghanischer Afghani', 'EGP' => 'Ägyptisches Pfund', ...]
@@ -286,8 +306,9 @@ to catching the exception, you can also check if a given currency code is valid:
Timezones
~~~~~~~~~
-The ``Timezones`` class provides several utilities related to timezones. First,
-you can get the name and values of all timezones in all languages::
+The :class:`Symfony\\Component\\Intl\\Timezones` class provides several utilities
+related to timezones. First, you can get the name and values of all timezones in
+all languages::
use Symfony\Component\Intl\Timezones;
@@ -320,7 +341,7 @@ translate into any locale with the ``getName()`` method shown earlier::
The reverse lookup is also possible thanks to the ``getCountryCode()`` method,
which returns the code of the country where the given timezone ID belongs to::
- $countryCode = Timezones::getCountryCode('America/Vancouver')
+ $countryCode = Timezones::getCountryCode('America/Vancouver');
// => $countryCode = 'CA' (CA = Canada)
The `UTC/GMT time offsets`_ of all timezones are provided by ``getRawOffset()``
@@ -350,8 +371,8 @@ arguments to get the offset at any given point in time::
The string representation of the GMT offset can vary depending on the locale, so
you can pass the locale as the third optional argument::
- $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 28, 2019'), 'ar')); // $offset = 'غرينتش+01:00'
- $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 28, 2019'), 'dz')); // $offset = 'ཇི་ཨེམ་ཏི་+01:00'
+ $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 28, 2019'), 'ar'); // $offset = 'غرينتش+01:00'
+ $offset = Timezones::getGmtOffset('Europe/Madrid', strtotime('October 28, 2019'), 'dz'); // $offset = 'ཇི་ཨེམ་ཏི་+01:00'
If the given timezone ID doesn't exist, the methods trigger a
:class:`Symfony\\Component\\Intl\\Exception\\MissingResourceException`. In addition
@@ -359,6 +380,27 @@ to catching the exception, you can also check if a given timezone ID is valid::
$isValidTimezone = Timezones::exists($timezoneId);
+.. _component-intl-emoji-transliteration:
+
+Emoji Transliteration
+~~~~~~~~~~~~~~~~~~~~~
+
+Symfony provides utilities to translate emojis into their textual representation
+in all languages. Read the documentation about :ref:`emoji transliteration `
+to learn more about this feature.
+
+Disk Space
+----------
+
+If you need to save disk space (e.g. because you deploy to some service with tight size
+constraints), run this command (e.g. as an automated script after ``composer install``) to compress the
+internal Symfony Intl data files using the PHP ``zlib`` extension:
+
+.. code-block:: terminal
+
+ # adjust the path to the 'compress' binary based on your application installation
+ $ php ./vendor/symfony/intl/Resources/bin/compress
+
Learn more
----------
@@ -372,13 +414,12 @@ Learn more
/reference/forms/types/locale
/reference/forms/types/timezone
-.. _intl extension: https://php.net/manual/en/book.intl.php
-.. _install the intl extension: https://php.net/manual/en/intl.setup.php
-.. _ICU library: http://site.icu-project.org/
+.. _ICU library: https://icu.unicode.org/
.. _`Unicode ISO 15924 Registry`: https://www.unicode.org/iso15924/iso15924-codes.html
.. _`ISO 3166-1 alpha-2`: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
.. _`ISO 3166-1 alpha-3`: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
+.. _`ISO 3166-1 numeric`: https://en.wikipedia.org/wiki/ISO_3166-1_numeric
.. _`UTC/GMT time offsets`: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets
.. _`daylight saving time (DST)`: https://en.wikipedia.org/wiki/Daylight_saving_time
.. _`ISO 639-1 alpha-2`: https://en.wikipedia.org/wiki/ISO_639-1
-.. _`ISO 639-2 alpha-3`: https://en.wikipedia.org/wiki/ISO_639-2
+.. _`ISO 639-2 alpha-3 (2T)`: https://en.wikipedia.org/wiki/ISO_639-2
diff --git a/components/json_path.rst b/components/json_path.rst
new file mode 100644
index 00000000000..9db8e48885e
--- /dev/null
+++ b/components/json_path.rst
@@ -0,0 +1,330 @@
+The JsonPath Component
+======================
+
+.. versionadded:: 7.3
+
+ The JsonPath component was introduced in Symfony 7.3 as an
+ :doc:`experimental feature `.
+
+The JsonPath component lets you query and extract data from JSON structures.
+It implements the `RFC 9535 – JSONPath`_ standard, allowing you to navigate
+complex JSON data.
+
+Similar to the :doc:`DomCrawler component `, which lets
+you navigate and query HTML or XML documents with XPath, the JsonPath component
+offers the same convenience for traversing and searching JSON structures through
+JSONPath expressions. The component also provides an abstraction layer for data
+extraction.
+
+Installation
+------------
+
+You can install the component in your project using Composer:
+
+.. code-block:: terminal
+
+ $ composer require symfony/json-path
+
+.. include:: /components/require_autoload.rst.inc
+
+Usage
+-----
+
+To start querying a JSON document, first create a :class:`Symfony\\Component\\JsonPath\\JsonCrawler`
+object from a JSON string. The following examples use this sample "bookstore"
+JSON data::
+
+ use Symfony\Component\JsonPath\JsonCrawler;
+
+ $json = <<<'JSON'
+ {
+ "store": {
+ "book": [
+ {
+ "category": "reference",
+ "author": "Nigel Rees",
+ "title": "Sayings of the Century",
+ "price": 8.95
+ },
+ {
+ "category": "fiction",
+ "author": "Evelyn Waugh",
+ "title": "Sword of Honour",
+ "price": 12.99
+ },
+ {
+ "category": "fiction",
+ "author": "Herman Melville",
+ "title": "Moby Dick",
+ "isbn": "0-553-21311-3",
+ "price": 8.99
+ },
+ {
+ "category": "fiction",
+ "author": "John Ronald Reuel Tolkien",
+ "title": "The Lord of the Rings",
+ "isbn": "0-395-19395-8",
+ "price": 22.99
+ }
+ ],
+ "bicycle": {
+ "color": "red",
+ "price": 399
+ }
+ }
+ }
+ JSON;
+
+ $crawler = new JsonCrawler($json);
+
+Once you have the crawler instance, use its :method:`Symfony\\Component\\JsonPath\\JsonCrawler::find`
+method to start querying the data. This method returns an array of matching values.
+
+Querying with Expressions
+-------------------------
+
+The primary way to query the JSON is by passing a JSONPath expression string
+to the :method:`Symfony\\Component\\JsonPath\\JsonCrawler::find` method.
+
+Accessing a Specific Property
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Use dot notation for object keys and square brackets for array indices. The root
+of the document is represented by ``$``::
+
+ // get the title of the first book in the store
+ $titles = $crawler->find('$.store.book[0].title');
+
+ // $titles is ['Sayings of the Century']
+
+Dot notation is the default, but JSONPath provides other syntaxes for cases
+where it doesn't work. Use bracket notation (``['...']``) when a key contains
+spaces or special characters::
+
+ // this is equivalent to the previous example
+ $titles = $crawler->find('$["store"]["book"][0]["title"]');
+
+ // this expression requires brackets because some keys use dots or spaces
+ $titles = $crawler->find('$["store"]["book collection"][0]["title.original"]');
+
+ // you can combine both notations
+ $titles = $crawler->find('$["store"].book[0].title');
+
+Searching with the Descendant Operator
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The descendant operator (``..``) recursively searches for a given key, allowing
+you to find values without specifying the full path::
+
+ // get all authors from anywhere in the document
+ $authors = $crawler->find('$..author');
+
+ // $authors is ['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'John Ronald Reuel Tolkien']
+
+Filtering Results
+~~~~~~~~~~~~~~~~~
+
+JSONPath includes a filter syntax (``?(expression)``) to select items based on
+a condition. The current item within the filter is referenced by ``@``::
+
+ // get all books with a price less than 10
+ $cheapBooks = $crawler->find('$.store.book[?(@.price < 10)]');
+
+Building Queries Programmatically
+---------------------------------
+
+For more dynamic or complex query building, use the fluent API provided
+by the :class:`Symfony\\Component\\JsonPath\\JsonPath` class. This lets you
+construct a query object step by step. The ``JsonPath`` object can then be passed
+to the crawler's :method:`Symfony\\Component\\JsonPath\\JsonCrawler::find` method.
+
+The main advantage of the programmatic builder is that it automatically handles
+escaping of keys and values, preventing syntax errors::
+
+ use Symfony\Component\JsonPath\JsonPath;
+
+ $path = (new JsonPath())
+ ->key('store') // selects the 'store' key
+ ->key('book') // then the 'book' key
+ ->index(1); // then the second item (indexes start at 0)
+
+ // the created $path object is equivalent to the string '$["store"]["book"][1]'
+ $book = $crawler->find($path);
+
+ // $book contains the book object for "Sword of Honour"
+
+The :class:`Symfony\\Component\\JsonPath\\JsonPath` class provides several
+methods to build your query:
+
+* :method:`Symfony\\Component\\JsonPath\\JsonPath::key`
+ Adds a key selector. The key name is properly escaped::
+
+ // creates the path '$["key\"with\"quotes"]'
+ $path = (new JsonPath())->key('key"with"quotes');
+
+* :method:`Symfony\\Component\\JsonPath\\JsonPath::deepScan`
+ Adds the descendant operator ``..`` to perform a recursive search from the
+ current point in the path::
+
+ // get all prices in the store: '$["store"]..["price"]'
+ $path = (new JsonPath())->key('store')->deepScan()->key('price');
+
+* :method:`Symfony\\Component\\JsonPath\\JsonPath::all`
+ Adds the wildcard operator ``[*]`` to select all items in an array or object::
+
+ // creates the path '$["store"]["book"][*]'
+ $path = (new JsonPath())->key('store')->key('book')->all();
+
+* :method:`Symfony\\Component\\JsonPath\\JsonPath::index`
+ Adds an array index selector. Index numbers start at ``0``.
+
+* :method:`Symfony\\Component\\JsonPath\\JsonPath::first` /
+ :method:`Symfony\\Component\\JsonPath\\JsonPath::last`
+ Shortcuts for ``index(0)`` and ``index(-1)`` respectively::
+
+ // get the last book: '$["store"]["book"][-1]'
+ $path = (new JsonPath())->key('store')->key('book')->last();
+
+* :method:`Symfony\\Component\\JsonPath\\JsonPath::slice`
+ Adds an array slice selector ``[start:end:step]``::
+
+ // get books from index 1 up to (but not including) index 3
+ // creates the path '$["store"]["book"][1:3]'
+ $path = (new JsonPath())->key('store')->key('book')->slice(1, 3);
+
+ // get every second book from the first four books
+ // creates the path '$["store"]["book"][0:4:2]'
+ $path = (new JsonPath())->key('store')->key('book')->slice(0, 4, 2);
+
+* :method:`Symfony\\Component\\JsonPath\\JsonPath::filter`
+ Adds a filter expression. The expression string is the part that goes inside
+ the ``?()`` syntax::
+
+ // get expensive books: '$["store"]["book"][?(@.price > 20)]'
+ $path = (new JsonPath())
+ ->key('store')
+ ->key('book')
+ ->filter('@.price > 20');
+
+Advanced Querying
+-----------------
+
+For a complete overview of advanced operators like wildcards and functions within
+filters, refer to the `Querying with Expressions`_ section above. All these
+features are supported and can be combined with the programmatic builder when
+appropriate (e.g., inside a ``filter()`` expression).
+
+Testing with JSON Assertions
+----------------------------
+
+The component provides a set of PHPUnit assertions to make testing JSON data
+more convenient. Use the :class:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait`
+in your test class::
+
+ use PHPUnit\Framework\TestCase;
+ use Symfony\Component\JsonPath\Test\JsonPathAssertionsTrait;
+
+ class MyTest extends TestCase
+ {
+ use JsonPathAssertionsTrait;
+
+ public function testSomething(): void
+ {
+ $json = '{"books": [{"title": "A"}, {"title": "B"}]}';
+
+ self::assertJsonPathCount(2, '$.books[*]', $json);
+ }
+ }
+
+The trait provides the following assertion methods:
+
+* :method:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait::assertJsonPathCount`
+ Asserts that the number of elements found by the JSONPath expression matches
+ an expected count::
+
+ $json = '{"a": [1, 2, 3]}';
+ self::assertJsonPathCount(3, '$.a[*]', $json);
+
+* :method:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait::assertJsonPathEquals`
+ Asserts that the result of a JSONPath expression is equal to an expected
+ value. The comparison uses ``==`` (type coercion) instead of ``===``::
+
+ $json = '{"a": [1, 2, 3]}';
+
+ // passes because "1" == 1
+ self::assertJsonPathEquals(['1'], '$.a[0]', $json);
+
+* :method:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait::assertJsonPathNotEquals`
+ Asserts that the result of a JSONPath expression is not equal to an expected
+ value. The comparison uses ``!=`` (type coercion) instead of ``!==``::
+
+ $json = '{"a": [1, 2, 3]}';
+ self::assertJsonPathNotEquals([42], '$.a[0]', $json);
+
+* :method:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait::assertJsonPathSame`
+ Asserts that the result of a JSONPath expression is identical (``===``) to an
+ expected value. This is a strict comparison and does not perform type
+ coercion::
+
+ $json = '{"a": [1, 2, 3]}';
+
+ // fails because "1" !== 1
+ // self::assertJsonPathSame(['1'], '$.a[0]', $json);
+
+ self::assertJsonPathSame([1], '$.a[0]', $json);
+
+* :method:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait::assertJsonPathNotSame`
+ Asserts that the result of a JSONPath expression is not identical (``!==``) to
+ an expected value::
+
+ $json = '{"a": [1, 2, 3]}';
+ self::assertJsonPathNotSame(['1'], '$.a[0]', $json);
+
+* :method:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait::assertJsonPathContains`
+ Asserts that a given value is found within the array of results from the
+ JSONPath expression::
+
+ $json = '{"tags": ["php", "symfony", "json"]}';
+ self::assertJsonPathContains('symfony', '$.tags[*]', $json);
+
+* :method:`Symfony\\Component\\JsonPath\\Test\\JsonPathAssertionsTrait::assertJsonPathNotContains`
+ Asserts that a given value is NOT found within the array of results from the
+ JSONPath expression::
+
+ $json = '{"tags": ["php", "symfony", "json"]}';
+ self::assertJsonPathNotContains('java', '$.tags[*]', $json);
+
+Error Handling
+--------------
+
+The component throws specific exceptions for invalid input or queries:
+
+* :class:`Symfony\\Component\\JsonPath\\Exception\\InvalidArgumentException`:
+ Thrown if the input to the ``JsonCrawler`` constructor is not a valid JSON string;
+* :class:`Symfony\\Component\\JsonPath\\Exception\\InvalidJsonStringInputException`:
+ Thrown during a ``find()`` call if the JSON string is malformed (e.g., syntax error);
+* :class:`Symfony\\Component\\JsonPath\\Exception\\JsonCrawlerException`:
+ Thrown for errors within the JsonPath expression itself, such as using an
+ unknown function
+
+Example of handling errors::
+
+ use Symfony\Component\JsonPath\Exception\InvalidJsonStringInputException;
+ use Symfony\Component\JsonPath\Exception\JsonCrawlerException;
+
+ try {
+ // the following line contains malformed JSON
+ $crawler = new JsonCrawler('{"store": }');
+ $crawler->find('$..*');
+ } catch (InvalidJsonStringInputException $e) {
+ // ... handle error
+ }
+
+ try {
+ // the following line contains an invalid query
+ $crawler->find('$.store.book[?unknown_function(@.price)]');
+ } catch (JsonCrawlerException $e) {
+ // ... handle error
+ }
+
+.. _`RFC 9535 – JSONPath`: https://datatracker.ietf.org/doc/html/rfc9535
diff --git a/components/ldap.rst b/components/ldap.rst
index 73963d5f243..e52a341986c 100644
--- a/components/ldap.rst
+++ b/components/ldap.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Ldap
- single: Components; Ldap
-
The Ldap Component
==================
@@ -74,6 +70,23 @@ distinguished name (DN) and the password of a user::
$ldap->bind($dn, $password);
+.. danger::
+
+ When the LDAP server allows unauthenticated binds, a blank password will always be valid.
+
+You can also use the :method:`Symfony\\Component\\Ldap\\Ldap::saslBind` method
+for binding to an LDAP server using `SASL`_::
+
+ // this method defines other optional arguments like $mech, $realm, $authcId, etc.
+ $ldap->saslBind($dn, $password);
+
+After binding to the LDAP server, you can use the :method:`Symfony\\Component\\Ldap\\Ldap::whoami`
+method to get the distinguished name (DN) of the authenticated and authorized user.
+
+.. versionadded:: 7.2
+
+ The ``saslBind()`` and ``whoami()`` methods were introduced in Symfony 7.2.
+
Once bound (or if you enabled anonymous authentication on your
LDAP server), you may query the LDAP server using the
:method:`Symfony\\Component\\Ldap\\Ldap::query` method::
@@ -111,6 +124,10 @@ to the ``LDAP_SCOPE_BASE`` scope of :phpfunction:`ldap_read`) and ``SCOPE_ONE``
$query = $ldap->query('dc=symfony,dc=com', '...', ['scope' => QueryInterface::SCOPE_ONE]);
+Use the ``filter`` option to only retrieve some specific attributes:
+
+ $query = $ldap->query('dc=symfony,dc=com', '...', ['filter' => ['cn', 'mail']);
+
Creating or Updating Entries
----------------------------
@@ -135,6 +152,13 @@ delete existing ones::
$query = $ldap->query('dc=symfony,dc=com', '(&(objectclass=person)(ou=Maintainers))');
$result = $query->execute();
$entry = $result[0];
+
+ $phoneNumber = $entry->getAttribute('phoneNumber');
+ $isContractor = $entry->hasAttribute('contractorCompany');
+ // attribute names in getAttribute() and hasAttribute() methods are case-sensitive
+ // pass FALSE as the second method argument to make them case-insensitive
+ $isContractor = $entry->hasAttribute('contractorCompany', false);
+
$entry->setAttribute('email', ['fabpot@symfony.com']);
$entryManager->update($entry);
@@ -172,3 +196,5 @@ Possible operation types are ``LDAP_MODIFY_BATCH_ADD``, ``LDAP_MODIFY_BATCH_REMO
``LDAP_MODIFY_BATCH_REMOVE_ALL``, ``LDAP_MODIFY_BATCH_REPLACE``. Parameter
``$values`` must be ``NULL`` when using ``LDAP_MODIFY_BATCH_REMOVE_ALL``
operation type.
+
+.. _`SASL`: https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer
diff --git a/components/lock.rst b/components/lock.rst
index 6660318bf12..2403763bd4a 100644
--- a/components/lock.rst
+++ b/components/lock.rst
@@ -1,13 +1,12 @@
-.. index::
- single: Lock
- single: Components; Lock
-
The Lock Component
==================
The Lock Component creates and manages `locks`_, a mechanism to provide
exclusive access to a shared resource.
+If you're using the Symfony Framework, read the
+:doc:`Symfony Framework Lock documentation `.
+
Installation
------------
@@ -39,11 +38,11 @@ resource. Then, a call to the :method:`Symfony\\Component\\Lock\\LockInterface::
method will try to acquire the lock::
// ...
- $lock = $factory->createLock('pdf-invoice-generation');
+ $lock = $factory->createLock('pdf-creation');
if ($lock->acquire()) {
- // The resource "pdf-invoice-generation" is locked.
- // You can compute and generate invoice safely here.
+ // The resource "pdf-creation" is locked.
+ // You can compute and generate the invoice safely here.
$lock->release();
}
@@ -53,50 +52,116 @@ method can be safely called repeatedly, even if the lock is already acquired.
.. note::
- Unlike other implementations, the Lock Component distinguishes locks
- instances even when they are created for the same resource. If a lock has
- to be used by several services, they should share the same ``Lock`` instance
- returned by the ``LockFactory::createLock`` method.
+ Unlike other implementations, the Lock Component distinguishes lock
+ instances even when they are created for the same resource. It means that for
+ a given scope and resource one lock instance can be acquired multiple times.
+ If a lock has to be used by several services, they should share the same ``Lock``
+ instance returned by the ``LockFactory::createLock`` method.
.. tip::
If you don't release the lock explicitly, it will be released automatically
- on instance destruction. In some cases, it can be useful to lock a resource
+ upon instance destruction. In some cases, it can be useful to lock a resource
across several requests. To disable the automatic release behavior, set the
third argument of the ``createLock()`` method to ``false``.
+Serializing Locks
+-----------------
+
+The :class:`Symfony\\Component\\Lock\\Key` contains the state of the
+:class:`Symfony\\Component\\Lock\\Lock` and can be serialized. This
+allows the user to begin a long job in a process by acquiring the lock, and
+continue the job in another process using the same lock.
+
+First, you may create a serializable class containing the resource and the
+key of the lock::
+
+ // src/Lock/RefreshTaxonomy.php
+ namespace App\Lock;
+
+ use Symfony\Component\Lock\Key;
+
+ class RefreshTaxonomy
+ {
+ public function __construct(
+ private object $article,
+ private Key $key,
+ ) {
+ }
+
+ public function getArticle(): object
+ {
+ return $this->article;
+ }
+
+ public function getKey(): Key
+ {
+ return $this->key;
+ }
+ }
+
+Then, you can use this class to dispatch all that's needed for another process
+to handle the rest of the job::
+
+ use App\Lock\RefreshTaxonomy;
+ use Symfony\Component\Lock\Key;
+
+ $key = new Key('article.'.$article->getId());
+ $lock = $factory->createLockFromKey(
+ $key,
+ 300, // ttl
+ false // autoRelease
+ );
+ $lock->acquire(true);
+
+ $this->bus->dispatch(new RefreshTaxonomy($article, $key));
+
+.. note::
+
+ Don't forget to set the ``autoRelease`` argument to ``false`` in the
+ ``Lock`` instantiation to avoid releasing the lock when the destructor is
+ called.
+
+Not all stores are compatible with serialization and cross-process locking: for
+example, the kernel will automatically release semaphores acquired by the
+:ref:`SemaphoreStore ` store. If you use an incompatible
+store (see :ref:`lock stores ` for supported stores), an
+exception will be thrown when the application tries to serialize the key.
+
.. _lock-blocking-locks:
Blocking Locks
--------------
By default, when a lock cannot be acquired, the ``acquire`` method returns
-``false`` immediately. To wait (indefinitely) until the lock
-can be created, pass ``true`` as the argument of the ``acquire()`` method. This
-is called a **blocking lock** because the execution of your application stops
-until the lock is acquired.
-
-Some of the built-in ``Store`` classes support this feature. When they don't,
-they can be decorated with the ``RetryTillSaveStore`` class::
+``false`` immediately. To wait (indefinitely) until the lock can be created,
+pass ``true`` as the argument of the ``acquire()`` method. This is called a
+**blocking lock** because the execution of your application stops until the
+lock is acquired::
use Symfony\Component\Lock\LockFactory;
- use Symfony\Component\Lock\Store\RedisStore;
- use Symfony\Component\Lock\Store\RetryTillSaveStore;
+ use Symfony\Component\Lock\Store\FlockStore;
- $store = new RedisStore(new \Predis\Client('tcp://localhost:6379'));
- $store = new RetryTillSaveStore($store);
+ $store = new FlockStore('/var/stores');
$factory = new LockFactory($store);
- $lock = $factory->createLock('notification-flush');
+ $lock = $factory->createLock('pdf-creation');
$lock->acquire(true);
+When the store does not support blocking locks by implementing the
+:class:`Symfony\\Component\\Lock\\BlockingStoreInterface` interface (see
+:ref:`lock stores ` for supported stores), the ``Lock`` class
+will retry to acquire the lock in a non-blocking way until the lock is
+acquired.
+
Expiring Locks
--------------
Locks created remotely are difficult to manage because there is no way for the
remote ``Store`` to know if the locker process is still alive. Due to bugs,
-fatal errors or segmentation faults, it cannot be guaranteed that ``release()``
-method will be called, which would cause the resource to be locked infinitely.
+fatal errors or segmentation faults, it cannot be guaranteed that the
+``release()`` method will be called, which would cause the resource to be
+locked infinitely.
The best solution in those cases is to create **expiring locks**, which are
released automatically after some amount of time has passed (called TTL for
@@ -110,10 +175,12 @@ job; if it's too long and the process crashes before calling the ``release()``
method, the resource will stay locked until the timeout::
// ...
- // create an expiring lock that lasts 30 seconds
- $lock = $factory->createLock('charts-generation', 30);
+ // create an expiring lock that lasts 30 seconds (default is 300.0)
+ $lock = $factory->createLock('pdf-creation', ttl: 30);
- $lock->acquire();
+ if (!$lock->acquire()) {
+ return;
+ }
try {
// perform a job during less than 30 seconds
} finally {
@@ -122,7 +189,7 @@ method, the resource will stay locked until the timeout::
.. tip::
- To avoid letting the lock in a locking state, it's recommended to wrap the
+ To avoid leaving the lock in a locked state, it's recommended to wrap the
job in a try/catch/finally block to always try to release the expiring lock.
In case of long-running tasks, it's better to start with a not too long TTL and
@@ -130,9 +197,11 @@ then use the :method:`Symfony\\Component\\Lock\\LockInterface::refresh` method
to reset the TTL to its original value::
// ...
- $lock = $factory->createLock('charts-generation', 30);
+ $lock = $factory->createLock('pdf-creation', ttl: 30);
- $lock->acquire();
+ if (!$lock->acquire()) {
+ return;
+ }
try {
while (!$finished) {
// perform a small part of the job.
@@ -149,7 +218,7 @@ to reset the TTL to its original value::
Another useful technique for long-running tasks is to pass a custom TTL as
an argument of the ``refresh()`` method to change the default lock TTL::
- $lock = $factory->createLock('charts-generation', 30);
+ $lock = $factory->createLock('pdf-creation', ttl: 30);
// ...
// refresh the lock for 30 seconds
$lock->refresh();
@@ -158,13 +227,109 @@ to reset the TTL to its original value::
$lock->refresh(600);
This component also provides two useful methods related to expiring locks:
-``getExpiringDate()`` (which returns ``null`` or a ``\DateTimeImmutable``
-object) and ``isExpired()`` (which returns a boolean).
+``getRemainingLifetime()`` (which returns ``null`` or a ``float``
+as seconds) and ``isExpired()`` (which returns a boolean).
+
+Automatically Releasing The Lock
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Locks are automatically released when their Lock objects are destroyed. This is
+an implementation detail that is important when sharing Locks between
+processes. In the example below, ``pcntl_fork()`` creates two processes and the
+Lock will be released automatically as soon as one process finishes::
+
+ // ...
+ $lock = $factory->createLock('pdf-creation');
+ if (!$lock->acquire()) {
+ return;
+ }
+
+ $pid = pcntl_fork();
+ if (-1 === $pid) {
+ // Could not fork
+ exit(1);
+ } elseif ($pid) {
+ // Parent process
+ sleep(30);
+ } else {
+ // Child process
+ echo 'The lock will be released now.';
+ exit(0);
+ }
+ // ...
+
+.. note::
+
+ In order for the above example to work, the `PCNTL`_ extension must be
+ installed.
+
+To disable this behavior, set the ``autoRelease`` argument of
+``LockFactory::createLock()`` to ``false``. That will make the lock acquired
+for 3600 seconds or until ``Lock::release()`` is called::
+
+ $lock = $factory->createLock(
+ 'pdf-creation',
+ 3600, // ttl
+ false // autoRelease
+ );
+
+Shared Locks
+------------
+
+A shared or `readers-writer lock`_ is a synchronization primitive that allows
+concurrent access for read-only operations, while write operations require
+exclusive access. This means that multiple threads can read the data in parallel
+but an exclusive lock is needed for writing or modifying data. They are used for
+example for data structures that cannot be updated atomically and are invalid
+until the update is complete.
+
+Use the :method:`Symfony\\Component\\Lock\\SharedLockInterface::acquireRead`
+method to acquire a read-only lock, and
+:method:`Symfony\\Component\\Lock\\LockInterface::acquire` method to acquire a
+write lock::
+
+ $lock = $factory->createLock('user-'.$user->id);
+ if (!$lock->acquireRead()) {
+ return;
+ }
+
+Similar to the ``acquire()`` method, pass ``true`` as the argument of ``acquireRead()``
+to acquire the lock in a blocking mode::
+
+ $lock = $factory->createLock('user-'.$user->id);
+ $lock->acquireRead(true);
+
+.. note::
+
+ The `priority policy`_ of Symfony's shared locks depends on the underlying
+ store (e.g. Redis store prioritizes readers vs writers).
+
+When a read-only lock is acquired with the ``acquireRead()`` method, it's
+possible to **promote** the lock, and change it to a write lock, by calling the
+``acquire()`` method::
+
+ $lock = $factory->createLock('user-'.$userId);
+ $lock->acquireRead(true);
+
+ if (!$this->shouldUpdate($userId)) {
+ return;
+ }
+
+ $lock->acquire(true); // Promote the lock to a write lock
+ $this->update($userId);
+
+In the same way, it's possible to **demote** a write lock, and change it to a
+read-only lock by calling the ``acquireRead()`` method.
+
+When the provided store does not implement the
+:class:`Symfony\\Component\\Lock\\SharedLockStoreInterface` interface (see
+:ref:`lock stores ` for supported stores), the ``Lock`` class
+will fallback to a write lock by calling the ``acquire()`` method.
The Owner of The Lock
---------------------
-Locks that are acquired for the first time are owned by the ``Lock`` instance that acquired
+Locks that are acquired for the first time are :ref:`owned ` by the ``Lock`` instance that acquired
it. If you need to check whether the current ``Lock`` instance is (still) the owner of
a lock, you can use the ``isAcquired()`` method::
@@ -172,8 +337,8 @@ a lock, you can use the ``isAcquired()`` method::
// We (still) own the lock
}
-Because of the fact that some lock stores have expiring locks (as seen and explained
-above), it is possible for an instance to lose the lock it acquired automatically::
+Because some lock stores have expiring locks, it is possible for an instance to
+lose the lock it acquired automatically::
// If we cannot acquire ourselves, it means some other process is already working on it
if (!$lock->acquire()) {
@@ -194,37 +359,57 @@ above), it is possible for an instance to lose the lock it acquired automaticall
throw new \Exception('Process failed');
}
-.. caution::
+.. warning::
A common pitfall might be to use the ``isAcquired()`` method to check if
a lock has already been acquired by any process. As you can see in this example
you have to use ``acquire()`` for this. The ``isAcquired()`` method is used to check
- if the lock has been acquired by the **current process** only!
+ if the lock has been acquired by the **current process** only.
+
+.. _lock-owner-technical-details:
+
+.. note::
-.. [1] Technically, the true owners of the lock are the ones that share the same instance of ``Key``,
+ Technically, the true owners of the lock are the ones that share the same instance of ``Key``,
not ``Lock``. But from a user perspective, ``Key`` is internal and you will likely only be working
with the ``Lock`` instance so it's easier to think of the ``Lock`` instance as being the one that
is the owner of the lock.
+.. _lock-stores:
+
Available Stores
----------------
Locks are created and managed in ``Stores``, which are classes that implement
-:class:`Symfony\\Component\\Lock\\PersistStoreInterface` and, optionally,
+:class:`Symfony\\Component\\Lock\\PersistingStoreInterface` and, optionally,
:class:`Symfony\\Component\\Lock\\BlockingStoreInterface`.
The component includes the following built-in store types:
-============================================ ====== ======== ========
-Store Scope Blocking Expiring
-============================================ ====== ======== ========
-:ref:`FlockStore ` local yes no
-:ref:`MemcachedStore ` remote no yes
-:ref:`PdoStore ` remote no yes
-:ref:`RedisStore ` remote no yes
-:ref:`SemaphoreStore ` local yes no
-:ref:`ZookeeperStore ` remote no no
-============================================ ====== ======== ========
+========================================================== ====== ======== ======== ======= =============
+Store Scope Blocking Expiring Sharing Serialization
+========================================================== ====== ======== ======== ======= =============
+:ref:`FlockStore ` local yes no yes no
+:ref:`MemcachedStore ` remote no yes no yes
+:ref:`MongoDbStore ` remote no yes no yes
+:ref:`PdoStore ` remote no yes no yes
+:ref:`DoctrineDbalStore ` remote no yes no yes
+:ref:`PostgreSqlStore ` remote yes no yes no
+:ref:`DoctrineDbalPostgreSqlStore ` remote yes no yes no
+:ref:`RedisStore ` remote no yes yes yes
+:ref:`SemaphoreStore ` local yes no no no
+:ref:`ZookeeperStore ` remote no no no no
+========================================================== ====== ======== ======== ======= =============
+
+.. tip::
+
+ Symfony includes two other special stores that are mostly useful for testing:
+ ``InMemoryStore``, which saves locks in memory during a process, and ``NullStore``,
+ which doesn't persist anything.
+
+.. versionadded:: 7.2
+
+ The :class:`Symfony\\Component\\Lock\\Store\\NullStore` was introduced in Symfony 7.2.
.. _lock-store-flock:
@@ -233,18 +418,20 @@ FlockStore
The FlockStore uses the file system on the local computer to create the locks.
It does not support expiration, but the lock is automatically released when the
-PHP process is terminated::
+lock object goes out of scope and is freed by the garbage collector (for example
+when the PHP process ends)::
use Symfony\Component\Lock\Store\FlockStore;
// the argument is the path of the directory where the locks are created
- $store = new FlockStore(sys_get_temp_dir());
+ // if none is given, sys_get_temp_dir() is used internally.
+ $store = new FlockStore('/var/stores');
-.. caution::
+.. warning::
Beware that some file systems (such as some types of NFS) do not support
locking. In those cases, it's better to use a directory on a local disk
- drive or a remote store based on PDO, Redis or Memcached.
+ drive or a remote store.
.. _lock-store-memcached:
@@ -266,44 +453,158 @@ support blocking, and expects a TTL to avoid stalled locks::
Memcached does not support TTL lower than 1 second.
+.. _lock-store-mongodb:
+
+MongoDbStore
+~~~~~~~~~~~~
+
+The MongoDbStore saves locks on a MongoDB server ``>=2.2``, it requires a
+``\MongoDB\Collection`` or ``\MongoDB\Client`` from `mongodb/mongodb`_ or a
+`MongoDB Connection String`_.
+This store does not support blocking and expects a TTL to
+avoid stalled locks::
+
+ use Symfony\Component\Lock\Store\MongoDbStore;
+
+ $mongo = 'mongodb://localhost/database?collection=lock';
+ $options = [
+ 'gcProbability' => 0.001,
+ 'database' => 'myapp',
+ 'collection' => 'lock',
+ 'uriOptions' => [],
+ 'driverOptions' => [],
+ ];
+ $store = new MongoDbStore($mongo, $options);
+
+The ``MongoDbStore`` takes the following ``$options`` (depending on the first parameter type):
+
+============= ================================================================================================
+Option Description
+============= ================================================================================================
+gcProbability Should a TTL Index be created expressed as a probability from 0.0 to 1.0 (Defaults to ``0.001``)
+database The name of the database
+collection The name of the collection
+uriOptions Array of URI options for `MongoDBClient::__construct`_
+driverOptions Array of driver options for `MongoDBClient::__construct`_
+============= ================================================================================================
+
+When the first parameter is a:
+
+``MongoDB\Collection``:
+
+- ``$options['database']`` is ignored
+- ``$options['collection']`` is ignored
+
+``MongoDB\Client``:
+
+- ``$options['database']`` is mandatory
+- ``$options['collection']`` is mandatory
+
+MongoDB Connection String:
+
+- ``$options['database']`` is used otherwise ``/path`` from the DSN, at least one is mandatory
+- ``$options['collection']`` is used otherwise ``?collection=`` from the DSN, at least one is mandatory
+
+.. note::
+
+ The ``collection`` querystring parameter is not part of the `MongoDB Connection String`_ definition.
+ It is used to allow constructing a ``MongoDbStore`` using a `Data Source Name (DSN)`_ without ``$options``.
+
.. _lock-store-pdo:
PdoStore
~~~~~~~~
-The PdoStore saves locks in an SQL database. It requires a `PDO`_ connection, a
-`Doctrine DBAL Connection`_, or a `Data Source Name (DSN)`_. This store does not
-support blocking, and expects a TTL to avoid stalled locks::
+The PdoStore saves locks in an SQL database. It requires a `PDO`_ connection or a `Data Source Name (DSN)`_.
+This store does not support blocking, and expects a TTL to avoid stalled locks::
use Symfony\Component\Lock\Store\PdoStore;
- // a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO
- $databaseConnectionOrDSN = 'mysql:host=127.0.0.1;dbname=lock';
+ // a PDO instance or DSN for lazy connecting through PDO
+ $databaseConnectionOrDSN = 'mysql:host=127.0.0.1;dbname=app';
$store = new PdoStore($databaseConnectionOrDSN, ['db_username' => 'myuser', 'db_password' => 'mypassword']);
.. note::
This store does not support TTL lower than 1 second.
-Before storing locks in the database, you must create the table that stores
-the information. The store provides a method called
-:method:`Symfony\\Component\\Lock\\Store\\PdoStore::createTable`
-to set up this table for you according to the database engine used::
+The table where values are stored is created automatically on the first call to
+the :method:`Symfony\\Component\\Lock\\Store\\PdoStore::save` method.
+You can also create this table explicitly by calling the
+:method:`Symfony\\Component\\Lock\\Store\\PdoStore::createTable` method in
+your code.
- try {
- $store->createTable();
- } catch (\PDOException $exception) {
- // the table could not be created for some reason
- }
+.. _lock-store-dbal:
+
+DoctrineDbalStore
+~~~~~~~~~~~~~~~~~
-A great way to set up the table in production is to call the ``createTable()``
-method in your local computer and then generate a
-:ref:`database migration `:
+The DoctrineDbalStore saves locks in an SQL database. It is identical to PdoStore
+but requires a `Doctrine DBAL Connection`_, or a `Doctrine DBAL URL`_. This store
+does not support blocking, and expects a TTL to avoid stalled locks::
+
+ use Symfony\Component\Lock\Store\DoctrineDbalStore;
+
+ // a Doctrine DBAL connection or DSN
+ $connectionOrURL = 'mysql://myuser:mypassword@127.0.0.1/app';
+ $store = new DoctrineDbalStore($connectionOrURL);
+
+.. note::
+
+ This store does not support TTL lower than 1 second.
+
+The table where values are stored will be automatically generated when your run
+the command:
.. code-block:: terminal
- $ php bin/console doctrine:migrations:diff
- $ php bin/console doctrine:migrations:migrate
+ $ php bin/console make:migration
+
+If you prefer to create the table yourself and it has not already been created, you can
+create this table explicitly by calling the
+:method:`Symfony\\Component\\Lock\\Store\\DoctrineDbalStore::createTable` method.
+You can also add this table to your schema by calling
+:method:`Symfony\\Component\\Lock\\Store\\DoctrineDbalStore::configureSchema` method
+in your code
+
+If the table has not been created upstream, it will be created automatically on the first call to
+the :method:`Symfony\\Component\\Lock\\Store\\DoctrineDbalStore::save` method.
+
+.. _lock-store-pgsql:
+
+PostgreSqlStore
+~~~~~~~~~~~~~~~
+
+The PostgreSqlStore uses `Advisory Locks`_ provided by PostgreSQL. It requires a
+`PDO`_ connection or a `Data Source Name (DSN)`_. It supports native blocking, as well as sharing
+locks::
+
+ use Symfony\Component\Lock\Store\PostgreSqlStore;
+
+ // a PDO instance or DSN for lazy connecting through PDO
+ $databaseConnectionOrDSN = 'pgsql:host=localhost;port=5634;dbname=app';
+ $store = new PostgreSqlStore($databaseConnectionOrDSN, ['db_username' => 'myuser', 'db_password' => 'mypassword']);
+
+In opposite to the ``PdoStore``, the ``PostgreSqlStore`` does not need a table to
+store locks and it does not expire.
+
+.. _lock-store-dbal-pgsql:
+
+DoctrineDbalPostgreSqlStore
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The DoctrineDbalPostgreSqlStore uses `Advisory Locks`_ provided by PostgreSQL.
+It is identical to PostgreSqlStore but requires a `Doctrine DBAL Connection`_ or
+a `Doctrine DBAL URL`_. It supports native blocking, as well as sharing locks::
+
+ use Symfony\Component\Lock\Store\DoctrineDbalPostgreSqlStore;
+
+ // a Doctrine Connection or DSN
+ $databaseConnectionOrDSN = 'postgresql+advisory://myuser:mypassword@127.0.0.1:5634/lock';
+ $store = new DoctrineDbalPostgreSqlStore($databaseConnectionOrDSN);
+
+In opposite to the ``DoctrineDbalStore``, the ``DoctrineDbalPostgreSqlStore`` does not need a table to
+store locks and does not expire.
.. _lock-store-redis:
@@ -311,9 +612,9 @@ RedisStore
~~~~~~~~~~
The RedisStore saves locks on a Redis server, it requires a Redis connection
-implementing the ``\Redis``, ``\RedisArray``, ``\RedisCluster`` or
-``\Predis`` classes. This store does not support blocking, and expects a TTL to
-avoid stalled locks::
+implementing the ``\Redis``, ``\RedisArray``, ``\RedisCluster``, ``\Relay\Relay``,
+``\Relay\Cluster`` or ``\Predis`` classes. This store does not support blocking,
+and expects a TTL to avoid stalled locks::
use Symfony\Component\Lock\Store\RedisStore;
@@ -322,6 +623,10 @@ avoid stalled locks::
$store = new RedisStore($redis);
+.. versionadded:: 7.3
+
+ Support for ``Relay\Cluster`` was introduced in Symfony 7.3.
+
.. _lock-store-semaphore:
SemaphoreStore
@@ -339,10 +644,10 @@ CombinedStore
~~~~~~~~~~~~~
The CombinedStore is designed for High Availability applications because it
-manages several stores in sync (for example, several Redis servers). When a lock
-is being acquired, it forwards the call to all the managed stores, and it
-collects their responses. If a simple majority of stores have acquired the lock,
-then the lock is considered as acquired; otherwise as not acquired::
+manages several stores in sync (for example, several Redis servers). When a
+lock is acquired, it forwards the call to all the managed stores, and it
+collects their responses. If a simple majority of stores have acquired the
+lock, then the lock is considered acquired::
use Symfony\Component\Lock\Store\CombinedStore;
use Symfony\Component\Lock\Store\RedisStore;
@@ -360,14 +665,19 @@ then the lock is considered as acquired; otherwise as not acquired::
Instead of the simple majority strategy (``ConsensusStrategy``) an
``UnanimousStrategy`` can be used to require the lock to be acquired in all
-the stores.
+the stores::
-.. caution::
+ use Symfony\Component\Lock\Store\CombinedStore;
+ use Symfony\Component\Lock\Strategy\UnanimousStrategy;
+
+ $store = new CombinedStore($stores, new UnanimousStrategy());
+
+.. warning::
In order to get high availability when using the ``ConsensusStrategy``, the
minimum cluster size must be three servers. This allows the cluster to keep
working when a single server fails (because this strategy requires that the
- lock is acquired in more than half of the servers).
+ lock is acquired for more than half of the servers).
.. _lock-store-zookeeper:
@@ -395,29 +705,26 @@ PHP process is terminated::
Reliability
-----------
-The component guarantees that the same resource can't be lock twice as long as
+The component guarantees that the same resource can't be locked twice as long as
the component is used in the following way.
Remote Stores
~~~~~~~~~~~~~
Remote stores (:ref:`MemcachedStore `,
+:ref:`MongoDbStore `,
:ref:`PdoStore `,
+:ref:`PostgreSqlStore `,
:ref:`RedisStore ` and
:ref:`ZookeeperStore `) use a unique token to recognize
the true owner of the lock. This token is stored in the
:class:`Symfony\\Component\\Lock\\Key` object and is used internally by
-the ``Lock``, therefore this key must not be shared between processes (session,
-caching, fork, ...).
-
-.. caution::
-
- Do not share a key between processes.
+the ``Lock``.
-Every concurrent process must store the ``Lock`` in the same server. Otherwise two
+Every concurrent process must store the ``Lock`` on the same server. Otherwise two
different machines may allow two different processes to acquire the same ``Lock``.
-.. caution::
+.. warning::
To guarantee that the same server will always be safe, do not use Memcached
behind a LoadBalancer, a cluster or round-robin DNS. Even if the main server
@@ -427,6 +734,7 @@ Expiring Stores
~~~~~~~~~~~~~~~
Expiring stores (:ref:`MemcachedStore `,
+:ref:`MongoDbStore `,
:ref:`PdoStore ` and
:ref:`RedisStore `)
guarantee that the lock is acquired only for the defined duration of time. If
@@ -437,12 +745,14 @@ The ``Lock`` provides several methods to check its health. The ``isExpired()``
method checks whether or not its lifetime is over and the ``getRemainingLifetime()``
method returns its time to live in seconds.
-Using the above methods, a more robust code would be::
+Using the above methods, a robust code would be::
// ...
- $lock = $factory->createLock('invoice-publication', 30);
+ $lock = $factory->createLock('pdf-creation', 30);
- $lock->acquire();
+ if (!$lock->acquire()) {
+ return;
+ }
while (!$finished) {
if ($lock->getRemainingLifetime() <= 5) {
if ($lock->isExpired()) {
@@ -453,24 +763,24 @@ Using the above methods, a more robust code would be::
$lock->refresh();
}
- // Perform the task whose duration MUST be less than 5 minutes
+ // Perform the task whose duration MUST be less than 5 seconds
}
-.. caution::
+.. warning::
Choose wisely the lifetime of the ``Lock`` and check whether its remaining
- time to leave is enough to perform the task.
+ time to live is enough to perform the task.
-.. caution::
+.. warning::
Storing a ``Lock`` usually takes a few milliseconds, but network conditions
may increase that time a lot (up to a few seconds). Take that into account
when choosing the right TTL.
-By design, locks are stored in servers with a defined lifetime. If the date or
+By design, locks are stored on servers with a defined lifetime. If the date or
time of the machine changes, a lock could be released sooner than expected.
-.. caution::
+.. warning::
To guarantee that date won't change, the NTP service should be disabled
and the date should be updated when the service is stopped.
@@ -479,11 +789,11 @@ FlockStore
~~~~~~~~~~
By using the file system, this ``Store`` is reliable as long as concurrent
-processes use the same physical directory to stores locks.
+processes use the same physical directory to store locks.
Processes must run on the same machine, virtual machine or container.
-Be careful when updating a Kubernetes or Swarm service because for a short
-period of time, there can be two running containers in parallel.
+Be careful when updating a Kubernetes or Swarm service because, for a short
+period of time, there can be two containers running in parallel.
The absolute path to the directory must remain the same. Be careful of symlinks
that could change at anytime: Capistrano and blue/green deployment often use
@@ -492,22 +802,21 @@ deployments.
Some file systems (such as some types of NFS) do not support locking.
-.. caution::
+.. warning::
All concurrent processes must use the same physical file system by running
- on the same machine and using the same absolute path to locks directory.
+ on the same machine and using the same absolute path to the lock directory.
- By definition, usage of ``FlockStore`` in an HTTP context is incompatible
- with multiple front servers, unless to ensure that the same resource will
- always be locked on the same machine or to use a well configured shared file
- system.
+ Using a ``FlockStore`` in an HTTP context is incompatible with multiple
+ front servers, unless to ensure that the same resource will always be
+ locked on the same machine or to use a well configured shared file system.
-Files on the file system can be removed during a maintenance operation. For instance,
-to clean up the ``/tmp`` directory or after a reboot of the machine when a directory
-uses tmpfs. It's not an issue if the lock is released when the process ended, but
-it is in case of ``Lock`` reused between requests.
+Files on the file system can be removed during a maintenance operation. For
+instance, to clean up the ``/tmp`` directory or after a reboot of the machine
+when a directory uses ``tmpfs``. It's not an issue if the lock is released when
+the process ended, but it is in case of ``Lock`` reused between requests.
-.. caution::
+.. danger::
Do not store locks on a volatile file system if they have to be reused in
several requests.
@@ -517,12 +826,12 @@ MemcachedStore
The way Memcached works is to store items in memory. That means that by using
the :ref:`MemcachedStore ` the locks are not persisted
-and may disappear by mistake at anytime.
+and may disappear by mistake at any time.
If the Memcached service or the machine hosting it restarts, every lock would
be lost without notifying the running processes.
-.. caution::
+.. warning::
To avoid that someone else acquires a lock after a restart, it's recommended
to delay service start and wait at least as long as the longest lock TTL.
@@ -530,7 +839,7 @@ be lost without notifying the running processes.
By default Memcached uses a LRU mechanism to remove old entries when the service
needs space to add new items.
-.. caution::
+.. warning::
The number of items stored in Memcached must be under control. If it's not
possible, LRU should be disabled and Lock should be stored in a dedicated
@@ -540,22 +849,63 @@ When the Memcached service is shared and used for multiple usage, Locks could be
removed by mistake. For instance some implementation of the PSR-6 ``clear()``
method uses the Memcached's ``flush()`` method which purges and removes everything.
-.. caution::
+.. danger::
The method ``flush()`` must not be called, or locks should be stored in a
dedicated Memcached service away from Cache.
+MongoDbStore
+~~~~~~~~~~~~
+
+.. warning::
+
+ The locked resource name is indexed in the ``_id`` field of the lock
+ collection. Beware that an indexed field's value in MongoDB can be
+ `a maximum of 1024 bytes in length`_ including the structural overhead.
+
+A TTL index must be used to automatically clean up expired locks.
+Such an index can be created manually:
+
+.. code-block:: javascript
+
+ db.lock.createIndex(
+ { "expires_at": 1 },
+ { "expireAfterSeconds": 0 }
+ )
+
+Alternatively, the method ``MongoDbStore::createTtlIndex(int $expireAfterSeconds = 0)``
+can be called once to create the TTL index during database setup. Read more
+about `Expire Data from Collections by Setting TTL`_ in MongoDB.
+
+.. tip::
+
+ ``MongoDbStore`` will attempt to automatically create a TTL index. It's
+ recommended to set constructor option ``gcProbability`` to ``0.0`` to
+ disable this behavior if you have manually dealt with TTL index creation.
+
+.. warning::
+
+ This store relies on all PHP application and database nodes to have
+ synchronized clocks for lock expiry to occur at the correct time. To ensure
+ locks don't expire prematurely; the lock TTL should be set with enough extra
+ time in ``expireAfterSeconds`` to account for any clock drift between nodes.
+
+``writeConcern`` and ``readConcern`` are not specified by MongoDbStore meaning
+the collection's settings will take effect.
+``readPreference`` is ``primary`` for all queries.
+Read more about `Replica Set Read and Write Semantics`_ in MongoDB.
+
PdoStore
-~~~~~~~~~~
+~~~~~~~~
The PdoStore relies on the `ACID`_ properties of the SQL engine.
-.. caution::
+.. warning::
In a cluster configured with multiple primaries, ensure writes are
- synchronously propagated to every nodes, or always use the same node.
+ synchronously propagated to every node, or always use the same node.
-.. caution::
+.. warning::
Some SQL engines like MySQL allow to disable the unique constraint check.
Ensure that this is not the case ``SET unique_checks=1;``.
@@ -564,22 +914,36 @@ In order to purge old locks, this store uses a current datetime to define an
expiration date reference. This mechanism relies on all server nodes to
have synchronized clocks.
-.. caution::
+.. warning::
To ensure locks don't expire prematurely; the TTLs should be set with
enough extra time to account for any clock drift between nodes.
+PostgreSqlStore
+~~~~~~~~~~~~~~~
+
+The PostgreSqlStore relies on the `Advisory Locks`_ properties of the PostgreSQL
+database. That means that by using :ref:`PostgreSqlStore `
+the locks will be automatically released at the end of the session in case the
+client cannot unlock for any reason.
+
+If the PostgreSQL service or the machine hosting it restarts, every lock would
+be lost without notifying the running processes.
+
+If the TCP connection is lost, the PostgreSQL may release locks without
+notifying the application.
+
RedisStore
~~~~~~~~~~
The way Redis works is to store items in memory. That means that by using
the :ref:`RedisStore ` the locks are not persisted
-and may disappear by mistake at anytime.
+and may disappear by mistake at any time.
If the Redis service or the machine hosting it restarts, every locks would
be lost without notifying the running processes.
-.. caution::
+.. warning::
To avoid that someone else acquires a lock after a restart, it's recommended
to delay service start and wait at least as long as the longest lock TTL.
@@ -593,7 +957,7 @@ be lost without notifying the running processes.
When the Redis service is shared and used for multiple usages, locks could be
removed by mistake.
-.. caution::
+.. danger::
The command ``FLUSHDB`` must not be called, or locks should be stored in a
dedicated Redis service away from Cache.
@@ -601,13 +965,13 @@ removed by mistake.
CombinedStore
~~~~~~~~~~~~~
-Combined stores allow to store locks across several backends. It's a common
-mistake to think that the lock mechanism will be more reliable. This is wrong
+Combined stores allow the storage of locks across several backends. It's a common
+mistake to think that the lock mechanism will be more reliable. This is wrong.
The ``CombinedStore`` will be, at best, as reliable as the least reliable of
all managed stores. As soon as one managed store returns erroneous information,
the ``CombinedStore`` won't be reliable.
-.. caution::
+.. warning::
All concurrent processes must use the same configuration, with the same
amount of managed stored and the same endpoint.
@@ -625,12 +989,20 @@ must run on the same machine, virtual machine or container. Be careful when
updating a Kubernetes or Swarm service because for a short period of time, there
can be two running containers in parallel.
-.. caution::
+.. warning::
All concurrent processes must use the same machine. Before starting a
- concurrent process on a new machine, check that other process are stopped
+ concurrent process on a new machine, check that other processes are stopped
on the old one.
+.. warning::
+
+ When running on systemd with non-system user and option ``RemoveIPC=yes``
+ (default value), locks are deleted by systemd when that user logs out.
+ Check that process is run with a system user (UID <= SYS_UID_MAX) with
+ ``SYS_UID_MAX`` defined in ``/etc/login.defs``, or set the option
+ ``RemoveIPC=off`` in ``/etc/systemd/logind.conf``.
+
ZookeeperStore
~~~~~~~~~~~~~~
@@ -663,10 +1035,21 @@ instance, during the deployment of a new version. Processes with new
configuration must not be started while old processes with old configuration
are still running.
+.. _`a maximum of 1024 bytes in length`: https://docs.mongodb.com/manual/reference/limits/#Index-Key-Limit
.. _`ACID`: https://en.wikipedia.org/wiki/ACID
-.. _`locks`: https://en.wikipedia.org/wiki/Lock_(computer_science)
-.. _`PHP semaphore functions`: https://php.net/manual/en/book.sem.php
-.. _`PDO`: https://php.net/pdo
-.. _`Doctrine DBAL Connection`: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Connection.php
+.. _`Advisory Locks`: https://www.postgresql.org/docs/current/explicit-locking.html
.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name
+.. _`Doctrine DBAL Connection`: https://github.com/doctrine/dbal/blob/master/src/Connection.php
+.. _`Doctrine DBAL URL`: https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
+.. _`Expire Data from Collections by Setting TTL`: https://docs.mongodb.com/manual/tutorial/expire-data/
+.. _`locks`: https://en.wikipedia.org/wiki/Lock_(computer_science)
+.. _`MongoDB Connection String`: https://docs.mongodb.com/manual/reference/connection-string/
+.. _`mongodb/mongodb`: https://packagist.org/packages/mongodb/mongodb
+.. _`MongoDBClient::__construct`: https://docs.mongodb.com/php-library/current/reference/method/MongoDBClient__construct/
+.. _`PDO`: https://www.php.net/pdo
+.. _`PHP semaphore functions`: https://www.php.net/manual/en/book.sem.php
+.. _`Replica Set Read and Write Semantics`: https://docs.mongodb.com/manual/applications/replication/
.. _`ZooKeeper`: https://zookeeper.apache.org/
+.. _`readers-writer lock`: https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock
+.. _`priority policy`: https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock#Priority_policies
+.. _`PCNTL`: https://www.php.net/manual/book.pcntl.php
diff --git a/components/mailer.rst b/components/mailer.rst
deleted file mode 100644
index cb180bb858b..00000000000
--- a/components/mailer.rst
+++ /dev/null
@@ -1,196 +0,0 @@
-.. index::
- single: Mailer
- single: Components; Mailer
-
-The Mailer Component
-====================
-
- The Mailer component helps sending emails.
-
-If you're using the Symfony Framework, read the
-:doc:`Symfony Framework Mailer documentation `.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/mailer
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-The Mailer component has two main classes: a ``Transport`` and the ``Mailer`` itself::
-
- use Symfony\Component\Mailer\Mailer;
- use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
-
- $transport = new EsmtpTransport('localhost');
- $mailer = new Mailer($transport);
- $mailer->send($email);
-
-The ``$email`` object is created via the :doc:`Mime component `.
-
-Transport
----------
-
-The only transport that comes pre-installed is SMTP.
-
-Below is the list of other popular providers with built-in support:
-
-================== =============================================
-Service Install with
-================== =============================================
-Amazon SES ``composer require symfony/amazon-mailer``
-Gmail ``composer require symfony/google-mailer``
-MailChimp ``composer require symfony/mailchimp-mailer``
-Mailgun ``composer require symfony/mailgun-mailer``
-Postmark ``composer require symfony/postmark-mailer``
-SendGrid ``composer require symfony/sendgrid-mailer``
-================== =============================================
-
-For example, suppose you want to use Google's Gmail SMTP server. First, install
-it:
-
-.. code-block:: terminal
-
- $ composer require symfony/google-mailer
-
-Then, use the SMTP Gmail transport::
-
- use Symfony\Component\Mailer\Bridge\Google\Smtp\GmailTransport;
- use Symfony\Component\Mailer\Mailer;
-
- $transport = new GmailTransport('user', 'pass');
- $mailer = new Mailer($transport);
- $mailer->send($email);
-
-Each provider provides up to 3 transports: standard SMTP, HTTP (it uses the
-provider's API but the body is created by the mailer component), API (it uses
-the full API of the provider with no control over the body creation -- features
-might be limited as well).
-
-.. _mailer_dsn:
-
-The mailer component provides a convenient way to create a transport from a
-DSN::
-
- use Symfony\Component\Mailer\Transport;
-
- $transport = Transport::fromDsn($dsn);
-
-Where ``$dsn`` depends on the provider you want to use. For plain SMTP, use
-``smtp://user:pass@example.com`` or ``sendmail+smtp://default`` to use the
-``sendmail`` binary. To disable the transport, use ``null://null``.
-
-For third-party providers, refer to the following table:
-
-==================== ========================================== =========================================== ========================================
- Provider SMTP HTTP API
-==================== ========================================== =========================================== ========================================
- Amazon SES ses+smtp://ACCESS_KEY:SECRET_KEY@default ses+https://ACCESS_KEY:SECRET_KEY@default ses+api://ACCESS_KEY:SECRET_KEY@default
- Google Gmail gmail+smtp://USERNAME:PASSWORD@default n/a n/a
- Mailchimp Mandrill mandrill+smtp://USERNAME:PASSWORD@default mandrill+https://KEY@default mandrill+api://KEY@default
- Mailgun mailgun+smtp://USERNAME:PASSWORD@default mailgun+https://KEY:DOMAIN@default mailgun+api://KEY:DOMAIN@default
- Postmark postmark+smtp://ID:ID@default n/a postmark+api://KEY@default
- Sendgrid sendgrid+smtp://apikey:KEY@default n/a sendgrid+api://KEY@default
-==================== ========================================== =========================================== ========================================
-
-Instead of choosing a specific protocol, you can also let Symfony pick the
-best one by omitting it from the scheme: for instance, ``mailgun://KEY:DOMAIN@default``
-is equivalent to ``mailgun+https://KEY:DOMAIN@default``.
-
-If you want to override the default host for a provider (to debug an issue using
-a service like ``requestbin.com``), change ``default`` by your host:
-
-.. code-block:: bash
-
- mailgun+https://KEY:DOMAIN@example.com
- mailgun+https://KEY:DOMAIN@example.com:99
-
-Note that the protocol is *always* HTTPs and cannot be changed.
-
-High Availability
------------------
-
-Symfony's mailer supports `high availability`_ via a technique called "failover"
-to ensure that emails are sent even if one mailer server fails .
-
-A failover transport is configured with two or more transports and the
-``failover`` keyword::
-
- $dsn = 'failover(postmark+api://ID@default sendgrid+smtp://KEY@default)';
-
-The mailer will start using the first transport. If the sending fails, the
-mailer won't retry it with the other transports, but it will switch to the next
-transport automatically for the following deliveries.
-
-Load Balancing
---------------
-
-Symfony's mailer supports `load balancing`_ via a technique called "round-robin"
-to distribute the mailing workload across multiple transports .
-
-A round-robin transport is configured with two or more transports and the
-``roundrobin`` keyword::
-
- $dsn = 'roundrobin(postmark+api://ID@default sendgrid+smtp://KEY@default)'
-
-The mailer will start using the first transport and if it fails, it will retry
-the same delivery with the next transports until one of them succeeds (or until
-all of them fail).
-
-Sending emails asynchronously
------------------------------
-
-If you want to send emails asynchronously, install the :doc:`Messenger component
-`.
-
-.. code-block:: terminal
-
- $ composer require symfony/messenger
-
-Then, instantiate and pass a ``MessageBus`` as a second argument to ``Mailer``::
-
- use Symfony\Component\Mailer\Envelope;
- use Symfony\Component\Mailer\Mailer;
- use Symfony\Component\Mailer\Messenger\MessageHandler;
- use Symfony\Component\Mailer\Messenger\SendEmailMessage;
- use Symfony\Component\Mailer\Transport;
- use Symfony\Component\Messenger\Handler\HandlersLocator;
- use Symfony\Component\Messenger\MessageBus;
- use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
- use Symfony\Component\Mime\Address;
-
- $dsn = 'change-dsn-accordingly';
-
- $transport = Transport::fromDsn($dsn);
- $handler = new MessageHandler($transport);
-
- $bus = new MessageBus([
- new HandleMessageMiddleware(new HandlersLocator([
- SendEmailMessage::class => [$handler],
- ])),
- ]);
-
- $mailer = new Mailer($transport, $bus);
- $mailer->send($email);
-
- // you can pass an optional Envelope
- $mailer->send($email, new Envelope(
- new Address('sender@example.com'),
- [
- new Address('recipient@example.com'),
- ]
- ));
-
-Learn More
------------
-
-To learn more about how to use the mailer component, refer to the
-:doc:`Symfony Framework Mailer documentation `.
-
-.. _`high availability`: https://en.wikipedia.org/wiki/High_availability
-.. _`load balancing`: https://en.wikipedia.org/wiki/Load_balancing_(computing)
diff --git a/components/mercure.rst b/components/mercure.rst
deleted file mode 100644
index 9ad99419e8e..00000000000
--- a/components/mercure.rst
+++ /dev/null
@@ -1,46 +0,0 @@
-.. index::
- single: Mercure
- single: Components; Mercure
-
-The Mercure Component
-=====================
-
- `Mercure`_ is an open protocol allowing to push data updates to web
- browsers and other HTTP clients in a convenient, fast, reliable
- and battery-friendly way.
- It is especially useful to publish real-time updates of resources served
- through web APIs, to reactive web and mobile applications.
-
-The Mercure Component implements the "publisher" part of the Mercure Protocol.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/mercure
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-The following example shows the component in action::
-
- // change these values accordingly to your hub installation
- define('HUB_URL', 'https://demo.mercure.rocks/.well-known/mercure');
- define('JWT', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InN1YnNjcmliZSI6WyJmb28iLCJiYXIiXSwicHVibGlzaCI6WyJmb28iXX19.LRLvirgONK13JgacQ_VbcjySbVhkSmHy3IznH3tA9PM');
-
- use Symfony\Component\Mercure\Jwt\StaticJwtProvider;
- use Symfony\Component\Mercure\Publisher;
- use Symfony\Component\Mercure\Update;
-
- $publisher = new Publisher(HUB_URL, new StaticJwtProvider(JWT));
- // Serialize the update, and dispatch it to the hub, that will broadcast it to the clients
- $id = $publisher(new Update('https://example.com/books/1.jsonld', 'Hi from Symfony!', ['target1', 'target2']));
-
-Read the full :doc:`Mercure integration documentation ` to learn
-about all the features of this component and its integration with the Symfony
-framework.
-
-.. _`Mercure`: https://mercure.rocks
diff --git a/components/messenger.rst b/components/messenger.rst
index f073b47b255..a8ff1e5290e 100644
--- a/components/messenger.rst
+++ b/components/messenger.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Messenger
- single: Components; Messenger
-
The Messenger Component
=======================
@@ -31,7 +27,9 @@ Concepts
.. raw:: html
-
+
**Sender**:
Responsible for serializing and sending messages to *something*. This
@@ -54,14 +52,16 @@ Concepts
For instance: logging, validating a message, starting a transaction, ...
They are also responsible for calling the next middleware in the chain,
which means they can tweak the envelope, by adding stamps to it or even
- replacing it, as well as interrupt the middleware chain.
+ replacing it, as well as interrupt the middleware chain. Middleware are called
+ both when a message is originally dispatched and again later when a message
+ is received from a transport.
-**Envelope**
+**Envelope**:
Messenger specific concept, it gives full flexibility inside the message bus,
by wrapping the messages into it, allowing to add useful information inside
through *envelope stamps*.
-**Envelope Stamps**
+**Envelope Stamps**:
Piece of information you need to attach to your message: serializer context
to use for transport, markers identifying a received message or any sort of
metadata your middleware or transport layer may use.
@@ -75,16 +75,19 @@ middleware stack. The component comes with a set of middleware that you can use.
When using the message bus with Symfony's FrameworkBundle, the following middleware
are configured for you:
-#. :class:`Symfony\\Component\\Messenger\\Middleware\\SendMessageMiddleware` (enables asynchronous processing, logs the processing of your messages if you pass a logger)
+#. :class:`Symfony\\Component\\Messenger\\Middleware\\SendMessageMiddleware` (enables asynchronous processing, logs the processing of your messages if you provide a logger)
#. :class:`Symfony\\Component\\Messenger\\Middleware\\HandleMessageMiddleware` (calls the registered handler(s))
Example::
use App\Message\MyMessage;
+ use App\MessageHandler\MyMessageHandler;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
+ $handler = new MyMessageHandler();
+
$bus = new MessageBus([
new HandleMessageMiddleware(new HandlersLocator([
MyMessage::class => [$handler],
@@ -110,12 +113,14 @@ that will do the required processing for your message::
class MyMessageHandler
{
- public function __invoke(MyMessage $message)
+ public function __invoke(MyMessage $message): void
{
// Message processing...
}
}
+.. _messenger-envelopes:
+
Adding Metadata to Messages (Envelopes)
---------------------------------------
@@ -135,26 +140,49 @@ through the transport layer, use the ``SerializerStamp`` stamp::
]))
);
-At the moment, the Symfony Messenger has the following built-in envelope stamps:
-
-#. :class:`Symfony\\Component\\Messenger\\Stamp\\SerializerStamp`,
- to configure the serialization groups used by the transport.
-#. :class:`Symfony\\Component\\Messenger\\Stamp\\ValidationStamp`,
- to configure the validation groups used when the validation middleware is enabled.
-#. :class:`Symfony\\Component\\Messenger\\Stamp\\ReceivedStamp`,
- an internal stamp that marks the message as received from a transport.
-#. :class:`Symfony\\Component\\Messenger\\Stamp\\SentStamp`,
- a stamp that marks the message as sent by a specific sender.
- Allows accessing the sender FQCN and the alias if available from the
- :class:`Symfony\\Component\\Messenger\\Transport\\Sender\\SendersLocator`.
-#. :class:`Symfony\\Component\\Messenger\\Stamp\\HandledStamp`,
- a stamp that marks the message as handled by a specific handler.
- Allows accessing the handler returned value and the handler name.
+Here are some important envelope stamps that are shipped with the Symfony Messenger:
+
+* :class:`Symfony\\Component\\Messenger\\Stamp\\DelayStamp`,
+ to delay handling of an asynchronous message.
+* :class:`Symfony\\Component\\Messenger\\Stamp\\DispatchAfterCurrentBusStamp`,
+ to make the message be handled after the current bus has executed. Read more
+ at :ref:`messenger-transactional-messages`.
+* :class:`Symfony\\Component\\Messenger\\Stamp\\HandledStamp`,
+ a stamp that marks the message as handled by a specific handler.
+ Allows accessing the handler returned value and the handler name.
+* :class:`Symfony\\Component\\Messenger\\Stamp\\ReceivedStamp`,
+ an internal stamp that marks the message as received from a transport.
+* :class:`Symfony\\Component\\Messenger\\Stamp\\SentStamp`,
+ a stamp that marks the message as sent by a specific sender.
+ Allows accessing the sender FQCN and the alias if available from the
+ :class:`Symfony\\Component\\Messenger\\Transport\\Sender\\SendersLocator`.
+* :class:`Symfony\\Component\\Messenger\\Stamp\\SerializerStamp`,
+ to configure the serialization groups used by the transport.
+* :class:`Symfony\\Component\\Messenger\\Stamp\\ValidationStamp`,
+ to configure the validation groups used when the validation middleware is enabled.
+* :class:`Symfony\\Component\\Messenger\\Stamp\\ErrorDetailsStamp`,
+ an internal stamp when a message fails due to an exception in the handler.
+* :class:`Symfony\\Component\\Scheduler\\Messenger\\ScheduledStamp`,
+ a stamp that marks the message as produced by a scheduler. This helps
+ differentiate it from messages created "manually". You can learn more about it
+ in the :doc:`Scheduler documentation `.
+
+.. note::
+
+ The :class:`Symfony\\Component\\Messenger\\Stamp\\ErrorDetailsStamp` stamp
+ contains a :class:`Symfony\\Component\\ErrorHandler\\Exception\\FlattenException`,
+ which is a representation of the exception that made the message fail. You can
+ get this exception with the
+ :method:`Symfony\\Component\\Messenger\\Stamp\\ErrorDetailsStamp::getFlattenException`
+ method. This exception is normalized thanks to the
+ :class:`Symfony\\Component\\Messenger\\Transport\\Serialization\\Normalizer\\FlattenExceptionNormalizer`
+ which helps error reporting in the Messenger context.
Instead of dealing directly with the messages in the middleware you receive the envelope.
Hence you can inspect the envelope content and its stamps, or add any::
use App\Message\Stamp\AnotherStamp;
+ use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;
@@ -168,6 +196,8 @@ Hence you can inspect the envelope content and its stamps, or add any::
// You could for example add another stamp.
$envelope = $envelope->with(new AnotherStamp(/* ... */));
+ } else {
+ // Message was just originally dispatched
}
return $stack->next()->handle($envelope, $stack);
@@ -202,7 +232,7 @@ Your own Sender
Imagine that you already have an ``ImportantAction`` message going through the
message bus and being handled by a handler. Now, you also want to send this
message as an email (using the :doc:`Mime ` and
-:doc:`Mailer ` components).
+:doc:`Mailer ` components).
Using the :class:`Symfony\\Component\\Messenger\\Transport\\Sender\\SenderInterface`,
you can create your own message sender::
@@ -217,13 +247,10 @@ you can create your own message sender::
class ImportantActionToEmailSender implements SenderInterface
{
- private $mailer;
- private $toEmail;
-
- public function __construct(MailerInterface $mailer, string $toEmail)
- {
- $this->mailer = $mailer;
- $this->toEmail = $toEmail;
+ public function __construct(
+ private MailerInterface $mailer,
+ private string $toEmail,
+ ) {
}
public function send(Envelope $envelope): Envelope
@@ -269,19 +296,22 @@ do is to write your own CSV receiver::
class NewOrdersFromCsvFileReceiver implements ReceiverInterface
{
- private $serializer;
- private $filePath;
-
- public function __construct(SerializerInterface $serializer, string $filePath)
- {
- $this->serializer = $serializer;
- $this->filePath = $filePath;
+ private $connection;
+
+ public function __construct(
+ private SerializerInterface $serializer,
+ private string $filePath,
+ ) {
+ // Available connection bundled with the Messenger component
+ // can be found in "Symfony\Component\Messenger\Bridge\*\Transport\Connection".
+ $this->connection = /* create your connection */;
}
public function get(): iterable
{
// Receive the envelope according to your transport ($yourEnvelope here),
// in most cases, using a connection is the easiest solution.
+ $yourEnvelope = $this->connection->get();
if (null === $yourEnvelope) {
return [];
}
@@ -307,7 +337,9 @@ do is to write your own CSV receiver::
public function reject(Envelope $envelope): void
{
// In the case of a custom connection
- $this->connection->reject($this->findCustomStamp($envelope)->getId());
+ $id = /* get the message id thanks to information or stamps present in the envelope */;
+
+ $this->connection->reject($id);
}
}
@@ -329,5 +361,5 @@ Learn more
/messenger
/messenger/*
-.. _`blog posts about command buses`: https://matthiasnoback.nl/tags/command%20bus/
-.. _`SimpleBus project`: http://docs.simplebus.io/en/latest/
+.. _`blog posts about command buses`: https://matthiasnoback.nl/tags/command-bus/
+.. _`SimpleBus project`: https://docs.simplebus.io/en/latest/
diff --git a/components/mime.rst b/components/mime.rst
index e2dd3b05056..c043b342ebc 100644
--- a/components/mime.rst
+++ b/components/mime.rst
@@ -1,8 +1,3 @@
-.. index::
- single: MIME
- single: MIME Messages
- single: Components; MIME
-
The Mime Component
==================
@@ -34,7 +29,7 @@ complexity to provide two ways of creating MIME messages:
* A high-level API based on the :class:`Symfony\\Component\\Mime\\Email` class
to quickly create email messages with all the common features;
* A low-level API based on the :class:`Symfony\\Component\\Mime\\Message` class
- to have an absolute control over every single part of the email message.
+ to have absolute control over every single part of the email message.
Usage
-----
@@ -56,12 +51,8 @@ methods to compose the entire email message::
->html('Lorem ipsum ...
')
;
-This only purpose of this component is to create the email messages. Use the
-:doc:`Mailer component ` to actually send them. In Symfony
-applications, it's easier to use the :doc:`Mailer integration `.
-
-Most of the details about how to create Email objects, including Twig integration,
-can be found in the :doc:`Mailer documentation `.
+The only purpose of this component is to create the email messages. Use the
+:doc:`Mailer component ` to actually send them.
Twig Integration
----------------
@@ -103,12 +94,12 @@ extension:
.. code-block:: terminal
- $ composer require twig/cssinliner-extension
+ $ composer require twig/cssinliner-extra
Now, enable the extension::
// ...
- use Twig\CssInliner\CssInlinerExtension;
+ use Twig\Extra\CssInliner\CssInlinerExtension;
$loader = new FilesystemLoader(__DIR__.'/templates');
$twig = new Environment($loader);
@@ -166,7 +157,7 @@ different parts of the email by hand::
;
$textContent = new TextPart('Lorem ipsum...');
- $htmlContent = new TextPart('Lorem ipsum ...
', 'html');
+ $htmlContent = new TextPart('Lorem ipsum ...
', null, 'html');
$body = new AlternativePart($textContent, $htmlContent);
$email = new Message($headers, $body);
@@ -188,7 +179,7 @@ email multiparts::
$textContent = new TextPart('Lorem ipsum...');
$htmlContent = new TextPart(sprintf(
' Lorem ipsum ...
', $imageCid
- ), 'html');
+ ), null, 'html');
$bodyContent = new AlternativePart($textContent, $htmlContent);
$body = new RelatedPart($bodyContent, $embeddedImage);
@@ -242,10 +233,10 @@ MIME types and file name extensions::
$exts = $mimeTypes->getExtensions('image/jpeg');
// $exts = ['jpeg', 'jpg', 'jpe']
- $mimeTypes = $mimeTypes->getMimeTypes('js');
- // $mimeTypes = ['application/javascript', 'application/x-javascript', 'text/javascript']
- $mimeTypes = $mimeTypes->getMimeTypes('apk');
- // $mimeTypes = ['application/vnd.android.package-archive']
+ $types = $mimeTypes->getMimeTypes('js');
+ // $types = ['application/javascript', 'application/x-javascript', 'text/javascript']
+ $types = $mimeTypes->getMimeTypes('apk');
+ // $types = ['application/vnd.android.package-archive']
These methods return arrays with one or more elements. The element position
indicates its priority, so the first returned extension is the preferred one.
@@ -272,7 +263,7 @@ that extension to improve the guessing performance.
Adding a MIME Type Guesser
..........................
-You can register your own MIME type guesser by creating a class that implements
+You can add your own MIME type guesser by creating a class that implements
:class:`Symfony\\Component\\Mime\\MimeTypeGuesserInterface`::
namespace App;
@@ -296,6 +287,12 @@ You can register your own MIME type guesser by creating a class that implements
}
}
+MIME type guessers must be :ref:`registered as services `
+and :doc:`tagged ` with the ``mime.mime_type_guesser`` tag.
+If you're using the
+:ref:`default services.yaml configuration `,
+this is already done for you, thanks to :ref:`autoconfiguration `.
+
.. _`MIME`: https://en.wikipedia.org/wiki/MIME
.. _`MIME types`: https://en.wikipedia.org/wiki/Media_type
-.. _`fileinfo extension`: https://php.net/fileinfo
+.. _`fileinfo extension`: https://www.php.net/fileinfo
diff --git a/components/options_resolver.rst b/components/options_resolver.rst
index 48d69128b8e..17ec46c2fc9 100644
--- a/components/options_resolver.rst
+++ b/components/options_resolver.rst
@@ -1,7 +1,3 @@
-.. index::
- single: OptionsResolver
- single: Components; OptionsResolver
-
The OptionsResolver Component
=============================
@@ -27,7 +23,7 @@ Imagine you have a ``Mailer`` class which has four options: ``host``,
class Mailer
{
- protected $options;
+ protected array $options;
public function __construct(array $options = [])
{
@@ -41,7 +37,7 @@ check which options are set::
class Mailer
{
// ...
- public function sendMail($from, $to)
+ public function sendMail($from, $to): void
{
$mail = ...;
@@ -55,7 +51,7 @@ check which options are set::
}
Also, the default values of the options are buried in the business logic of your
-code. Use the :phpfunction:`array_replace` to fix that::
+code. Use :phpfunction:`array_replace` to fix that::
class Mailer
{
@@ -125,7 +121,7 @@ code::
{
// ...
- public function sendMail($from, $to)
+ public function sendMail($from, $to): void
{
$mail = ...;
$mail->setHost($this->options['host']);
@@ -151,7 +147,7 @@ It's a good practice to split the option configuration into a separate method::
$this->options = $resolver->resolve($options);
}
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'host' => 'smtp.example.org',
@@ -170,7 +166,7 @@ than processing options. Second, sub-classes may now override the
// ...
class GoogleMailer extends Mailer
{
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
@@ -193,7 +189,7 @@ For example, to make the ``host`` option required, you can do::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setRequired('host');
@@ -217,7 +213,7 @@ one required option::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setRequired(['host', 'username', 'password']);
@@ -232,7 +228,7 @@ retrieve the names of all required options::
// ...
class GoogleMailer extends Mailer
{
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
@@ -255,7 +251,7 @@ been set::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setRequired('host');
@@ -265,7 +261,7 @@ been set::
// ...
class GoogleMailer extends Mailer
{
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
@@ -285,7 +281,7 @@ been set::
}
}
-The method :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::getMissingOptions`
+The :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::getMissingOptions` method
lets you access the names of all missing options.
Type Validation
@@ -300,7 +296,7 @@ correctly. To validate the types of the options, call
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
@@ -309,13 +305,21 @@ correctly. To validate the types of the options, call
// specify multiple allowed types
$resolver->setAllowedTypes('port', ['null', 'int']);
+ // if you prefer, you can also use the following equivalent syntax
+ $resolver->setAllowedTypes('port', 'int|null');
// check all items in an array recursively for a type
$resolver->setAllowedTypes('dates', 'DateTime[]');
$resolver->setAllowedTypes('ports', 'int[]');
+ // the following syntax means "an array of integers or an array of strings"
+ $resolver->setAllowedTypes('endpoints', '(int|string)[]');
}
}
+.. versionadded:: 7.3
+
+ Defining type unions with the ``|`` syntax was introduced in Symfony 7.3.
+
You can pass any type for which an ``is_()`` function is defined in PHP.
You may also pass fully qualified class or interface names (which is checked
using ``instanceof``). Additionally, you can validate all items in an array
@@ -335,6 +339,8 @@ is thrown::
In sub-classes, you can use :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::addAllowedTypes`
to add additional allowed types without erasing the ones already set.
+.. _optionsresolver-validate-value:
+
Value Validation
~~~~~~~~~~~~~~~~
@@ -349,7 +355,7 @@ to verify that the passed option contains one of these values::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setDefault('transport', 'sendmail');
@@ -372,10 +378,25 @@ For options with more complicated validation schemes, pass a closure which
returns ``true`` for acceptable values and ``false`` for invalid values::
// ...
- $resolver->setAllowedValues('transport', function ($value) {
+ $resolver->setAllowedValues('transport', function (string $value): bool {
// return true or false
});
+.. tip::
+
+ You can even use the :doc:`Validator ` component to validate the
+ input by using the :method:`Symfony\\Component\\Validator\\Validation::createIsValidCallable`
+ method::
+
+ use Symfony\Component\OptionsResolver\OptionsResolver;
+ use Symfony\Component\Validator\Constraints\Length;
+ use Symfony\Component\Validator\Validation;
+
+ // ...
+ $resolver->setAllowedValues('transport', Validation::createIsValidCallable(
+ new Length(min: 10)
+ ));
+
In sub-classes, you can use :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::addAllowedValues`
to add additional allowed values without erasing the ones already set.
@@ -395,12 +416,12 @@ option. You can configure a normalizer by calling
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
- $resolver->setNormalizer('host', function (Options $options, $value) {
- if ('http://' !== substr($value, 0, 7)) {
+ $resolver->setNormalizer('host', function (Options $options, string $value): string {
+ if (!str_starts_with($value, 'http://')) {
$value = 'http://'.$value;
}
@@ -417,11 +438,11 @@ if you need to use other options during normalization::
class Mailer
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
- $resolver->setNormalizer('host', function (Options $options, $value) {
- if ('http://' !== substr($value, 0, 7) && 'https://' !== substr($value, 0, 8)) {
+ $resolver->setNormalizer('host', function (Options $options, string $value): string {
+ if (!str_starts_with($value, 'http://') && !str_starts_with($value, 'https://')) {
if ('ssl' === $options['encryption']) {
$value = 'https://'.$value;
} else {
@@ -434,8 +455,8 @@ if you need to use other options during normalization::
}
}
-To normalize a new allowed value in sub-classes that are being normalized
-in parent classes use :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::addNormalizer`.
+To normalize a new allowed value in subclasses that are being normalized
+in parent classes, use :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::addNormalizer` method.
This way, the ``$value`` argument will receive the previously normalized
value, otherwise you can prepend the new normalizer by passing ``true`` as
third argument.
@@ -448,7 +469,7 @@ encryption chosen by the user of the ``Mailer`` class. More precisely, you want
to set the port to ``465`` if SSL is used and to ``25`` otherwise.
You can implement this feature by passing a closure as the default value of
-the ``port`` option. The closure receives the options as argument. Based on
+the ``port`` option. The closure receives the options as arguments. Based on
these options, you can return the desired default value::
use Symfony\Component\OptionsResolver\Options;
@@ -457,12 +478,12 @@ these options, you can return the desired default value::
class Mailer
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setDefault('encryption', null);
- $resolver->setDefault('port', function (Options $options) {
+ $resolver->setDefault('port', function (Options $options): int {
if ('ssl' === $options['encryption']) {
return 465;
}
@@ -472,7 +493,7 @@ these options, you can return the desired default value::
}
}
-.. caution::
+.. warning::
The argument of the callable must be type hinted as ``Options``. Otherwise,
the callable itself is considered as the default value of the option.
@@ -480,7 +501,7 @@ these options, you can return the desired default value::
.. note::
The closure is only executed if the ``port`` option isn't set by the user
- or overwritten in a sub-class.
+ or overwritten in a subclass.
A previously set default value can be accessed by adding a second argument to
the closure::
@@ -489,7 +510,7 @@ the closure::
class Mailer
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setDefaults([
@@ -501,13 +522,13 @@ the closure::
class GoogleMailer extends Mailer
{
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
- $resolver->setDefault('host', function (Options $options, $previousValue) {
+ $resolver->setDefault('host', function (Options $options, string $previousValue): string {
if ('ssl' === $options['encryption']) {
- return 'secure.example.org'
+ return 'secure.example.org';
}
// Take default value configured in the base class
@@ -532,14 +553,14 @@ from the default::
class Mailer
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setDefault('port', 25);
}
// ...
- public function sendMail($from, $to)
+ public function sendMail(string $from, string $to): void
{
// Is this the default value or did the caller of the class really
// set the port to 25?
@@ -559,14 +580,14 @@ be included in the resolved options if it was actually passed to
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setDefined('port');
}
// ...
- public function sendMail($from, $to)
+ public function sendMail(string $from, string $to): void
{
if (array_key_exists('port', $this->options)) {
echo 'Set!';
@@ -593,7 +614,7 @@ options in one go::
class Mailer
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
$resolver->setDefined(['port', 'encryption']);
@@ -609,7 +630,7 @@ let you find out which options are defined::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
@@ -639,9 +660,9 @@ default value::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
- $resolver->setDefault('spool', function (OptionsResolver $spoolResolver) {
+ $resolver->setOptions('spool', function (OptionsResolver $spoolResolver): void {
$spoolResolver->setDefaults([
'type' => 'file',
'path' => '/path/to/spool',
@@ -651,7 +672,7 @@ default value::
});
}
- public function sendMail($from, $to)
+ public function sendMail(string $from, string $to): void
{
if ('memory' === $this->options['spool']['type']) {
// ...
@@ -665,6 +686,16 @@ default value::
],
]);
+.. deprecated:: 7.3
+
+ Defining nested options via :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::setDefault`
+ is deprecated since Symfony 7.3. Use the :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::setOptions`
+ method instead, which also allows defining default values for prototyped options.
+
+.. versionadded:: 7.3
+
+ The ``setOptions()`` method was introduced in Symfony 7.3.
+
Nested options also support required options, validation (type, value) and
normalization of their values. If the default value of a nested option depends
on another option defined in the parent level, add a second ``Options`` argument
@@ -674,10 +705,10 @@ to the closure to access to them::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefault('sandbox', false);
- $resolver->setDefault('spool', function (OptionsResolver $spoolResolver, Options $parent) {
+ $resolver->setOptions('spool', function (OptionsResolver $spoolResolver, Options $parent): void {
$spoolResolver->setDefaults([
'type' => $parent['sandbox'] ? 'memory' : 'file',
// ...
@@ -686,7 +717,7 @@ to the closure to access to them::
}
}
-.. caution::
+.. warning::
The arguments of the closure must be type hinted as ``OptionsResolver`` and
``Options`` respectively. Otherwise, the closure itself is considered as the
@@ -698,15 +729,15 @@ In same way, parent options can access to the nested options as normal arrays::
{
// ...
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
- $resolver->setDefault('spool', function (OptionsResolver $spoolResolver) {
+ $resolver->setOptions('spool', function (OptionsResolver $spoolResolver): void {
$spoolResolver->setDefaults([
'type' => 'file',
// ...
]);
});
- $resolver->setDefault('profiling', function (Options $options) {
+ $resolver->setOptions('profiling', function (Options $options): void {
return 'file' === $options['spool']['type'];
});
}
@@ -717,6 +748,51 @@ In same way, parent options can access to the nested options as normal arrays::
The fact that an option is defined as nested means that you must pass
an array of values to resolve it at runtime.
+Prototype Options
+~~~~~~~~~~~~~~~~~
+
+There are situations where you will have to resolve and validate a set of
+options that may repeat many times within another option. Let's imagine a
+``connections`` option that will accept an array of database connections
+with ``host``, ``database``, ``user`` and ``password`` each.
+
+The best way to implement this is to define the ``connections`` option as prototype::
+
+ $resolver->setOptions('connections', function (OptionsResolver $connResolver): void {
+ $connResolver
+ ->setPrototype(true)
+ ->setRequired(['host', 'database'])
+ ->setDefaults(['user' => 'root', 'password' => null]);
+ });
+
+According to the prototype definition in the example above, it is possible
+to have multiple connection arrays like the following::
+
+ $resolver->resolve([
+ 'connections' => [
+ 'default' => [
+ 'host' => '127.0.0.1',
+ 'database' => 'symfony',
+ ],
+ 'test' => [
+ 'host' => '127.0.0.1',
+ 'database' => 'symfony_test',
+ 'user' => 'test',
+ 'password' => 'test',
+ ],
+ // ...
+ ],
+ ]);
+
+The array keys (``default``, ``test``, etc.) of this prototype option are
+validation-free and can be any arbitrary value that helps differentiate the
+connections.
+
+.. note::
+
+ A prototype option can only be defined inside a nested option and
+ during its resolution it will expect an array of arrays.
+
Deprecating the Option
~~~~~~~~~~~~~~~~~~~~~~
@@ -726,12 +802,21 @@ method::
$resolver
->setDefined(['hostname', 'host'])
- // this outputs the following generic deprecation message:
- // The option "hostname" is deprecated.
- ->setDeprecated('hostname')
- // you can also pass a custom deprecation message
- ->setDeprecated('hostname', 'The option "hostname" is deprecated, use "host" instead.')
+ // this outputs the following generic deprecation message:
+ // Since acme/package 1.2: The option "hostname" is deprecated.
+ ->setDeprecated('hostname', 'acme/package', '1.2')
+
+ // you can also pass a custom deprecation message (%name% placeholder is available)
+ // %name% placeholder will be replaced by the deprecated option.
+ // This outputs the following deprecation message:
+ // Since acme/package 1.2: The option "hostname" is deprecated, use "host" instead.
+ ->setDeprecated(
+ 'hostname',
+ 'acme/package',
+ '1.2',
+ 'The option "%name%" is deprecated, use "host" instead.'
+ )
;
.. note::
@@ -744,9 +829,13 @@ method::
When using an option deprecated by you in your own library, you can pass
``false`` as the second argument of the
- :method:`Symfony\\Component\\OptionsResolver\\Options::offsetGet()` method
+ :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::offsetGet` method
to not trigger the deprecation warning.
+.. note::
+
+ All deprecation messages are displayed in the profiler logs in the "Deprecations" tab.
+
Instead of passing the message, you may also pass a closure which returns
a string (the deprecation message) or an empty string to ignore the deprecation.
This closure is useful to only deprecate some of the allowed types or values of
@@ -756,7 +845,7 @@ the option::
->setDefault('encryption', null)
->setDefault('port', null)
->setAllowedTypes('port', ['null', 'int'])
- ->setDeprecated('port', function (Options $options, $value) {
+ ->setDeprecated('port', 'acme/package', '1.2', function (Options $options, ?int $value): string {
if (null === $value) {
return 'Passing "null" to option "port" is deprecated, pass an integer instead.';
}
@@ -778,6 +867,56 @@ the option::
This closure receives as argument the value of the option after validating it
and before normalizing it when the option is being resolved.
+Ignore not defined Options
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+By default, all options are resolved and validated, resulting in a
+:class:`Symfony\\Component\\OptionsResolver\\Exception\\UndefinedOptionsException`
+if an unknown option is passed. You can ignore not defined options by using the
+:method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::ignoreUndefined` method::
+
+ // ...
+ $resolver
+ ->setDefined(['hostname'])
+ ->setIgnoreUndefined(true)
+ ;
+
+ // option "version" will be ignored
+ $resolver->resolve([
+ 'hostname' => 'acme/package',
+ 'version' => '1.2.3'
+ ]);
+
+Chaining Option Configurations
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+In many cases you may need to define multiple configurations for each option.
+For example, suppose the ``InvoiceMailer`` class has an ``host`` option that is required
+and a ``transport`` option which can be one of ``sendmail``, ``mail`` and ``smtp``.
+You can improve the readability of the code avoiding to duplicate option name for
+each configuration using the :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::define`
+method::
+
+ // ...
+ class InvoiceMailer
+ {
+ // ...
+ public function configureOptions(OptionsResolver $resolver): void
+ {
+ // ...
+ $resolver->define('host')
+ ->required()
+ ->default('smtp.example.org')
+ ->allowedTypes('string')
+ ->info('The IP address or hostname');
+
+ $resolver->define('transport')
+ ->required()
+ ->default('transport')
+ ->allowedValues('sendmail', 'mail', 'smtp');
+ }
+ }
+
Performance Tweaks
~~~~~~~~~~~~~~~~~~
@@ -790,14 +929,14 @@ can change your code to do the configuration only once per class::
// ...
class Mailer
{
- private static $resolversByClass = [];
+ private static array $resolversByClass = [];
- protected $options;
+ protected array $options;
public function __construct(array $options = [])
{
// What type of Mailer is this, a Mailer, a GoogleMailer, ... ?
- $class = get_class($this);
+ $class = $this::class;
// Was configureOptions() executed before for this class?
if (!isset(self::$resolversByClass[$class])) {
@@ -808,7 +947,7 @@ can change your code to do the configuration only once per class::
$this->options = self::$resolversByClass[$class]->resolve($options);
}
- public function configureOptions(OptionsResolver $resolver)
+ public function configureOptions(OptionsResolver $resolver): void
{
// ...
}
@@ -823,9 +962,9 @@ method ``clearOptionsConfig()`` and call it periodically::
// ...
class Mailer
{
- private static $resolversByClass = [];
+ private static array $resolversByClass = [];
- public static function clearOptionsConfig()
+ public static function clearOptionsConfig(): void
{
self::$resolversByClass = [];
}
@@ -835,3 +974,21 @@ method ``clearOptionsConfig()`` and call it periodically::
That's it! You now have all the tools and knowledge needed to process
options in your code.
+
+Getting More Insights
+~~~~~~~~~~~~~~~~~~~~~
+
+Use the ``OptionsResolverIntrospector`` to inspect the options definitions
+inside an ``OptionsResolver`` instance::
+
+ use Symfony\Component\OptionsResolver\Debug\OptionsResolverIntrospector;
+ use Symfony\Component\OptionsResolver\OptionsResolver;
+
+ $resolver = new OptionsResolver();
+ $resolver->setDefaults([
+ 'host' => 'smtp.example.org',
+ 'port' => 25,
+ ]);
+
+ $introspector = new OptionsResolverIntrospector($resolver);
+ $introspector->getDefault('host'); // Retrieves "smtp.example.org"
diff --git a/components/phpunit_bridge.rst b/components/phpunit_bridge.rst
index 4e64f0a41ac..5ce4c003a11 100644
--- a/components/phpunit_bridge.rst
+++ b/components/phpunit_bridge.rst
@@ -1,7 +1,3 @@
-.. index::
- single: PHPUnitBridge
- single: Components; PHPUnitBridge
-
The PHPUnit Bridge
==================
@@ -11,8 +7,8 @@ The PHPUnit Bridge
It comes with the following features:
-* Forces the tests to use a consistent locale (``C``) (if you create
- locale-sensitive tests, use PHPUnit's ``setLocale()`` method);
+* Sets by default a consistent locale (``C``) for your tests (if you
+ create locale-sensitive tests, use PHPUnit's ``setLocale()`` method);
* Auto-register ``class_exists`` to load Doctrine annotations (when used);
@@ -23,10 +19,11 @@ It comes with the following features:
* Provides a ``ClockMock``, ``DnsMock`` and ``ClassExistsMock`` classes for tests
sensitive to time, network or class existence;
-* Provides a modified version of PHPUnit that allows 1. separating the
- dependencies of your app from those of phpunit to prevent any unwanted
- constraints to apply; 2. running tests in parallel when a test suite is split
- in several phpunit.xml files; 3. recording and replaying skipped tests;
+* Provides a modified version of PHPUnit that allows:
+
+ #. separating the dependencies of your app from those of phpunit to prevent any unwanted constraints to apply;
+ #. running tests in parallel when a test suite is split in several phpunit.xml files;
+ #. recording and replaying skipped tests;
* It allows to create tests that are compatible with multiple PHPUnit versions
(because it provides polyfills for missing methods, namespaced aliases for
@@ -48,13 +45,13 @@ Installation
always use its very latest stable major version to get the most accurate
deprecation report.
-If you plan to :ref:`write-assertions-about-deprecations` and use the regular
+If you plan to :ref:`write assertions about deprecations ` and use the regular
PHPUnit script (not the modified PHPUnit script provided by Symfony), you have
to register a new `test listener`_ called ``SymfonyTestsListener``:
.. code-block:: xml
-
+
@@ -153,7 +150,7 @@ a directory containing multiple test suites with their own ``phpunit.xml.dist``.
$ ./vendor/bin/simple-phpunit tests/
The modified PHPUnit script will recursively go through the provided directory,
-up to a depth of 3 subfolders or the value specified by the environment variable
+up to a depth of 3 subdirectories or the value specified by the environment variable
``SYMFONY_PHPUNIT_MAX_DEPTH``, looking for ``phpunit.xml.dist`` files and then
running each suite it finds in parallel, collecting their output and displaying
each test suite's results in their own section.
@@ -161,15 +158,14 @@ each test suite's results in their own section.
Trigger Deprecation Notices
---------------------------
-Deprecation notices can be triggered by using::
+Deprecation notices can be triggered by using ``trigger_deprecation`` from
+the ``symfony/deprecation-contracts`` package::
- @trigger_error('Your deprecation message', E_USER_DEPRECATED);
+ // indicates something is deprecated since version 1.3 of vendor-name/packagename
+ trigger_deprecation('vendor-name/package-name', '1.3', 'Your deprecation message');
-Without the `@-silencing operator`_, users would need to opt-out from deprecation
-notices. Silencing by default swaps this behavior and allows users to opt-in
-when they are ready to cope with them (by adding a custom error handler like the
-one provided by this bridge). When not silenced, deprecation notices will appear
-in the **Unsilenced** section of the deprecation report.
+ // you can also use printf format (all arguments after the message will be used)
+ trigger_deprecation('...', '1.3', 'Value "%s" is deprecated, use ... instead.', $value);
Mark Tests as Legacy
--------------------
@@ -204,7 +200,7 @@ message, enclosed with ``/``. For example, with:
.. code-block:: xml
-
+
@@ -213,28 +209,30 @@ message, enclosed with ``/``. For example, with:
-
+
`PHPUnit`_ will stop your test suite once a deprecation notice is triggered whose
message contains the ``"foobar"`` string.
+.. _making-tests-fail:
+
Making Tests Fail
~~~~~~~~~~~~~~~~~
-By default, any non-legacy-tagged or any non-`@-silenced`_ deprecation
-notices will make tests fail. Alternatively, you can configure an
-arbitrary threshold by setting ``SYMFONY_DEPRECATIONS_HELPER`` to
-``max[total]=320`` for instance. It will make the tests fails only if a
+By default, any non-legacy-tagged or any non-silenced (`@-silencing operator`_)
+deprecation notices will make tests fail. Alternatively, you can configure
+an arbitrary threshold by setting ``SYMFONY_DEPRECATIONS_HELPER`` to
+``max[total]=320`` for instance. It will make the tests fail only if a
higher number of deprecation notices is reached (``0`` is the default
value).
You can have even finer-grained control by using other keys of the ``max``
array, which are ``self``, ``direct``, and ``indirect``. The
-``SYMFONY_DEPRECATIONS_HELPER`` environment variable accepts an URL-encoded
+``SYMFONY_DEPRECATIONS_HELPER`` environment variable accepts a URL-encoded
string, meaning you can combine thresholds and any other configuration setting,
-like this: ``SYMFONY_DEPRECATIONS_HELPER=max[total]=42&max[self]=0&verbose=0``
+like this: ``SYMFONY_DEPRECATIONS_HELPER='max[total]=42&max[self]=0&verbose=0'``
Internal deprecations
.....................
@@ -255,7 +253,7 @@ deprecations but:
* forget to mark appropriate tests with the ``@group legacy`` annotations.
By using ``SYMFONY_DEPRECATIONS_HELPER=max[self]=0``, deprecations that are
-triggered outside the ``vendors`` directory will be accounted for separately,
+triggered outside the ``vendor/`` directory will be accounted for separately,
while deprecations triggered from a library inside it will not (unless you reach
999999 of these), giving you the best of both worlds.
@@ -290,6 +288,55 @@ Here is a summary that should help you pick the right configuration:
| | cannot afford to use one of the modes above. |
+------------------------+-----------------------------------------------------+
+Ignoring Deprecations
+.....................
+
+If your application has some deprecations that you can't fix for some reasons,
+you can tell Symfony to ignore them.
+
+You need first to create a text file where each line is a deprecation to ignore
+defined as a regular expression. Lines beginning with a hash (``#``) are
+considered comments:
+
+.. code-block:: terminal
+
+ # This file contains patterns to be ignored while testing for use of
+ # deprecated code.
+
+ %The "Symfony\\Component\\Validator\\Context\\ExecutionContextInterface::.*\(\)" method is considered internal Used by the validator engine\. (Should not be called by user\W+code\. )?It may change without further notice\. You should not extend it from "[^"]+"\.%
+ %The "PHPUnit\\Framework\\TestCase::addWarning\(\)" method is considered internal%
+
+Then, you can run the following command to use that file and ignore those deprecations:
+
+.. code-block:: terminal
+
+ $ SYMFONY_DEPRECATIONS_HELPER='ignoreFile=./tests/baseline-ignore' ./vendor/bin/simple-phpunit
+
+Baseline Deprecations
+.....................
+
+You can also take a snapshot of deprecations currently triggered by your application
+code, and ignore those during your test runs, still reporting newly added ones.
+The trick is to create a file with the allowed deprecations and define it as the
+"deprecation baseline". Deprecations inside that file are ignored but the rest of
+deprecations are still reported.
+
+First, generate the file with the allowed deprecations (run the same command
+whenever you want to update the existing file):
+
+.. code-block:: terminal
+
+ $ SYMFONY_DEPRECATIONS_HELPER='generateBaseline=true&baselineFile=./tests/allowed.json' ./vendor/bin/simple-phpunit
+
+This command stores all the deprecations reported while running tests in the
+given file path and encoded in JSON.
+
+Then, you can run the following command to use that file and ignore those deprecations:
+
+.. code-block:: terminal
+
+ $ SYMFONY_DEPRECATIONS_HELPER='baselineFile=./tests/allowed.json' ./vendor/bin/simple-phpunit
+
Disabling the Verbose Output
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -297,6 +344,14 @@ By default, the bridge will display a detailed output with the number of
deprecations and where they arise. If this is too much for you, you can use
``SYMFONY_DEPRECATIONS_HELPER=verbose=0`` to turn the verbose output off.
+It's also possible to change verbosity per deprecation type. For example, using
+``quiet[]=indirect&quiet[]=other`` will hide details for deprecations of types
+"indirect" and "other".
+
+The ``quiet`` option hides details for the specified deprecation types, but will
+not change the outcome in terms of exit code. That's what :ref:`max `
+is for, and both settings are orthogonal.
+
Disabling the Deprecation Helper
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -305,14 +360,12 @@ to completely disable the deprecation helper. This is useful to make use of the
rest of features provided by this component without getting errors or messages
related to deprecations.
-.. _write-assertions-about-deprecations:
-
Deprecation Notices at Autoloading Time
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By default, the PHPUnit Bridge uses ``DebugClassLoader`` from the
-`Debug component`_ to throw deprecation notices at class autoloading time.
-This can be disabled with the ``debug-class-loader`` option.
+`ErrorHandler component`_ to throw deprecation notices at class autoloading
+time. This can be disabled with the ``debug-class-loader`` option.
.. code-block:: xml
@@ -329,26 +382,90 @@ This can be disabled with the ``debug-class-loader`` option.
+Compile-time Deprecations
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Use the ``debug:container`` command to list the deprecations generated during
+the compiling and warming up of the container:
+
+.. code-block:: terminal
+
+ $ php bin/console debug:container --deprecations
+
+Log Deprecations
+~~~~~~~~~~~~~~~~
+
+For turning the verbose output off and write it to a log file instead you can use
+``SYMFONY_DEPRECATIONS_HELPER='logFile=/path/deprecations.log'``.
+
+Setting The Locale For Tests
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+By default, the PHPUnit Bridge forces the locale to ``C`` to avoid locale
+issues in tests. This behavior can be changed by setting the
+``SYMFONY_PHPUNIT_LOCALE`` environment variable to the desired locale:
+
+.. code-block:: bash
+
+ # .env.test
+ SYMFONY_PHPUNIT_LOCALE="fr_FR"
+
+Alternatively, you can set this environment variable in the PHPUnit
+configuration file:
+
+.. code-block:: xml
+
+
+
+
+
+
+
+
+
+
+
+
+Finally, if you want to avoid the bridge to force any locale, you can set the
+``SYMFONY_PHPUNIT_LOCALE`` environment variable to ``0``.
+
+.. _write-assertions-about-deprecations:
+
Write Assertions about Deprecations
-----------------------------------
When adding deprecations to your code, you might like writing tests that verify
that they are triggered as required. To do so, the bridge provides the
-``@expectedDeprecation`` annotation that you can use on your test methods.
+``expectDeprecation()`` method that you can use on your test methods.
It requires you to pass the expected message, given in the same format as for
the `PHPUnit's assertStringMatchesFormat()`_ method. If you expect more than one
-deprecation message for a given test method, you can use the annotation several
+deprecation message for a given test method, you can use the method several
times (order matters)::
- /**
- * @group legacy
- * @expectedDeprecation This "%s" method is deprecated.
- * @expectedDeprecation The second argument of the "%s" method is deprecated.
- */
- public function testDeprecatedCode()
+ use PHPUnit\Framework\TestCase;
+ use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
+
+ class MyTest extends TestCase
{
- @trigger_error('This "Foo" method is deprecated.', E_USER_DEPRECATED);
- @trigger_error('The second argument of the "Bar" method is deprecated.', E_USER_DEPRECATED);
+ use ExpectDeprecationTrait;
+
+ /**
+ * @group legacy
+ */
+ public function testDeprecatedCode(): void
+ {
+ // test some code that triggers the following deprecation:
+ // trigger_deprecation('vendor-name/package-name', '5.1', 'This "Foo" method is deprecated.');
+ $this->expectDeprecation('Since vendor-name/package-name 5.1: This "%s" method is deprecated');
+
+ // ...
+
+ // test some code that triggers the following deprecation:
+ // trigger_deprecation('vendor-name/package-name', '4.4', 'The second argument of the "Bar" method is deprecated.');
+ $this->expectDeprecation('Since vendor-name/package-name 4.4: The second argument of the "%s" method is deprecated.');
+ }
}
Display the Full Stack Trace
@@ -402,32 +519,6 @@ PHPUnit to remove the return type (introduced in PHPUnit 8) from ``setUp()``,
``tearDown()``, ``setUpBeforeClass()`` and ``tearDownAfterClass()`` methods.
This allows you to write a test compatible with both PHP 5 and PHPUnit 8.
-Alternatively, you can use the trait :class:`Symfony\\Bridge\\PhpUnit\\SetUpTearDownTrait`,
-which provides the right signature for the ``setUp()``, ``tearDown()``,
-``setUpBeforeClass()`` and ``tearDownAfterClass()`` methods and delegates the
-call to the ``doSetUp()``, ``doTearDown()``, ``doSetUpBeforeClass()`` and
-``doTearDownAfterClass()`` methods::
-
- use PHPUnit\Framework\TestCase;
- use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
-
- class MyTest extends TestCase
- {
- // when using the SetUpTearDownTrait, methods like doSetup() can
- // be defined with and without the 'void' return type, as you wish
- use SetUpTearDownTrait;
-
- private function doSetup()
- {
- // ...
- }
-
- protected function doSetup(): void
- {
- // ...
- }
- }
-
Using Namespaced PHPUnit Classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -449,7 +540,7 @@ If you have this kind of time-related tests::
class MyTest extends TestCase
{
- public function testSomething()
+ public function testSomething(): void
{
$stopwatch = new Stopwatch();
@@ -461,8 +552,8 @@ If you have this kind of time-related tests::
}
}
-You used the :doc:`Symfony Stopwatch Component ` to
-calculate the duration time of your process, here 10 seconds. However, depending
+You calculated the duration time of your process using the Stopwatch utilities to
+:ref:`profile Symfony applications `. However, depending
on the load of the server or the processes running on your local machine, the
``$duration`` could for example be ``10.000023s`` instead of ``10s``.
@@ -475,13 +566,14 @@ Clock Mocking
The :class:`Symfony\\Bridge\\PhpUnit\\ClockMock` class provided by this bridge
allows you to mock the PHP's built-in time functions ``time()``, ``microtime()``,
-``sleep()``, ``usleep()`` and ``gmdate()``. Additionally the function ``date()``
-is mocked so it uses the mocked time if no timestamp is specified.
+``sleep()``, ``usleep()``, ``gmdate()``, and ``hrtime()``. Additionally the
+function ``date()`` is mocked so it uses the mocked time if no timestamp is
+specified.
Other functions with an optional timestamp parameter that defaults to ``time()``
will still use the system time instead of the mocked time. This means that you
may need to change some code in your tests. For example, instead of ``new DateTime()``,
-you should use ``DateTime::createFromFormat('U', time())`` to use the mocked
+you should use ``DateTime::createFromFormat('U', (string) time())`` to use the mocked
``time()`` function.
To use the ``ClockMock`` class in your test, add the ``@group time-sensitive``
@@ -515,7 +607,7 @@ test::
*/
class MyTest extends TestCase
{
- public function testSomething()
+ public function testSomething(): void
{
$stopwatch = new Stopwatch();
@@ -529,7 +621,7 @@ test::
And that's all!
-.. caution::
+.. warning::
Time-based function mocking follows the `PHP namespace resolutions rules`_
so "fully qualified function calls" (e.g ``\time()``) cannot be mocked.
@@ -543,7 +635,7 @@ different class, do it explicitly using ``ClockMock::register(MyClass::class)``:
class MyClass
{
- public function getTimeInHours()
+ public function getTimeInHours(): void
{
return time() / 3600;
}
@@ -561,7 +653,7 @@ different class, do it explicitly using ``ClockMock::register(MyClass::class)``:
*/
class MyTest extends TestCase
{
- public function testGetTimeInHours()
+ public function testGetTimeInHours(): void
{
ClockMock::register(MyClass::class);
@@ -609,7 +701,7 @@ associated to a valid host::
class MyTest extends TestCase
{
- public function testEmail()
+ public function testEmail(): void
{
$validator = new DomainValidator(['checkDnsRecord' => true]);
$isValid = $validator->validate('example.com');
@@ -618,7 +710,7 @@ associated to a valid host::
}
}
-In order to avoid making a real network connection, add the ``@dns-sensitive``
+In order to avoid making a real network connection, add the ``@group dns-sensitive``
annotation to the class and use the ``DnsMock::withMockedHosts()`` to configure
the data you expect to get for the given hosts::
@@ -631,7 +723,7 @@ the data you expect to get for the given hosts::
*/
class DomainValidatorTest extends TestCase
{
- public function testEmails()
+ public function testEmails(): void
{
DnsMock::withMockedHosts([
'example.com' => [['type' => 'A', 'ip' => '1.2.3.4']],
@@ -672,6 +764,7 @@ reason, this component also provides mocks for these PHP functions:
* :phpfunction:`class_exists`
* :phpfunction:`interface_exists`
* :phpfunction:`trait_exists`
+* :phpfunction:`enum_exists`
Use Case
~~~~~~~~
@@ -701,7 +794,7 @@ are installed during tests) would look like::
class MyClassTest extends TestCase
{
- public function testHello()
+ public function testHello(): void
{
$class = new MyClass();
$result = $class->hello(); // "The dependency behavior."
@@ -722,7 +815,7 @@ classes, interfaces and/or traits for the code to run::
{
// ...
- public function testHelloDefault()
+ public function testHelloDefault(): void
{
ClassExistsMock::register(MyClass::class);
ClassExistsMock::withMockedClasses([DependencyClass::class => false]);
@@ -734,13 +827,23 @@ classes, interfaces and/or traits for the code to run::
}
}
+Note that mocking a class with ``ClassExistsMock::withMockedClasses()``
+will make :phpfunction:`class_exists`, :phpfunction:`interface_exists`
+and :phpfunction:`trait_exists` return true.
+
+To register an enumeration and mock :phpfunction:`enum_exists`,
+``ClassExistsMock::withMockedEnums()`` must be used. Note that, like in
+PHP 8.1 and later, calling ``class_exists`` on a enum will return ``true``.
+That's why calling ``ClassExistsMock::withMockedEnums()`` will also register the enum
+as a mocked class.
+
Troubleshooting
---------------
The ``@group time-sensitive`` and ``@group dns-sensitive`` annotations work
"by convention" and assume that the namespace of the tested class can be
obtained just by removing the ``Tests\`` part from the test namespace. I.e.
-that if the your test case fully-qualified class name (FQCN) is
+if your test cases fully-qualified class name (FQCN) is
``App\Tests\Watch\DummyWatchTest``, it assumes the tested class namespace
is ``App\Watch``.
@@ -750,7 +853,7 @@ namespaces in the ``phpunit.xml`` file, as done for example in the
.. code-block:: xml
-
+
@@ -770,10 +873,16 @@ namespaces in the ``phpunit.xml`` file, as done for example in the
Under the hood, a PHPUnit listener injects the mocked functions in the tested
classes' namespace. In order to work as expected, the listener has to run before
-the tested class ever runs. By default, the mocked functions are created when the
-annotation are found and the corresponding tests are run. Depending on how your
-tests are constructed, this might be too late. In this case, you will need to declare
-the namespaces of the tested classes in your phpunit.xml.dist
+the tested class ever runs.
+
+By default, the mocked functions are created when the annotation are found and
+the corresponding tests are run. Depending on how your tests are constructed,
+this might be too late.
+
+You can either:
+
+* Declare the namespaces of the tested classes in your ``phpunit.xml.dist``;
+* Register the namespaces at the end of the ``config/bootstrap.php`` file.
.. code-block:: xml
@@ -789,6 +898,16 @@ the namespaces of the tested classes in your phpunit.xml.dist
+::
+
+ // config/bootstrap.php
+ use Symfony\Bridge\PhpUnit\ClockMock;
+
+ // ...
+ if ('test' === $_SERVER['APP_ENV']) {
+ ClockMock::register('Acme\\MyClassTest\\');
+ }
+
Modified PHPUnit script
-----------------------
@@ -797,8 +916,6 @@ its ``bin/simple-phpunit`` command. It has the following features:
* Works with a standalone vendor directory that doesn't conflict with yours;
* Does not embed ``prophecy`` to prevent any conflicts with its dependencies;
-* Uses PHPUnit 4.8 when run with PHP <=5.5, PHPUnit 5.7 when run with PHP >=5.6
- and PHPUnit 6.5 when run with PHP >=7.2;
* Collects and replays skipped tests when the ``SYMFONY_PHPUNIT_SKIPPED_TESTS``
env var is defined: the env var should specify a file name that will be used for
storing skipped tests on a first run, and replay them on the second run;
@@ -811,18 +928,6 @@ configured by the ``SYMFONY_PHPUNIT_DIR`` env var, or in the same directory as
the ``simple-phpunit`` if it is not provided. It's also possible to set this
env var in the ``phpunit.xml.dist`` file.
-By default, these are the PHPUnit versions used depending on the installed PHP versions:
-
-===================== ===============================
-Installed PHP version PHPUnit version used by default
-===================== ===============================
-PHP <= 5.5 PHPUnit 4.8
-PHP 5.6 PHPUnit 5.7
-PHP 7.0 PHPUnit 6.5
-PHP 7.1 PHPUnit 7.5
-PHP >= 7.2 PHPUnit 8.3
-===================== ===============================
-
If you have installed the bridge through Composer, you can run it by calling e.g.:
.. code-block:: terminal
@@ -831,7 +936,7 @@ If you have installed the bridge through Composer, you can run it by calling e.g
.. tip::
- It's possible to change the base version of PHPUnit by setting the
+ It's possible to change the PHPUnit version by setting the
``SYMFONY_PHPUNIT_VERSION`` env var in the ``phpunit.xml.dist`` file (e.g.
`` ``). This is the
preferred method as it can be committed to your version control repository.
@@ -839,6 +944,10 @@ If you have installed the bridge through Composer, you can run it by calling e.g
It's also possible to set ``SYMFONY_PHPUNIT_VERSION`` as a real env var
(not defined in a :ref:`dotenv file `).
+ In the same way, ``SYMFONY_MAX_PHPUNIT_VERSION`` will set the maximum version
+ of PHPUnit to be considered. This is useful when testing a framework that does
+ not support the latest version(s) of PHPUnit.
+
.. tip::
If you still need to use ``prophecy`` (but not ``symfony/yaml``),
@@ -846,6 +955,22 @@ If you have installed the bridge through Composer, you can run it by calling e.g
It's also possible to set this env var in the ``phpunit.xml.dist`` file.
+.. tip::
+
+ It is also possible to require additional packages that will be installed along
+ with the rest of the needed PHPUnit packages using the ``SYMFONY_PHPUNIT_REQUIRE``
+ env variable. This is specially useful for installing PHPUnit plugins without
+ having to add them to your main ``composer.json`` file. The required packages
+ need to be separated with a space.
+
+ .. code-block:: xml
+
+
+
+
+
+
+
Code Coverage Listener
----------------------
@@ -858,7 +983,7 @@ Consider the following example::
class Bar
{
- public function barMethod()
+ public function barMethod(): string
{
return 'bar';
}
@@ -866,14 +991,12 @@ Consider the following example::
class Foo
{
- private $bar;
-
- public function __construct(Bar $bar)
- {
- $this->bar = $bar;
+ public function __construct(
+ private Bar $bar,
+ ) {
}
- public function fooMethod()
+ public function fooMethod(): string
{
$this->bar->barMethod();
@@ -883,7 +1006,7 @@ Consider the following example::
class FooTest extends PHPUnit\Framework\TestCase
{
- public function test()
+ public function test(): void
{
$bar = new Bar();
$foo = new Foo($bar);
@@ -909,7 +1032,7 @@ Add the following configuration to the ``phpunit.xml.dist`` file:
.. code-block:: xml
-
+
@@ -935,7 +1058,7 @@ your application, you can use your own SUT (System Under Test) solver:
The ``My\Namespace\SutSolver::solve`` can be any PHP callable and receives the
-current test classname as its first argument.
+current test as its first argument.
Finally, the listener can also display warning messages when the SUT solver does
not find the SUT:
@@ -952,14 +1075,13 @@ not find the SUT:
.. _`PHPUnit`: https://phpunit.de
-.. _`PHPUnit event listener`: https://phpunit.de/manual/current/en/extending-phpunit.html#extending-phpunit.PHPUnit_Framework_TestListener
-.. _`PHPUnit's assertStringMatchesFormat()`: https://phpunit.de/manual/current/en/appendixes.assertions.html#appendixes.assertions.assertStringMatchesFormat
-.. _`PHP error handler`: https://php.net/manual/en/book.errorfunc.php
-.. _`environment variable`: https://phpunit.de/manual/current/en/appendixes.configuration.html#appendixes.configuration.php-ini-constants-variables
-.. _`@-silencing operator`: https://php.net/manual/en/language.operators.errorcontrol.php
-.. _`@-silenced`: https://php.net/manual/en/language.operators.errorcontrol.php
+.. _`PHPUnit event listener`: https://docs.phpunit.de/en/10.0/extending-phpunit.html#phpunit-s-event-system
+.. _`ErrorHandler component`: https://github.com/symfony/error-handler
+.. _`PHPUnit's assertStringMatchesFormat()`: https://docs.phpunit.de/en/9.6/assertions.html#assertstringmatchesformat
+.. _`PHP error handler`: https://www.php.net/manual/en/book.errorfunc.php
+.. _`environment variable`: https://docs.phpunit.de/en/9.6/configuration.html#the-env-element
+.. _`@-silencing operator`: https://www.php.net/manual/en/language.operators.errorcontrol.php
.. _`Travis CI`: https://travis-ci.org/
-.. _`test listener`: https://phpunit.de/manual/current/en/appendixes.configuration.html#appendixes.configuration.test-listeners
-.. _`@covers`: https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.covers
-.. _`PHP namespace resolutions rules`: https://php.net/manual/en/language.namespaces.rules.php
-.. _Debug component: https://github.com/symfony/debug
+.. _`test listener`: https://docs.phpunit.de/en/9.6/configuration.html#the-extensions-element
+.. _`@covers`: https://docs.phpunit.de/en/9.6/annotations.html#covers
+.. _`PHP namespace resolutions rules`: https://www.php.net/manual/en/language.namespaces.rules.php
diff --git a/components/polyfill_apcu.rst b/components/polyfill_apcu.rst
deleted file mode 100644
index 80f7aeef809..00000000000
--- a/components/polyfill_apcu.rst
+++ /dev/null
@@ -1,50 +0,0 @@
-.. index::
- single: Polyfill
- single: APC
- single: Components; Polyfill
-
-The Symfony Polyfill / APCu Component
-=====================================
-
- This component provides ``apcu_*`` functions and the ``APCUIterator`` class
- to users of the legacy APC extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-apcu
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-classes and functions, no matter if the `PHP APCu extension`_ is installed or
-not in your server. The only requirement is to have installed at least the
-`legacy APC extension`_.
-
-Provided Classes
-~~~~~~~~~~~~~~~~
-
-* :phpclass:`APCUIterator`
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`apcu_add`
-* :phpfunction:`apcu_delete`
-* :phpfunction:`apcu_exists`
-* :phpfunction:`apcu_fetch`
-* :phpfunction:`apcu_store`
-* :phpfunction:`apcu_cache_info`
-* :phpfunction:`apcu_cas`
-* :phpfunction:`apcu_clear_cache`
-* :phpfunction:`apcu_dec`
-* :phpfunction:`apcu_inc`
-* :phpfunction:`apcu_sma_info`
-
-.. _`PHP APCu extension`: https://secure.php.net/manual/en/book.apcu.php
-.. _`legacy APC extension`: https://secure.php.net/manual/en/book.apc.php
diff --git a/components/polyfill_ctype.rst b/components/polyfill_ctype.rst
deleted file mode 100644
index f685a8563a2..00000000000
--- a/components/polyfill_ctype.rst
+++ /dev/null
@@ -1,43 +0,0 @@
-.. index::
- single: Polyfill
- single: Ctype
- single: Components; Polyfill
-
-The Symfony Polyfill / Ctype Component
-======================================
-
- This component provides ``ctype_*`` functions to users who run PHP versions
- without the ctype extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-ctype
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-functions, no matter if the `PHP Ctype extension`_ is installed or not in your
-server.
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`ctype_alnum`
-* :phpfunction:`ctype_alpha`
-* :phpfunction:`ctype_cntrl`
-* :phpfunction:`ctype_digit`
-* :phpfunction:`ctype_graph`
-* :phpfunction:`ctype_lower`
-* :phpfunction:`ctype_print`
-* :phpfunction:`ctype_punct`
-* :phpfunction:`ctype_space`
-* :phpfunction:`ctype_upper`
-* :phpfunction:`ctype_xdigit`
-
-.. _`PHP Ctype extension`: https://secure.php.net/manual/en/book.ctype.php
diff --git a/components/polyfill_iconv.rst b/components/polyfill_iconv.rst
deleted file mode 100644
index e50b926e6bd..00000000000
--- a/components/polyfill_iconv.rst
+++ /dev/null
@@ -1,57 +0,0 @@
-.. index::
- single: Polyfill
- single: Iconv
- single: Components; Polyfill
-
-The Symfony Polyfill / Iconv Component
-======================================
-
- This component provides a native PHP implementation of the ``iconv_*``
- functions to users who run PHP versions without the ``iconv`` extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-iconv
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-constants and functions, no matter if the `PHP iconv extension`_ is installed or
-not in your server. The only function not implemented in this component is
-:phpfunction:`ob_iconv_handler`.
-
-Provided Constants
-~~~~~~~~~~~~~~~~~~
-
-* ``ICONV_IMPL`` (value = ``'Symfony'``)
-* ``ICONV_VERSION`` (value = ``'1.0'``)
-* ``ICONV_MIME_DECODE_STRICT`` (value = ``1``)
-* ``ICONV_MIME_DECODE_CONTINUE_ON_ERROR`` (value = ``2``)
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-These functions are always available:
-
-* :phpfunction:`iconv`
-* :phpfunction:`iconv_get_encoding`
-* :phpfunction:`iconv_set_encoding`
-* :phpfunction:`iconv_mime_encode`
-* :phpfunction:`iconv_mime_decode_headers`
-
-These functions are only available when the ``mbstring`` or the ``xml``
-extension are installed:
-
-* :phpfunction:`iconv_strlen`
-* :phpfunction:`iconv_strpos`
-* :phpfunction:`iconv_strrpos`
-* :phpfunction:`iconv_substr`
-* :phpfunction:`iconv_mime_decode`
-
-.. _`PHP iconv extension`: https://secure.php.net/manual/en/book.iconv.php
diff --git a/components/polyfill_intl_grapheme.rst b/components/polyfill_intl_grapheme.rst
deleted file mode 100644
index cb5b020c59b..00000000000
--- a/components/polyfill_intl_grapheme.rst
+++ /dev/null
@@ -1,58 +0,0 @@
-.. index::
- single: Polyfill
- single: Intl
- single: Components; Polyfill
-
-The Symfony Polyfill / Intl Grapheme Component
-==============================================
-
- This component provides a partial, native PHP implementation of the
- ``grapheme_*`` functions to users who run PHP versions without the ``intl``
- extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-intl-grapheme
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-constants and functions, no matter if the `PHP intl extension`_ is installed or
-not in your server.
-
-Provided Constants
-~~~~~~~~~~~~~~~~~~
-
-* ``GRAPHEME_EXTR_COUNT`` (value = ``0``)
-* ``GRAPHEME_EXTR_MAXBYTES`` (value = ``1``)
-* ``GRAPHEME_EXTR_MAXCHARS`` (value = ``2``)
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`grapheme_extract`
-* :phpfunction:`grapheme_stripos`
-* :phpfunction:`grapheme_stristr`
-* :phpfunction:`grapheme_strlen`
-* :phpfunction:`grapheme_strpos`
-* :phpfunction:`grapheme_strripos`
-* :phpfunction:`grapheme_strrpos`
-* :phpfunction:`grapheme_strstr`
-* :phpfunction:`grapheme_substr`
-
-.. seealso::
-
- Symfony provides more polyfills for other classes and functions related to
- the Intl PHP extension:
- :doc:`polyfill-intl-icu `,
- :doc:`polyfill-intl-idn `,
- :doc:`polyfill-intl-messageformatter `,
- and :doc:`polyfill-intl-normalizer `.
-
-.. _`PHP intl extension`: https://secure.php.net/manual/en/book.intl.php
diff --git a/components/polyfill_intl_icu.rst b/components/polyfill_intl_icu.rst
deleted file mode 100644
index a00fb7ed35c..00000000000
--- a/components/polyfill_intl_icu.rst
+++ /dev/null
@@ -1,54 +0,0 @@
-.. index::
- single: Polyfill
- single: ICU
- single: Components; Polyfill
-
-The Symfony Polyfill / Intl ICU Component
-=========================================
-
- This component provides a native PHP implementation of several Intl
- functions and classes to users who run PHP versions without the ``intl``
- extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-intl-icu
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-classes and functions, no matter if the `PHP intl extension`_ is installed or
-not in your server.
-
-Provided Classes
-~~~~~~~~~~~~~~~~
-
-* :phpclass:`Collator`
-* :phpclass:`IntlDateFormatter`
-* :phpclass:`Locale`
-* :phpclass:`NumberFormatter`
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`intl_error_name`
-* :phpfunction:`intl_get_error_code`
-* :phpfunction:`intl_get_error_message`
-* :phpfunction:`intl_is_failure`
-
-.. seealso::
-
- Symfony provides more polyfills for other classes and functions related to
- the Intl PHP extension:
- :doc:`polyfill-intl-grapheme `,
- :doc:`polyfill-intl-idn `,
- :doc:`polyfill-intl-messageformatter `,
- and :doc:`polyfill-intl-normalizer `.
-
-.. _`PHP intl extension`: https://secure.php.net/manual/en/book.intl.php
diff --git a/components/polyfill_intl_idn.rst b/components/polyfill_intl_idn.rst
deleted file mode 100644
index 9314f0af35b..00000000000
--- a/components/polyfill_intl_idn.rst
+++ /dev/null
@@ -1,43 +0,0 @@
-.. index::
- single: Polyfill
- single: IDN
- single: Components; Polyfill
-
-The Symfony Polyfill / Intl IDN Component
-=========================================
-
- This component provides a collection of functions related to IDN when the
- Intl extension is not installed.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-intl-idn
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-functions, no matter if the `PHP intl extension`_ is installed or not in your
-server.
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`idn_to_ascii`
-* :phpfunction:`idn_to_utf8`
-
-.. seealso::
-
- Symfony provides more polyfills for other classes and functions related to
- the Intl PHP extension:
- :doc:`polyfill-intl-grapheme `,
- :doc:`polyfill-intl-icu `,
- :doc:`polyfill-intl-messageformatter `,
- and :doc:`polyfill-intl-normalizer `.
-
-.. _`PHP intl extension`: https://secure.php.net/manual/en/book.intl.php
diff --git a/components/polyfill_intl_messageformatter.rst b/components/polyfill_intl_messageformatter.rst
deleted file mode 100644
index b07533d1e16..00000000000
--- a/components/polyfill_intl_messageformatter.rst
+++ /dev/null
@@ -1,48 +0,0 @@
-.. index::
- single: Polyfill
- single: MessageFormatter
- single: Components; Polyfill
-
-The Symfony Polyfill / Intl MessageFormatter Component
-======================================================
-
- This component provides a fallback implementation for the ``MessageFormatter``
- class to users who run PHP versions without the ``intl`` extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-intl-messageformatter
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-classes and functions, no matter if the `PHP intl extension`_ is installed or
-not in your server.
-
-Provided Classes
-~~~~~~~~~~~~~~~~
-
-* :phpclass:`IntlException`
-* :phpclass:`MessageFormatter`
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`msgfmt_format_message`
-
-.. seealso::
-
- Symfony provides more polyfills for other classes and functions related to
- the Intl PHP extension:
- :doc:`polyfill-intl-grapheme `,
- :doc:`polyfill-intl-idn `,
- :doc:`polyfill-intl-icu `,
- and :doc:`polyfill-intl-normalizer `.
-
-.. _`PHP intl extension`: https://secure.php.net/manual/en/book.intl.php
diff --git a/components/polyfill_intl_normalizer.rst b/components/polyfill_intl_normalizer.rst
deleted file mode 100644
index a9c4ae01a32..00000000000
--- a/components/polyfill_intl_normalizer.rst
+++ /dev/null
@@ -1,48 +0,0 @@
-.. index::
- single: Polyfill
- single: Normalizer
- single: Components; Polyfill
-
-The Symfony Polyfill / Intl Normalizer Component
-================================================
-
- This component provides a fallback implementation for the ``Normalizer``
- class to users who run PHP versions without the ``intl`` extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-intl-normalizer
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-classes and functions, no matter if the `PHP intl extension`_ is installed or
-not in your server.
-
-Provided Classes
-~~~~~~~~~~~~~~~~
-
-* :phpclass:`Normalizer`
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`normalizer_is_normalized`
-* :phpfunction:`normalizer_normalize`
-
-.. seealso::
-
- Symfony provides more polyfills for other classes and functions related to
- the Intl PHP extension:
- :doc:`polyfill-intl-grapheme `,
- :doc:`polyfill-intl-idn `,
- :doc:`polyfill-intl-icu `,
- and :doc:`polyfill-intl-messageformatter `.
-
-.. _`PHP intl extension`: https://secure.php.net/manual/en/book.intl.php
diff --git a/components/polyfill_mbstring.rst b/components/polyfill_mbstring.rst
deleted file mode 100644
index 322f1e338fc..00000000000
--- a/components/polyfill_mbstring.rst
+++ /dev/null
@@ -1,76 +0,0 @@
-.. index::
- single: Polyfill
- single: Mbstring
- single: Components; Polyfill
-
-The Symfony Polyfill / Mbstring Component
-=========================================
-
- This component provides a partial, native PHP implementation for the
- ``mbstring`` PHP extension.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-mbstring
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-constants and functions, no matter if the `PHP mbstring extension`_ is installed
-or not in your server.
-
-Provided Constants
-~~~~~~~~~~~~~~~~~~
-
-* ``MB_CASE_UPPER`` (value = ``0``)
-* ``MB_CASE_LOWER`` (value = ``1``)
-* ``MB_CASE_TITLE`` (value = ``2``)
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`mb_check_encoding`
-* :phpfunction:`mb_chr`
-* :phpfunction:`mb_convert_case`
-* :phpfunction:`mb_convert_encoding`
-* :phpfunction:`mb_convert_variables`
-* :phpfunction:`mb_decode_mimeheader`
-* :phpfunction:`mb_decode_numericentity`
-* :phpfunction:`mb_detect_encoding`
-* :phpfunction:`mb_detect_order`
-* :phpfunction:`mb_encode_mimeheader`
-* :phpfunction:`mb_encode_numericentity`
-* :phpfunction:`mb_encoding_aliases`
-* :phpfunction:`mb_get_info`
-* :phpfunction:`mb_http_input`
-* :phpfunction:`mb_http_output`
-* :phpfunction:`mb_internal_encoding`
-* :phpfunction:`mb_language`
-* :phpfunction:`mb_list_encodings`
-* :phpfunction:`mb_ord`
-* :phpfunction:`mb_output_handler`
-* :phpfunction:`mb_parse_str`
-* :phpfunction:`mb_scrub`
-* :phpfunction:`mb_stripos`
-* :phpfunction:`mb_stristr`
-* :phpfunction:`mb_strlen`
-* :phpfunction:`mb_strpos`
-* :phpfunction:`mb_strrchr`
-* :phpfunction:`mb_strrichr`
-* :phpfunction:`mb_strripos`
-* :phpfunction:`mb_strrpos`
-* :phpfunction:`mb_strstr`
-* :phpfunction:`mb_strtolower`
-* :phpfunction:`mb_strtoupper`
-* :phpfunction:`mb_strwidth`
-* :phpfunction:`mb_substitute_character`
-* :phpfunction:`mb_substr_count`
-* :phpfunction:`mb_substr`
-
-.. _`PHP mbstring extension`: https://secure.php.net/manual/en/book.mbstring.php
diff --git a/components/polyfill_php54.rst b/components/polyfill_php54.rst
deleted file mode 100644
index 7c2019a0dba..00000000000
--- a/components/polyfill_php54.rst
+++ /dev/null
@@ -1,33 +0,0 @@
-.. index::
- single: Polyfill
- single: PHP
- single: Components; Polyfill
-
-The Symfony Polyfill / PHP 5.4 Component
-========================================
-
- This component provides some PHP 5.4 features to applications using earlier
- PHP versions.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-php54
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-functions, no matter if your PHP version is earlier than PHP 5.4.
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`class_uses`
-* :phpfunction:`hex2bin`
-* :phpfunction:`session_register_shutdown`
-* :phpfunction:`trait_exists`
diff --git a/components/polyfill_php55.rst b/components/polyfill_php55.rst
deleted file mode 100644
index 99650499763..00000000000
--- a/components/polyfill_php55.rst
+++ /dev/null
@@ -1,37 +0,0 @@
-.. index::
- single: Polyfill
- single: PHP
- single: Components; Polyfill
-
-The Symfony Polyfill / PHP 5.5 Component
-========================================
-
- This component provides some PHP 5.5 features to applications using earlier
- PHP versions.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-php55
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-functions, no matter if your PHP version is earlier than PHP 5.5.
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`array_column`
-* :phpfunction:`boolval`
-* :phpfunction:`hash_pbkdf2`
-* :phpfunction:`json_last_error_msg`
-* :phpfunction:`password_get_info`
-* :phpfunction:`password_hash`
-* :phpfunction:`password_needs_rehash`
-* :phpfunction:`password_verify`
diff --git a/components/polyfill_php56.rst b/components/polyfill_php56.rst
deleted file mode 100644
index c68e8d46fd8..00000000000
--- a/components/polyfill_php56.rst
+++ /dev/null
@@ -1,37 +0,0 @@
-.. index::
- single: Polyfill
- single: PHP
- single: Components; Polyfill
-
-The Symfony Polyfill / PHP 5.6 Component
-========================================
-
- This component provides some PHP 5.6 features to applications using earlier
- PHP versions.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-php56
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-constants and functions, no matter if your PHP version is earlier than PHP 5.6.
-
-Provided Constants
-~~~~~~~~~~~~~~~~~~
-
-* ``LDAP_ESCAPE_FILTER`` (value = ``1``)
-* ``LDAP_ESCAPE_DN`` (value = ``2``)
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`hash_equals`
-* :phpfunction:`ldap_escape`
diff --git a/components/polyfill_php70.rst b/components/polyfill_php70.rst
deleted file mode 100644
index 2169173faf0..00000000000
--- a/components/polyfill_php70.rst
+++ /dev/null
@@ -1,51 +0,0 @@
-.. index::
- single: Polyfill
- single: PHP
- single: Components; Polyfill
-
-The Symfony Polyfill / PHP 7.0 Component
-========================================
-
- This component provides some PHP 7.0 features to applications using earlier
- PHP versions.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-php70
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-constants, classes and functions, no matter if your PHP version is earlier than
-PHP 7.0.
-
-Provided Constants
-~~~~~~~~~~~~~~~~~~
-
-* ``PHP_INT_MIN`` (value = ``~PHP_INT_MAX``)
-
-Provided Classes
-~~~~~~~~~~~~~~~~
-
-* :phpclass:`ArithmeticError`
-* :phpclass:`AssertionError`
-* :phpclass:`DivisionByZeroError`
-* :phpclass:`Error`
-* :phpclass:`ParseError`
-* :phpclass:`SessionUpdateTimestampHandlerInterface`
-* :phpclass:`TypeError`
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`error_clear_last`
-* :phpfunction:`intdiv`
-* :phpfunction:`preg_replace_callback_array`
-* :phpfunction:`random_bytes`
-* :phpfunction:`random_int`
diff --git a/components/polyfill_php71.rst b/components/polyfill_php71.rst
deleted file mode 100644
index 1cec61b4fa6..00000000000
--- a/components/polyfill_php71.rst
+++ /dev/null
@@ -1,30 +0,0 @@
-.. index::
- single: Polyfill
- single: PHP
- single: Components; Polyfill
-
-The Symfony Polyfill / PHP 7.1 Component
-========================================
-
- This component provides some PHP 7.1 features to applications using earlier
- PHP versions.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-php71
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-functions, no matter if your PHP version is earlier than PHP 7.1.
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`is_iterable`
diff --git a/components/polyfill_php72.rst b/components/polyfill_php72.rst
deleted file mode 100644
index 1a0d0bf87ca..00000000000
--- a/components/polyfill_php72.rst
+++ /dev/null
@@ -1,39 +0,0 @@
-.. index::
- single: Polyfill
- single: PHP
- single: Components; Polyfill
-
-The Symfony Polyfill / PHP 7.2 Component
-========================================
-
- This component provides some PHP 7.2 features to applications using earlier
- PHP versions.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-php72
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-constants and functions, no matter if your PHP version is earlier than PHP 7.2.
-
-Provided Constants
-~~~~~~~~~~~~~~~~~~
-
-* ``PHP_OS_FAMILY`` (value = depends on your operating system)
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`sapi_windows_vt100_support` (only on Windows systems)
-* :phpfunction:`spl_object_id`
-* :phpfunction:`stream_isatty`
-* :phpfunction:`utf8_decode`
-* :phpfunction:`utf8_encode`
diff --git a/components/polyfill_php73.rst b/components/polyfill_php73.rst
deleted file mode 100644
index be04e57cb63..00000000000
--- a/components/polyfill_php73.rst
+++ /dev/null
@@ -1,33 +0,0 @@
-.. index::
- single: Polyfill
- single: PHP
- single: Components; Polyfill
-
-The Symfony Polyfill / PHP 7.3 Component
-========================================
-
- This component provides some PHP 7.3 features to applications using earlier
- PHP versions.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/polyfill-php73
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-Once this component is installed in your application, you can use the following
-functions, no matter if your PHP version is earlier than PHP 7.3.
-
-Provided Functions
-~~~~~~~~~~~~~~~~~~
-
-* :phpfunction:`is_countable`
-* :phpfunction:`hrtime`
-* :phpfunction:`array_key_first`
-* :phpfunction:`array_key_last`
diff --git a/components/process.rst b/components/process.rst
index e3abf3c35a9..7552537e82e 100644
--- a/components/process.rst
+++ b/components/process.rst
@@ -1,7 +1,3 @@
-.. index::
- single: Process
- single: Components; Process
-
The Process Component
=====================
@@ -14,7 +10,6 @@ Installation
$ composer require symfony/process
-
.. include:: /components/require_autoload.rst.inc
Usage
@@ -102,12 +97,31 @@ with a non-zero code)::
:method:`Symfony\\Component\\Process\\Process::getLastOutputTime` method.
This method returns ``null`` if the process wasn't started!
+Configuring Process Options
+---------------------------
+
+Symfony uses the PHP :phpfunction:`proc_open` function to run the processes.
+You can configure the options passed to the ``other_options`` argument of
+``proc_open()`` using the ``setOptions()`` method::
+
+ $process = new Process(['...', '...', '...']);
+ // this option allows a subprocess to continue running after the main script exited
+ $process->setOptions(['create_new_console' => true]);
+
+.. warning::
+
+ Most of the options defined by ``proc_open()`` (such as ``create_new_console``
+ and ``suppress_errors``) are only supported on Windows operating systems.
+ Check out the `PHP documentation for proc_open()`_ before using them.
+
+.. _process-using-features-from-the-os-shell:
+
Using Features From the OS Shell
--------------------------------
-Using array of arguments is the recommended way to define commands. This
+Using an array of arguments is the recommended way to define commands. This
saves you from any escaping and allows sending signals seamlessly
-(e.g. to stop processes before completion)::
+(e.g. to stop processes while they run)::
$process = new Process(['/path/command', '--option', 'argument', 'etc.']);
$process = new Process(['/path/to/php', '--define', 'memory_limit=1024M', '/path/to/script.php']);
@@ -134,6 +148,17 @@ environment variables using the second argument of the ``run()``,
// On both Unix-like and Windows
$process->run(null, ['MESSAGE' => 'Something to output']);
+If you prefer to create portable commands that are independent from the
+operating system, you can write the above command as follows::
+
+ // works the same on Windows , Linux and macOS
+ $process = Process::fromShellCommandline('echo "${:MESSAGE}"');
+
+Portable commands require using a syntax that is specific to the component: when
+enclosing a variable name into ``"${:`` and ``}"`` exactly, the process object
+will replace it with its escaped value, or will fail if the variable is not
+found in the list of environment variables attached to the command.
+
Setting Environment Variables for Processes
-------------------------------------------
@@ -166,7 +191,7 @@ anonymous function to the
use Symfony\Component\Process\Process;
$process = new Process(['ls', '-lsa']);
- $process->run(function ($type, $buffer) {
+ $process->run(function ($type, $buffer): void {
if (Process::ERR === $type) {
echo 'ERR > '.$buffer;
} else {
@@ -229,7 +254,7 @@ are done doing other stuff::
**synchronously** inside this event. Be aware that ``kernel.terminate``
is called only if you use PHP-FPM.
-.. caution::
+.. danger::
Beware also that if you do that, the said PHP-FPM process will not be
available to serve any new request until the subprocess is finished. This
@@ -244,7 +269,7 @@ in the output and its type::
$process = new Process(['ls', '-lsa']);
$process->start();
- $process->wait(function ($type, $buffer) {
+ $process->wait(function ($type, $buffer): void {
if (Process::ERR === $type) {
echo 'ERR > '.$buffer;
} else {
@@ -263,7 +288,7 @@ process and checks its output to wait until its fully initialized::
// ... do other things
// waits until the given anonymous function returns true
- $process->waitUntil(function ($type, $output) {
+ $process->waitUntil(function ($type, $output): bool {
return $output === 'Ready. Waiting for commands...';
});
@@ -305,7 +330,7 @@ provides the :class:`Symfony\\Component\\Process\\InputStream` class::
echo $process->getOutput();
The :method:`Symfony\\Component\\Process\\InputStream::write` method accepts scalars,
-stream resources or ``Traversable`` objects as argument. As shown in the above example,
+stream resources or ``Traversable`` objects as arguments. As shown in the above example,
you need to explicitly call the :method:`Symfony\\Component\\Process\\InputStream::close`
method when you are done writing to the standard input of the subprocess.
@@ -332,6 +357,35 @@ The input of a process can also be defined using `PHP streams`_::
// will echo: 'foobar'
echo $process->getOutput();
+Using TTY and PTY Modes
+-----------------------
+
+All examples above show that your program has control over the input of a
+process (using ``setInput()``) and the output from that process (using
+``getOutput()``). The Process component has two special modes that tweak
+the relationship between your program and the process: teletype (tty) and
+pseudo-teletype (pty).
+
+In TTY mode, you connect the input and output of the process to the input
+and output of your program. This allows for instance to open an editor like
+Vim or Nano as a process. You enable TTY mode by calling
+:method:`Symfony\\Component\\Process\\Process::setTty`::
+
+ $process = new Process(['vim']);
+ $process->setTty(true);
+ $process->run();
+
+ // As the output is connected to the terminal, it is no longer possible
+ // to read or modify the output from the process!
+ dump($process->getOutput()); // null
+
+In PTY mode, your program behaves as a terminal for the process instead of
+a plain input and output. Some programs behave differently when
+interacting with a real terminal instead of another program. For instance,
+some programs prompt for a password when talking with a terminal. Use
+:method:`Symfony\\Component\\Process\\Process::setPty` to enable this
+mode.
+
Stopping a Process
------------------
@@ -339,7 +393,7 @@ Any asynchronous process can be stopped at any time with the
:method:`Symfony\\Component\\Process\\Process::stop` method. This method takes
two arguments: a timeout and a signal. Once the timeout is reached, the signal
is sent to the running process. The default signal sent to a process is ``SIGKILL``.
-Please read the :ref:`signal documentation below`
+Please read the :ref:`signal documentation below `
to find out more about signal handling in the Process component::
$process = new Process(['ls', '-lsa']);
@@ -363,22 +417,35 @@ instead::
);
$process->run();
-Using a Prepared Command Line
------------------------------
+Executing a PHP Child Process with the Same Configuration
+---------------------------------------------------------
-You can run the process by using a a prepared command line using the
-double bracket notation. You can use a placeholder in order to have a
-process that can only be changed with the values and without changing
-the PHP code::
-
- use Symfony\Component\Process\Process;
+When you start a PHP process, it uses the default configuration defined in
+your ``php.ini`` file. You can bypass these options with the ``-d`` command line
+option. For example, if ``memory_limit`` is set to ``256M``, you can disable this
+memory limit when running some command like this:
+``php -d memory_limit=-1 bin/console app:my-command``.
- $process = Process::fromShellCommandline('echo "$name"');
- $process->run(null, ['name' => 'Elsa']);
+However, if you run the command via the Symfony ``Process`` class, PHP will use
+the settings defined in the ``php.ini`` file. You can solve this issue by using
+the :class:`Symfony\\Component\\Process\\PhpSubprocess` class to run the command::
-.. caution::
+ use Symfony\Component\Process\Process;
- A prepared command line will not be escaped automatically!
+ class MyCommand extends Command
+ {
+ protected function execute(InputInterface $input, OutputInterface $output): int
+ {
+ // the memory_limit (and any other config option) of this command is
+ // the one defined in php.ini instead of the new values (optionally)
+ // passed via the '-d' command option
+ $childProcess = new Process(['bin/console', 'cache:pool:prune']);
+
+ // the memory_limit (and any other config option) of this command takes
+ // into account the values (optionally) passed via the '-d' command option
+ $childProcess = new PhpSubprocess(['bin/console', 'cache:pool:prune']);
+ }
+ }
Process Timeout
---------------
@@ -410,6 +477,10 @@ check regularly::
usleep(200000);
}
+.. tip::
+
+ You can get the process start time using the ``getStartTime()`` method.
+
.. _reference-process-signal:
Process Idle Timeout
@@ -442,6 +513,20 @@ When running a program asynchronously, you can send it POSIX signals with the
// will send a SIGKILL to the process
$process->signal(SIGKILL);
+You can make the process ignore signals by using the
+:method:`Symfony\\Component\\Process\\Process::setIgnoredSignals`
+method. The given signals won't be propagated to the child process::
+
+ use Symfony\Component\Process\Process;
+
+ $process = new Process(['find', '/', '-name', 'rabbit']);
+ $process->setIgnoredSignals([SIGKILL, SIGUSR1]);
+
+.. versionadded:: 7.1
+
+ The :method:`Symfony\\Component\\Process\\Process::setIgnoredSignals`
+ method was introduced in Symfony 7.1.
+
Process Pid
-----------
@@ -469,7 +554,7 @@ Use :method:`Symfony\\Component\\Process\\Process::disableOutput` and
$process->disableOutput();
$process->run();
-.. caution::
+.. warning::
You cannot enable or disable the output while the process is running.
@@ -480,10 +565,31 @@ Use :method:`Symfony\\Component\\Process\\Process::disableOutput` and
However, it is possible to pass a callback to the ``start``, ``run`` or ``mustRun``
methods to handle process output in a streaming fashion.
+Finding an Executable
+---------------------
+
+The Process component provides a utility class called
+:class:`Symfony\\Component\\Process\\ExecutableFinder` which finds
+and returns the absolute path of an executable::
+
+ use Symfony\Component\Process\ExecutableFinder;
+
+ $executableFinder = new ExecutableFinder();
+ $chromedriverPath = $executableFinder->find('chromedriver');
+ // $chromedriverPath = '/usr/local/bin/chromedriver' (the result will be different on your computer)
+
+The :method:`Symfony\\Component\\Process\\ExecutableFinder::find` method also takes extra parameters to specify a default value
+to return and extra directories where to look for the executable::
+
+ use Symfony\Component\Process\ExecutableFinder;
+
+ $executableFinder = new ExecutableFinder();
+ $chromedriverPath = $executableFinder->find('chromedriver', '/path/to/chromedriver', ['local-bin/']);
+
Finding the Executable PHP Binary
---------------------------------
-This component also provides a utility class called
+This component also provides a special utility class called
:class:`Symfony\\Component\\Process\\PhpExecutableFinder` which returns the
absolute path of the executable PHP binary available on your server::
@@ -508,3 +614,4 @@ whether `TTY`_ is supported on the current operating system::
.. _`PHP streams`: https://www.php.net/manual/en/book.stream.php
.. _`output_buffering`: https://www.php.net/manual/en/outcontrol.configuration.php
.. _`TTY`: https://en.wikipedia.org/wiki/Tty_(unix)
+.. _`PHP documentation for proc_open()`: https://www.php.net/manual/en/function.proc-open.php
diff --git a/components/property_access.rst b/components/property_access.rst
index 3dc2cf7e3bd..f608640fa9b 100644
--- a/components/property_access.rst
+++ b/components/property_access.rst
@@ -1,11 +1,7 @@
-.. index::
- single: PropertyAccess
- single: Components; PropertyAccess
-
The PropertyAccess Component
============================
- The PropertyAccess component provides function to read and write from/to an
+ The PropertyAccess component provides functions to read and write from/to an
object or array using a simple string notation.
Installation
@@ -21,7 +17,7 @@ Usage
-----
The entry point of this component is the
-:method:`PropertyAccess::createPropertyAccessor`
+:method:`Symfony\\Component\\PropertyAccess\\PropertyAccess::createPropertyAccessor`
factory. This factory will create a new instance of the
:class:`Symfony\\Component\\PropertyAccess\\PropertyAccessor` class with the
default configuration::
@@ -30,12 +26,14 @@ default configuration::
$propertyAccessor = PropertyAccess::createPropertyAccessor();
+.. _property-access-reading-arrays:
+
Reading from Arrays
-------------------
You can read an array with the
-:method:`PropertyAccessor::getValue`
-method. This is done using the index notation that is used in PHP::
+:method:`Symfony\\Component\\PropertyAccess\\PropertyAccessor::getValue` method.
+This is done using the index notation that is used in PHP::
// ...
$person = [
@@ -63,6 +61,9 @@ method::
// Symfony\Component\PropertyAccess\Exception\NoSuchIndexException
$value = $propertyAccessor->getValue($person, '[age]');
+ // You can avoid the exception by adding the nullsafe operator
+ $value = $propertyAccessor->getValue($person, '[age?]');
+
You can also use multi dimensional arrays::
// ...
@@ -72,12 +73,24 @@ You can also use multi dimensional arrays::
],
[
'first_name' => 'Ryan',
- ]
+ ],
];
var_dump($propertyAccessor->getValue($persons, '[0][first_name]')); // 'Wouter'
var_dump($propertyAccessor->getValue($persons, '[1][first_name]')); // 'Ryan'
+.. tip::
+
+ If the key of the array contains a dot ``.`` or a left square bracket ``[``,
+ you must escape those characters with a backslash. In the above example,
+ if the array key was ``first.name`` instead of ``first_name``, you should
+ access its value as follows::
+
+ var_dump($propertyAccessor->getValue($persons, '[0][first\.name]')); // 'Wouter'
+ var_dump($propertyAccessor->getValue($persons, '[1][first\.name]')); // 'Ryan'
+
+ Right square brackets ``]`` don't need to be escaped in array keys.
+
Reading from Objects
--------------------
@@ -101,7 +114,7 @@ To read from properties, use the "dot" notation::
var_dump($propertyAccessor->getValue($person, 'children[0].firstName')); // 'Bar'
-.. caution::
+.. warning::
Accessing public properties is the last option used by ``PropertyAccessor``.
It tries to access the value using the below methods first before using
@@ -119,9 +132,9 @@ it with ``get``. So the actual method becomes ``getFirstName()``::
// ...
class Person
{
- private $firstName = 'Wouter';
+ private string $firstName = 'Wouter';
- public function getFirstName()
+ public function getFirstName(): string
{
return $this->firstName;
}
@@ -141,15 +154,15 @@ getters, this means that you can do something like this::
// ...
class Person
{
- private $author = true;
- private $children = [];
+ private bool $author = true;
+ private array $children = [];
- public function isAuthor()
+ public function isAuthor(): bool
{
return $this->author;
}
- public function hasChildren()
+ public function hasChildren(): bool
{
return 0 !== count($this->children);
}
@@ -158,19 +171,19 @@ getters, this means that you can do something like this::
$person = new Person();
if ($propertyAccessor->getValue($person, 'author')) {
- var_dump('He is an author');
+ var_dump('This person is an author');
}
if ($propertyAccessor->getValue($person, 'children')) {
- var_dump('He has children');
+ var_dump('This person has children');
}
-This will produce: ``He is an author``
+This will produce: ``This person is an author``
Accessing a non Existing Property Path
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By default a :class:`Symfony\\Component\\PropertyAccess\\Exception\\NoSuchPropertyException`
-is thrown if the property path passed to :method:`PropertyAccessor::getValue`
+is thrown if the property path passed to :method:`Symfony\\Component\\PropertyAccess\\PropertyAccessor::getValue`
does not exist. You can change this behavior using the
:method:`Symfony\\Component\\PropertyAccess\\PropertyAccessorBuilder::disableExceptionOnInvalidPropertyPath`
method::
@@ -178,7 +191,7 @@ method::
// ...
class Person
{
- public $name;
+ public string $name;
}
$person = new Person();
@@ -190,6 +203,37 @@ method::
// instead of throwing an exception the following code returns null
$value = $propertyAccessor->getValue($person, 'birthday');
+Accessing Nullable Property Paths
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Consider the following PHP code::
+
+ class Person
+ {
+ }
+
+ class Comment
+ {
+ public ?Person $person = null;
+ public string $message;
+ }
+
+ $comment = new Comment();
+ $comment->message = 'test';
+
+Given that ``$person`` is nullable, an object graph like ``comment.person.profile``
+will trigger an exception when the ``$person`` property is ``null``. The solution
+is to mark all nullable properties with the nullsafe operator (``?``)::
+
+ // This code throws an exception of type
+ // Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException
+ var_dump($propertyAccessor->getValue($comment, 'person.firstname'));
+
+ // If a property marked with the nullsafe operator is null, the expression is
+ // no longer evaluated and null is returned immediately without throwing an exception
+ var_dump($propertyAccessor->getValue($comment, 'person?.firstname')); // null
+
+.. _components-property-access-magic-get:
Magic ``__get()`` Method
~~~~~~~~~~~~~~~~~~~~~~~~
@@ -199,42 +243,50 @@ The ``getValue()`` method can also use the magic ``__get()`` method::
// ...
class Person
{
- private $children = [
+ private array $children = [
'Wouter' => [...],
];
- public function __get($id)
+ public function __get($id): mixed
{
return $this->children[$id];
}
+
+ public function __isset($id): bool
+ {
+ return isset($this->children[$id]);
+ }
}
$person = new Person();
var_dump($propertyAccessor->getValue($person, 'Wouter')); // [...]
+.. warning::
+
+ When implementing the magic ``__get()`` method, you also need to implement
+ ``__isset()``.
+
.. _components-property-access-magic-call:
Magic ``__call()`` Method
~~~~~~~~~~~~~~~~~~~~~~~~~
-At last, ``getValue()`` can use the magic ``__call()`` method, but you need to
+Lastly, ``getValue()`` can use the magic ``__call()`` method, but you need to
enable this feature by using :class:`Symfony\\Component\\PropertyAccess\\PropertyAccessorBuilder`::
// ...
class Person
{
- private $children = [
+ private array $children = [
'wouter' => [...],
];
- public function __call($name, $args)
+ public function __call($name, $args): mixed
{
$property = lcfirst(substr($name, 3));
if ('get' === substr($name, 0, 3)) {
- return isset($this->children[$property])
- ? $this->children[$property]
- : null;
+ return $this->children[$property] ?? null;
} elseif ('set' === substr($name, 0, 3)) {
$value = 1 == count($args) ? $args[0] : null;
$this->children[$property] = $value;
@@ -251,10 +303,10 @@ enable this feature by using :class:`Symfony\\Component\\PropertyAccess\\Propert
var_dump($propertyAccessor->getValue($person, 'wouter')); // [...]
-.. caution::
+.. warning::
The ``__call()`` feature is disabled by default, you can enable it by calling
- :method:`PropertyAccessorBuilder::enableMagicCall`
+ :method:`Symfony\\Component\\PropertyAccess\\PropertyAccessorBuilder::enableMagicCall`
see `Enable other Features`_.
Writing to Arrays
@@ -262,8 +314,7 @@ Writing to Arrays
The ``PropertyAccessor`` class can do more than just read an array, it can
also write to an array. This can be achieved using the
-:method:`PropertyAccessor::setValue`
-method::
+:method:`Symfony\\Component\\PropertyAccess\\PropertyAccessor::setValue` method::
// ...
$person = [];
@@ -274,6 +325,8 @@ method::
// or
// var_dump($person['first_name']); // 'Wouter'
+.. _components-property-access-writing-to-objects:
+
Writing to Objects
------------------
@@ -283,26 +336,26 @@ can use setters, the magic ``__set()`` method or properties to set values::
// ...
class Person
{
- public $firstName;
- private $lastName;
- private $children = [];
+ public string $firstName;
+ private string $lastName;
+ private array $children = [];
- public function setLastName($name)
+ public function setLastName($name): void
{
$this->lastName = $name;
}
- public function getLastName()
+ public function getLastName(): string
{
return $this->lastName;
}
- public function getChildren()
+ public function getChildren(): array
{
return $this->children;
}
- public function __set($property, $value)
+ public function __set($property, $value): void
{
$this->$property = $value;
}
@@ -324,15 +377,13 @@ see `Enable other Features`_::
// ...
class Person
{
- private $children = [];
+ private array $children = [];
- public function __call($name, $args)
+ public function __call($name, $args): mixed
{
$property = lcfirst(substr($name, 3));
if ('get' === substr($name, 0, 3)) {
- return isset($this->children[$property])
- ? $this->children[$property]
- : null;
+ return $this->children[$property] ?? null;
} elseif ('set' === substr($name, 0, 3)) {
$value = 1 == count($args) ? $args[0] : null;
$this->children[$property] = $value;
@@ -352,6 +403,11 @@ see `Enable other Features`_::
var_dump($person->getWouter()); // [...]
+.. note::
+
+ The ``__set()`` method support is enabled by default.
+ See `Enable other Features`_ if you want to disable it.
+
Writing to Array Properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -364,7 +420,7 @@ properties through *adder* and *remover* methods::
/**
* @var string[]
*/
- private $children = [];
+ private array $children = [];
public function getChildren(): array
{
@@ -390,19 +446,58 @@ properties through *adder* and *remover* methods::
The PropertyAccess component checks for methods called ``add()``
and ``remove()``. Both methods must be defined.
For instance, in the previous example, the component looks for the ``addChild()``
-and ``removeChild()`` methods to access to the ``children`` property.
-`The Inflector component`_ is used to find the singular of a property name.
+and ``removeChild()`` methods to access the ``children`` property.
+`The String component`_ inflector is used to find the singular of a property name.
If available, *adder* and *remover* methods have priority over a *setter* method.
+Using non-standard adder/remover methods
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Sometimes, adder and remover methods don't use the standard ``add`` or ``remove`` prefix, like in this example::
+
+ // ...
+ class Team
+ {
+ // ...
+
+ public function joinTeam(string $person): void
+ {
+ $this->team[] = $person;
+ }
+
+ public function leaveTeam(string $person): void
+ {
+ foreach ($this->team as $id => $item) {
+ if ($person === $item) {
+ unset($this->team[$id]);
+
+ break;
+ }
+ }
+ }
+ }
+
+ use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
+ use Symfony\Component\PropertyAccess\PropertyAccessor;
+
+ $list = new Team();
+ $reflectionExtractor = new ReflectionExtractor(null, null, ['join', 'leave']);
+ $propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH, null, $reflectionExtractor, $reflectionExtractor);
+ $propertyAccessor->setValue($person, 'team', ['kevin', 'wouter']);
+
+ var_dump($person->getTeam()); // ['kevin', 'wouter']
+
+Instead of calling ``add()`` and ``remove()``, the PropertyAccess
+component will call ``join()`` and ``leave()`` methods.
+
Checking Property Paths
-----------------------
When you want to check whether
-:method:`PropertyAccessor::getValue`
-can safely be called without actually calling that method, you can use
-:method:`PropertyAccessor::isReadable`
-instead::
+:method:`Symfony\\Component\\PropertyAccess\\PropertyAccessor::getValue` can
+safely be called without actually calling that method, you can use
+:method:`Symfony\\Component\\PropertyAccess\\PropertyAccessor::isReadable` instead::
$person = new Person();
@@ -410,9 +505,8 @@ instead::
// ...
}
-The same is possible for :method:`PropertyAccessor::setValue`:
-Call the
-:method:`PropertyAccessor::isWritable`
+The same is possible for :method:`Symfony\\Component\\PropertyAccess\\PropertyAccessor::setValue`:
+Call the :method:`Symfony\\Component\\PropertyAccess\\PropertyAccessor::isWritable`
method to find out whether a property path can be updated::
$person = new Person();
@@ -429,15 +523,15 @@ You can also mix objects and arrays::
// ...
class Person
{
- public $firstName;
- private $children = [];
+ public string $firstName;
+ private array $children = [];
- public function setChildren($children)
+ public function setChildren($children): void
{
$this->children = $children;
}
- public function getChildren()
+ public function getChildren(): array
{
return $this->children;
}
@@ -464,14 +558,20 @@ configured to enable extra features. To do that you could use the
// ...
$propertyAccessorBuilder = PropertyAccess::createPropertyAccessorBuilder();
- // enables magic __call
- $propertyAccessorBuilder->enableMagicCall();
+ $propertyAccessorBuilder->enableMagicCall(); // enables magic __call
+ $propertyAccessorBuilder->enableMagicGet(); // enables magic __get
+ $propertyAccessorBuilder->enableMagicSet(); // enables magic __set
+ $propertyAccessorBuilder->enableMagicMethods(); // enables magic __get, __set and __call
- // disables magic __call
- $propertyAccessorBuilder->disableMagicCall();
+ $propertyAccessorBuilder->disableMagicCall(); // disables magic __call
+ $propertyAccessorBuilder->disableMagicGet(); // disables magic __get
+ $propertyAccessorBuilder->disableMagicSet(); // disables magic __set
+ $propertyAccessorBuilder->disableMagicMethods(); // disables magic __get, __set and __call
- // checks if magic __call handling is enabled
+ // checks if magic __call, __get or __set handling are enabled
$propertyAccessorBuilder->isMagicCallEnabled(); // true or false
+ $propertyAccessorBuilder->isMagicGetEnabled(); // true or false
+ $propertyAccessorBuilder->isMagicSetEnabled(); // true or false
// At the end get the configured property accessor
$propertyAccessor = $propertyAccessorBuilder->getPropertyAccessor();
@@ -483,7 +583,7 @@ configured to enable extra features. To do that you could use the
Or you can pass parameters directly to the constructor (not the recommended way)::
- // ...
- $propertyAccessor = new PropertyAccessor(true); // this enables handling of magic __call
+ // enable handling of magic __call, __set but not __get:
+ $propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_CALL | PropertyAccessor::MAGIC_SET);
-.. _The Inflector component: https://github.com/symfony/inflector
+.. _`The String component`: https://github.com/symfony/string
diff --git a/components/property_info.rst b/components/property_info.rst
index 744b22553e3..865a36c5941 100644
--- a/components/property_info.rst
+++ b/components/property_info.rst
@@ -1,7 +1,3 @@
-.. index::
- single: PropertyInfo
- single: Components; PropertyInfo
-
The PropertyInfo Component
==========================
@@ -120,11 +116,12 @@ Extractable Information
The :class:`Symfony\\Component\\PropertyInfo\\PropertyInfoExtractor`
class exposes public methods to extract several types of information:
-* :ref:`List of properties `: :method:`Symfony\\Component\\PropertyInfo\\PropertyListExtractorInterface::getProperties()`
-* :ref:`Property type `: :method:`Symfony\\Component\\PropertyInfo\\PropertyTypeExtractorInterface::getTypes()`
-* :ref:`Property description `: :method:`Symfony\\Component\\PropertyInfo\\PropertyDescriptionExtractorInterface::getShortDescription()` and :method:`Symfony\\Component\\PropertyInfo\\PropertyDescriptionExtractorInterface::getLongDescription()`
-* :ref:`Property access details `: :method:`Symfony\\Component\\PropertyInfo\\PropertyAccessExtractorInterface::isReadable()` and :method:`Symfony\\Component\\PropertyInfo\\PropertyAccessExtractorInterface::isWritable()`
-* :ref:`Property initializable through the constructor `: :method:`Symfony\\Component\\PropertyInfo\\PropertyInitializableExtractorInterface::isInitializable()`
+* :ref:`List of properties `: :method:`Symfony\\Component\\PropertyInfo\\PropertyListExtractorInterface::getProperties`
+* :ref:`Property type `: :method:`Symfony\\Component\\PropertyInfo\\PropertyTypeExtractorInterface::getTypes`
+ (including typed properties)
+* :ref:`Property description `: :method:`Symfony\\Component\\PropertyInfo\\PropertyDescriptionExtractorInterface::getShortDescription` and :method:`Symfony\\Component\\PropertyInfo\\PropertyDescriptionExtractorInterface::getLongDescription`
+* :ref:`Property access details `: :method:`Symfony\\Component\\PropertyInfo\\PropertyAccessExtractorInterface::isReadable` and :method:`Symfony\\Component\\PropertyInfo\\PropertyAccessExtractorInterface::isWritable`
+* :ref:`Property initializable through the constructor `: :method:`Symfony\\Component\\PropertyInfo\\PropertyInitializableExtractorInterface::isInitializable`
.. note::
@@ -134,7 +131,7 @@ class exposes public methods to extract several types of information:
$propertyInfo->getProperties($awesomeObject);
// Good!
- $propertyInfo->getProperties(get_class($awesomeObject));
+ $propertyInfo->getProperties($awesomeObject::class);
$propertyInfo->getProperties('Example\Namespace\YourAwesomeClass');
$propertyInfo->getProperties(YourAwesomeClass::class);
@@ -186,6 +183,26 @@ for a property::
See :ref:`components-property-info-type` for info about the ``Type`` class.
+Documentation Block
+~~~~~~~~~~~~~~~~~~~
+
+Extractors that implement :class:`Symfony\\Component\\PropertyInfo\\PropertyDocBlockExtractorInterface`
+can provide the full documentation block for a property as a string::
+
+ $docBlock = $propertyInfo->getDocBlock($class, $property);
+ /*
+ Example Result
+ --------------
+ string(79):
+ This is the subsequent paragraph in the DocComment.
+ It can span multiple lines.
+ */
+
+.. versionadded:: 7.1
+
+ The :class:`Symfony\\Component\\PropertyInfo\\PropertyDocBlockExtractorInterface`
+ interface was introduced in Symfony 7.1.
+
.. _property-info-description:
Description Information
@@ -207,7 +224,7 @@ strings::
Example Result
--------------
string(79):
- These is the subsequent paragraph in the DocComment.
+ This is the subsequent paragraph in the DocComment.
It can span multiple lines.
*/
@@ -228,7 +245,9 @@ provide whether properties are readable or writable as booleans::
The :class:`Symfony\\Component\\PropertyInfo\\Extractor\\ReflectionExtractor` looks
for getter/isser/setter/hasser method in addition to whether or not a property is public
to determine if it's accessible. This based on how the :doc:`PropertyAccess `
-works.
+works. It assumes camel case style method names following `PSR-1`_. For example,
+both ``myProperty`` and ``my_property`` properties are readable if there's a
+``getMyProperty()`` method and writable if there's a ``setMyProperty()`` method.
.. _property-info-initializable:
@@ -322,15 +341,20 @@ this returns ``true`` if:
``@var SomeClass``, ``@var SomeClass``,
``@var Doctrine\Common\Collections\Collection``, etc.)
-``Type::getCollectionKeyType()`` & ``Type::getCollectionValueType()``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+``Type::getCollectionKeyTypes()`` & ``Type::getCollectionValueTypes()``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the property is a collection, additional type objects may be returned
for both the key and value types of the collection (if the information is
-available), via the :method:`Type::getCollectionKeyType() `
-and :method:`Type::getCollectionValueType() `
+available), via the :method:`Type::getCollectionKeyTypes() `
+and :method:`Type::getCollectionValueTypes() `
methods.
+.. note::
+
+ The ``list`` pseudo type is returned by the PropertyInfo component as an
+ array with integer as the key type.
+
.. _`components-property-info-extractors`:
Extractors
@@ -356,7 +380,7 @@ Using PHP reflection, the :class:`Symfony\\Component\\PropertyInfo\\Extractor\\R
provides list, type and access information from setter and accessor methods.
It can also give the type of a property (even extracting it from the constructor
arguments), and if it is initializable through the constructor. It supports
-return and scalar types for PHP 7::
+return and scalar types::
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
@@ -409,6 +433,54 @@ library is present::
// Description information.
$phpDocExtractor->getShortDescription($class, $property);
$phpDocExtractor->getLongDescription($class, $property);
+ $phpDocExtractor->getDocBlock($class, $property);
+
+.. versionadded:: 7.1
+
+ The :method:`Symfony\\Component\\PropertyInfo\\Extractor\\PhpDocExtractor::getDocBlock`
+ method was introduced in Symfony 7.1.
+
+PhpStanExtractor
+~~~~~~~~~~~~~~~~
+
+.. note::
+
+ This extractor depends on the `phpstan/phpdoc-parser`_ and
+ `phpdocumentor/reflection-docblock`_ libraries.
+
+This extractor fetches information thanks to the PHPStan parser. It gathers
+information from annotations of properties and methods, such as ``@var``,
+``@param`` or ``@return``::
+
+ // src/Domain/Foo.php
+ class Foo
+ {
+ /**
+ * @param string $bar
+ */
+ public function __construct(
+ private string $bar,
+ ) {
+ }
+ }
+
+ // Extraction.php
+ use Symfony\Component\PropertyInfo\Extractor\PhpStanExtractor;
+ use App\Domain\Foo;
+
+ $phpStanExtractor = new PhpStanExtractor();
+
+ // Type information.
+ $phpStanExtractor->getTypesFromConstructor(Foo::class, 'bar');
+ // Description information.
+ $phpStanExtractor->getShortDescription($class, 'bar');
+ $phpStanExtractor->getLongDescription($class, 'bar');
+
+.. versionadded:: 7.3
+
+ The :method:`Symfony\\Component\\PropertyInfo\\Extractor\\PhpStanExtractor::getShortDescription`
+ and :method:`Symfony\\Component\\PropertyInfo\\Extractor\\PhpStanExtractor::getLongDescription`
+ methods were introduced in Symfony 7.3.
SerializerExtractor
~~~~~~~~~~~~~~~~~~~
@@ -417,24 +489,25 @@ SerializerExtractor
This extractor depends on the `symfony/serializer`_ library.
-Using :ref:`groups metadata `
-from the :doc:`Serializer component `,
-the :class:`Symfony\\Component\\PropertyInfo\\Extractor\\SerializerExtractor`
+Using :ref:`groups metadata ` from the
+:doc:`Serializer component `, the
+:class:`Symfony\\Component\\PropertyInfo\\Extractor\\SerializerExtractor`
provides list information. This extractor is *not* registered automatically
with the ``property_info`` service in the Symfony Framework::
- use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\PropertyInfo\Extractor\SerializerExtractor;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
- use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
+ use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
- $serializerClassMetadataFactory = new ClassMetadataFactory(
- new AnnotationLoader(new AnnotationReader)
- );
+ $serializerClassMetadataFactory = new ClassMetadataFactory(new AttributeLoader());
$serializerExtractor = new SerializerExtractor($serializerClassMetadataFactory);
- // List information.
- $serializerExtractor->getProperties($class);
+ // the `serializer_groups` option must be configured (may be set to null)
+ $serializerExtractor->getProperties($class, ['serializer_groups' => ['mygroup']]);
+
+If ``serializer_groups`` is set to ``null``, serializer groups metadata won't be
+checked but you will get only the properties considered by the Serializer
+Component (notably the ``#[Ignore]`` attribute is taken into account).
DoctrineExtractor
~~~~~~~~~~~~~~~~~
@@ -465,6 +538,33 @@ with the ``property_info`` service in the Symfony Framework::
// Type information.
$doctrineExtractor->getTypes($class, $property);
+.. _components-property-information-constructor-extractor:
+
+ConstructorExtractor
+~~~~~~~~~~~~~~~~~~~~
+
+The :class:`Symfony\\Component\\PropertyInfo\\Extractor\\ConstructorExtractor`
+tries to extract properties information by using either the
+:class:`Symfony\\Component\\PropertyInfo\\Extractor\\PhpStanExtractor` or
+the :class:`Symfony\\Component\\PropertyInfo\\Extractor\\ReflectionExtractor`
+on the constructor arguments::
+
+ // src/Domain/Foo.php
+ class Foo
+ {
+ public function __construct(
+ private string $bar,
+ ) {
+ }
+ }
+
+ // Extraction.php
+ use App\Domain\Foo;
+ use Symfony\Component\PropertyInfo\Extractor\ConstructorExtractor;
+
+ $constructorExtractor = new ConstructorExtractor([new ReflectionExtractor()]);
+ $constructorExtractor->getTypes(Foo::class, 'bar')[0]->getBuiltinType(); // returns 'string'
+
.. _`components-property-information-extractors-creation`:
Creating Your Own Extractors
@@ -472,6 +572,7 @@ Creating Your Own Extractors
You can create your own property information extractors by creating a
class that implements one or more of the following interfaces:
+:class:`Symfony\\Component\\PropertyInfo\\Extractor\\ConstructorArgumentTypeExtractorInterface`,
:class:`Symfony\\Component\\PropertyInfo\\PropertyAccessExtractorInterface`,
:class:`Symfony\\Component\\PropertyInfo\\PropertyDescriptionExtractorInterface`,
:class:`Symfony\\Component\\PropertyInfo\\PropertyListExtractorInterface`,
@@ -487,9 +588,18 @@ service by defining it as a service with one or more of the following
* ``property_info.type_extractor`` if it provides type information.
* ``property_info.description_extractor`` if it provides description information.
* ``property_info.access_extractor`` if it provides access information.
+* ``property_info.initializable_extractor`` if it provides initializable information
+ (it checks if a property can be initialized through the constructor).
+* ``property_info.constructor_extractor`` if it provides type information from the constructor argument.
+
+ .. versionadded:: 7.3
+
+ The ``property_info.constructor_extractor`` tag was introduced in Symfony 7.3.
+.. _`PSR-1`: https://www.php-fig.org/psr/psr-1/
.. _`phpDocumentor Reflection`: https://github.com/phpDocumentor/ReflectionDocBlock
.. _`phpdocumentor/reflection-docblock`: https://packagist.org/packages/phpdocumentor/reflection-docblock
+.. _`phpstan/phpdoc-parser`: https://packagist.org/packages/phpstan/phpdoc-parser
.. _`Doctrine ORM`: https://www.doctrine-project.org/projects/orm.html
.. _`symfony/serializer`: https://packagist.org/packages/symfony/serializer
.. _`symfony/doctrine-bridge`: https://packagist.org/packages/symfony/doctrine-bridge
diff --git a/components/psr7.rst b/components/psr7.rst
index 2df3c6fc3af..04a3b9148b5 100644
--- a/components/psr7.rst
+++ b/components/psr7.rst
@@ -1,6 +1,3 @@
-.. index::
- single: PSR-7
-
The PSR-7 Bridge
================
@@ -33,8 +30,8 @@ Converting from HttpFoundation Objects to PSR-7
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The bridge provides an interface of a factory called
-:class:`Symfony\\Bridge\\PsrHttpMessage\\HttpMessageFactoryInterface`
-that builds objects implementing PSR-7 interfaces from HttpFoundation objects.
+`HttpMessageFactoryInterface`_ that builds objects implementing PSR-7
+interfaces from HttpFoundation objects.
The following code snippet explains how to convert a :class:`Symfony\\Component\\HttpFoundation\\Request`
to a ``Nyholm\Psr7\ServerRequest`` class implementing the
@@ -69,8 +66,8 @@ Converting Objects implementing PSR-7 Interfaces to HttpFoundation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On the other hand, the bridge provide a factory interface called
-:class:`Symfony\\Bridge\\PsrHttpMessage\\HttpFoundationFactoryInterface`
-that builds HttpFoundation objects from objects implementing PSR-7 interfaces.
+`HttpFoundationFactoryInterface`_ that builds HttpFoundation objects from
+objects implementing PSR-7 interfaces.
The next snippet explain how to convert an object implementing the
``Psr\Http\Message\ServerRequestInterface`` interface to a
@@ -96,3 +93,5 @@ to a :class:`Symfony\\Component\\HttpFoundation\\Response` instance::
.. _`PSR-7`: https://www.php-fig.org/psr/psr-7/
.. _`PSR-17`: https://www.php-fig.org/psr/psr-17/
.. _`libraries that implement psr/http-factory-implementation`: https://packagist.org/providers/psr/http-factory-implementation
+.. _`HttpMessageFactoryInterface`: https://github.com/symfony/psr-http-message-bridge/blob/main/HttpMessageFactoryInterface.php
+.. _`HttpFoundationFactoryInterface`: https://github.com/symfony/psr-http-message-bridge/blob/main/HttpFoundationFactoryInterface.php
diff --git a/components/routing.rst b/components/routing.rst
deleted file mode 100644
index 7ce3e0ac904..00000000000
--- a/components/routing.rst
+++ /dev/null
@@ -1,321 +0,0 @@
-.. index::
- single: Routing
- single: Components; Routing
-
-The Routing Component
-=====================
-
- The Routing component maps an HTTP request to a set of configuration
- variables. It's used to build routing systems for web applications where
- each URL is associated with some code to execute.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/routing
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-The main :doc:`Symfony routing ` article explains all the features of
-this component when used inside a Symfony application. This article only
-explains the things you need to do to use it in a non-Symfony PHP application.
-
-Routing System Setup
---------------------
-
-A routing system has three parts:
-
-* A :class:`Symfony\\Component\\Routing\\RouteCollection`, which contains the
- route definitions (instances of the class :class:`Symfony\\Component\\Routing\\Route`);
-* A :class:`Symfony\\Component\\Routing\\RequestContext`, which has information
- about the request;
-* A :class:`Symfony\\Component\\Routing\\Matcher\\UrlMatcher`, which performs
- the mapping of the path to a single route.
-
-Here is a quick example::
-
- use App\Controller\BlogController;
- use Symfony\Component\Routing\Generator\UrlGenerator;
- use Symfony\Component\Routing\Matcher\UrlMatcher;
- use Symfony\Component\Routing\RequestContext;
- use Symfony\Component\Routing\Route;
- use Symfony\Component\Routing\RouteCollection;
-
- $route = new Route('/blog/{slug}', ['_controller' => BlogController::class]);
- $routes = new RouteCollection();
- $routes->add('blog_show', $route);
-
- $context = new RequestContext('/');
-
- // Routing can match routes with incoming requests
- $matcher = new UrlMatcher($routes, $context);
- $parameters = $matcher->match('/blog/lorem-ipsum');
- // $parameters = [
- // '_controller' => 'App\Controller\BlogController',
- // 'slug' => 'lorem-ipsum',
- // '_route' => 'blog_show'
- // ]
-
- // Routing can also generate URLs for a given route
- $generator = new UrlGenerator($routes, $context);
- $url = $generator->generate('blog_show', [
- 'slug' => 'my-blog-post',
- ]);
- // $url = '/blog/my-blog-post'
-
-The :method:`RouteCollection::add() `
-method takes two arguments. The first is the name of the route. The second
-is a :class:`Symfony\\Component\\Routing\\Route` object, which expects a
-URL path and some array of custom variables in its constructor. This array
-of custom variables can be *anything* that's significant to your application,
-and is returned when that route is matched.
-
-The :method:`UrlMatcher::match() `
-returns the variables you set on the route as well as the route parameters.
-Your application can now use this information to continue processing the request.
-In addition to the configured variables, a ``_route`` key is added, which holds
-the name of the matched route.
-
-If no matching route can be found, a
-:class:`Symfony\\Component\\Routing\\Exception\\ResourceNotFoundException` will
-be thrown.
-
-Defining Routes
----------------
-
-A full route definition can contain up to eight parts::
-
- $route = new Route(
- '/archive/{month}', // path
- ['_controller' => 'showArchive'], // default values
- ['month' => '[0-9]{4}-[0-9]{2}', 'subdomain' => 'www|m'], // requirements
- [], // options
- '{subdomain}.example.com', // host
- [], // schemes
- [], // methods
- 'context.getHost() matches "/(secure|admin).example.com/"' // condition
- );
-
- // ...
-
- $parameters = $matcher->match('/archive/2012-01');
- // [
- // '_controller' => 'showArchive',
- // 'month' => '2012-01',
- // 'subdomain' => 'www',
- // '_route' => ...
- // ]
-
- $parameters = $matcher->match('/archive/foo');
- // throws ResourceNotFoundException
-
-Route Collections
------------------
-
-You can add routes or other instances of
-:class:`Symfony\\Component\\Routing\\RouteCollection` to *another* collection.
-This way you can build a tree of routes. Additionally you can define common
-options for all routes of a subtree using methods provided by the
-``RouteCollection`` class::
-
- $rootCollection = new RouteCollection();
-
- $subCollection = new RouteCollection();
- $subCollection->add(...);
- $subCollection->add(...);
- $subCollection->addPrefix('/prefix');
- $subCollection->addDefaults([...]);
- $subCollection->addRequirements([...]);
- $subCollection->addOptions([...]);
- $subCollection->setHost('{subdomain}.example.com');
- $subCollection->setMethods(['POST']);
- $subCollection->setSchemes(['https']);
- $subCollection->setCondition('context.getHost() matches "/(secure|admin).example.com/"');
-
- $rootCollection->addCollection($subCollection);
-
-Setting the Request Parameters
-------------------------------
-
-The :class:`Symfony\\Component\\Routing\\RequestContext` provides information
-about the current request. You can define all parameters of an HTTP request
-with this class via its constructor::
-
- public function __construct(
- $baseUrl = '',
- $method = 'GET',
- $host = 'localhost',
- $scheme = 'http',
- $httpPort = 80,
- $httpsPort = 443,
- $path = '/',
- $queryString = ''
- )
-
-.. _components-routing-http-foundation:
-
-Normally you can pass the values from the ``$_SERVER`` variable to populate the
-:class:`Symfony\\Component\\Routing\\RequestContext`. But if you use the
-:doc:`HttpFoundation ` component, you can use its
-:class:`Symfony\\Component\\HttpFoundation\\Request` class to feed the
-:class:`Symfony\\Component\\Routing\\RequestContext` in a shortcut::
-
- use Symfony\Component\HttpFoundation\Request;
-
- $context = new RequestContext();
- $context->fromRequest(Request::createFromGlobals());
-
-Loading Routes
---------------
-
-The Routing component comes with a number of loader classes, each giving you the
-ability to load a collection of route definitions from external resources.
-
-File Routing Loaders
-~~~~~~~~~~~~~~~~~~~~
-
-Each loader expects a :class:`Symfony\\Component\\Config\\FileLocator` instance
-as the constructor argument. You can use the :class:`Symfony\\Component\\Config\\FileLocator`
-to define an array of paths in which the loader will look for the requested files.
-If the file is found, the loader returns a :class:`Symfony\\Component\\Routing\\RouteCollection`.
-
-If you're using the ``YamlFileLoader``, then route definitions look like this:
-
-.. code-block:: yaml
-
- # routes.yaml
- route1:
- path: /foo
- controller: MyController::fooAction
- methods: GET|HEAD
- route2:
- path: /foo/bar
- controller: FooBarInvokableController
- methods: PUT
-
-To load this file, you can use the following code. This assumes that your
-``routes.yaml`` file is in the same directory as the below code::
-
- use Symfony\Component\Config\FileLocator;
- use Symfony\Component\Routing\Loader\YamlFileLoader;
-
- // looks inside *this* directory
- $fileLocator = new FileLocator([__DIR__]);
- $loader = new YamlFileLoader($fileLocator);
- $routes = $loader->load('routes.yaml');
-
-Besides :class:`Symfony\\Component\\Routing\\Loader\\YamlFileLoader` there are two
-other loaders that work the same way:
-
-* :class:`Symfony\\Component\\Routing\\Loader\\XmlFileLoader`
-* :class:`Symfony\\Component\\Routing\\Loader\\PhpFileLoader`
-
-If you use the :class:`Symfony\\Component\\Routing\\Loader\\PhpFileLoader` you
-have to provide the name of a PHP file which returns a callable handling a
-:class:`Symfony\\Component\\Routing\\Loader\\Configurator\\RoutingConfigurator`.
-This class allows to chain imports, collections or simple route definition calls::
-
- // RouteProvider.php
- use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
-
- return function (RoutingConfigurator $routes) {
- $routes->add('route_name', '/foo')
- ->controller('ExampleController')
- // ...
- ;
- };
-
-Closure Routing Loaders
-~~~~~~~~~~~~~~~~~~~~~~~
-
-There is also the :class:`Symfony\\Component\\Routing\\Loader\\ClosureLoader`, which
-calls a closure and uses the result as a :class:`Symfony\\Component\\Routing\\RouteCollection`::
-
- use Symfony\Component\Routing\Loader\ClosureLoader;
-
- $closure = function () {
- return new RouteCollection();
- };
-
- $loader = new ClosureLoader();
- $routes = $loader->load($closure);
-
-Annotation Routing Loaders
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Last but not least there are
-:class:`Symfony\\Component\\Routing\\Loader\\AnnotationDirectoryLoader` and
-:class:`Symfony\\Component\\Routing\\Loader\\AnnotationFileLoader` to load
-route definitions from class annotations::
-
- use Doctrine\Common\Annotations\AnnotationReader;
- use Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader;
- use Symfony\Component\Config\FileLocator;
- use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
-
- $loader = new AnnotationDirectoryLoader(
- new FileLocator(__DIR__.'/app/controllers/'),
- new AnnotatedRouteControllerLoader(
- new AnnotationReader()
- )
- );
-
- $routes = $loader->load(__DIR__.'/app/controllers/');
- // ...
-
-.. include:: /_includes/_annotation_loader_tip.rst.inc
-
-The all-in-one Router
-~~~~~~~~~~~~~~~~~~~~~
-
-The :class:`Symfony\\Component\\Routing\\Router` class is an all-in-one package
-to use the Routing component. The constructor expects a loader instance,
-a path to the main route definition and some other settings::
-
- public function __construct(
- LoaderInterface $loader,
- $resource,
- array $options = [],
- RequestContext $context = null,
- LoggerInterface $logger = null
- );
-
-With the ``cache_dir`` option you can enable route caching (if you provide a
-path) or disable caching (if it's set to ``null``). The caching is done
-automatically in the background if you want to use it. A basic example of the
-:class:`Symfony\\Component\\Routing\\Router` class would look like::
-
- $fileLocator = new FileLocator([__DIR__]);
- $requestContext = new RequestContext('/');
-
- $router = new Router(
- new YamlFileLoader($fileLocator),
- 'routes.yaml',
- ['cache_dir' => __DIR__.'/cache'],
- $requestContext
- );
- $parameters = $router->match('/foo/bar');
- $url = $router->generate('some_route', ['parameter' => 'value']);
-
-.. note::
-
- If you use caching, the Routing component will compile new classes which
- are saved in the ``cache_dir``. This means your script must have write
- permissions for that location.
-
-Learn more
-----------
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- /routing
- /routing/*
- /controller
- /controller/*
diff --git a/components/runtime.rst b/components/runtime.rst
new file mode 100644
index 00000000000..770ea102563
--- /dev/null
+++ b/components/runtime.rst
@@ -0,0 +1,496 @@
+The Runtime Component
+=====================
+
+ The Runtime Component decouples the bootstrapping logic from any global state
+ to make sure the application can run with runtimes like `PHP-PM`_, `ReactPHP`_,
+ `Swoole`_, `FrankenPHP`_ etc. without any changes.
+
+Installation
+------------
+
+.. code-block:: terminal
+
+ $ composer require symfony/runtime
+
+.. include:: /components/require_autoload.rst.inc
+
+Usage
+-----
+
+The Runtime component abstracts most bootstrapping logic as so-called
+*runtimes*, allowing you to write front-controllers in a generic way.
+For instance, the Runtime component allows Symfony's ``public/index.php``
+to look like this::
+
+ // public/index.php
+ use App\Kernel;
+
+ require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
+
+ return function (array $context): Kernel {
+ return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
+ };
+
+So how does this front-controller work? At first, the special
+``autoload_runtime.php`` file is automatically created by the Composer plugin in
+the component. This file runs the following logic:
+
+#. It instantiates a :class:`Symfony\\Component\\Runtime\\RuntimeInterface`;
+#. The front-controller script (e.g. ``public/index.php``) is included by the
+ runtime, making it run again. Ensure this doesn't produce any side effects
+ in your code;
+#. The callable (returned by ``public/index.php``) is passed to the Runtime, whose job
+ is to resolve the arguments (in this example: ``array $context``);
+#. Then, this callable is called to get the application (``App\Kernel``);
+#. At last, the Runtime is used to run the application (i.e. calling
+ ``$kernel->handle(Request::createFromGlobals())->send()``).
+
+.. warning::
+
+ If you use the Composer ``--no-plugins`` option, the ``autoload_runtime.php``
+ file won't be created.
+
+ If you use the Composer ``--no-scripts`` option, make sure your Composer version
+ is ``>=2.1.3``; otherwise the ``autoload_runtime.php`` file won't be created.
+
+To make a console application, the bootstrap code would look like::
+
+ #!/usr/bin/env php
+ setCode(static function (InputInterface $input, OutputInterface $output): void {
+ $output->write('Hello World');
+ });
+
+ return $command;
+ };
+
+:class:`Symfony\\Component\\Console\\Application`
+ Useful with console applications with more than one command. This will use the
+ :class:`Symfony\\Component\\Runtime\\Runner\\Symfony\\ConsoleApplicationRunner`::
+
+ use Symfony\Component\Console\Application;
+ use Symfony\Component\Console\Command\Command;
+ use Symfony\Component\Console\Input\InputInterface;
+ use Symfony\Component\Console\Output\OutputInterface;
+
+ require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
+
+ return static function (array $context): Application {
+ $command = new Command('hello');
+ $command->setCode(static function (InputInterface $input, OutputInterface $output): void {
+ $output->write('Hello World');
+ });
+
+ $app = new Application();
+ $app->add($command);
+ $app->setDefaultCommand('hello', true);
+
+ return $app;
+ };
+
+The ``GenericRuntime`` and ``SymfonyRuntime`` also support these generic
+applications:
+
+:class:`Symfony\\Component\\Runtime\\RunnerInterface`
+ The ``RunnerInterface`` is a way to use a custom application with the
+ generic Runtime::
+
+ // public/index.php
+ use Symfony\Component\Runtime\RunnerInterface;
+
+ require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
+
+ return static function (): RunnerInterface {
+ return new class implements RunnerInterface {
+ public function run(): int
+ {
+ echo 'Hello World';
+
+ return 0;
+ }
+ };
+ };
+
+``callable``
+ Your "application" can also be a ``callable``. The first callable will return
+ the "application" and the second callable is the "application" itself::
+
+ // public/index.php
+ require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
+
+ return static function (): callable {
+ $app = static function(): int {
+ echo 'Hello World';
+
+ return 0;
+ };
+
+ return $app;
+ };
+
+``void``
+ If the callable doesn't return anything, the ``SymfonyRuntime`` will assume
+ everything is fine::
+
+ require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
+
+ return function (): void {
+ echo 'Hello world';
+ };
+
+Using Options
+~~~~~~~~~~~~~
+
+Some behavior of the Runtimes can be modified through runtime options. They
+can be set using the ``APP_RUNTIME_OPTIONS`` environment variable::
+
+ $_SERVER['APP_RUNTIME_OPTIONS'] = [
+ 'project_dir' => '/var/task',
+ ];
+
+ require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
+
+ // ...
+
+You can also configure ``extra.runtime`` in ``composer.json``:
+
+.. code-block:: json
+
+ {
+ "require": {
+ "...": "..."
+ },
+ "extra": {
+ "runtime": {
+ "project_dir": "/var/task"
+ }
+ }
+ }
+
+Then, update your Composer files (running ``composer dump-autoload``, for instance),
+so that the ``vendor/autoload_runtime.php`` files gets regenerated with the new option.
+
+The following options are supported by the ``SymfonyRuntime``:
+
+``env`` (default: ``APP_ENV`` environment variable, or ``"dev"``)
+ To define the name of the environment the app runs in.
+``disable_dotenv`` (default: ``false``)
+ To disable looking for ``.env`` files.
+``dotenv_path`` (default: ``.env``)
+ To define the path of dot-env files.
+``dotenv_overload`` (default: ``false``)
+ To tell Dotenv whether to override ``.env`` vars with ``.env.local`` (or other ``.env.*`` files)
+``use_putenv``
+ To tell Dotenv to set env vars using ``putenv()`` (NOT RECOMMENDED).
+``prod_envs`` (default: ``["prod"]``)
+ To define the names of the production envs.
+``test_envs`` (default: ``["test"]``)
+ To define the names of the test envs.
+
+Besides these, the ``GenericRuntime`` and ``SymfonyRuntime`` also support
+these options:
+
+``debug`` (default: the value of the env var defined by ``debug_var_name`` option
+ (usually, ``APP_DEBUG``), or ``true`` if such env var is not defined)
+ Toggles the :ref:`debug mode ` of Symfony applications (e.g. to
+ display errors)
+``runtimes``
+ Maps "application types" to a ``GenericRuntime`` implementation that
+ knows how to deal with each of them.
+``error_handler`` (default: :class:`Symfony\\Component\\Runtime\\Internal\\BasicErrorHandler` or :class:`Symfony\\Component\\Runtime\\Internal\\SymfonyErrorHandler` for ``SymfonyRuntime``)
+ Defines the class to use to handle PHP errors.
+``env_var_name`` (default: ``"APP_ENV"``)
+ Defines the name of the env var that stores the name of the
+ :ref:`configuration environment `
+ to use when running the application.
+``debug_var_name`` (default: ``"APP_DEBUG"``)
+ Defines the name of the env var that stores the value of the
+ :ref:`debug mode ` flag to use when running the application.
+
+Create Your Own Runtime
+-----------------------
+
+This is an advanced topic that describes the internals of the Runtime component.
+
+Using the Runtime component will benefit maintainers because the bootstrap
+logic could be versioned as a part of a normal package. If the application
+author decides to use this component, the package maintainer of the Runtime
+class will have more control and can fix bugs and add features.
+
+The Runtime component is designed to be totally generic and able to run any
+application outside of the global state in 6 steps:
+
+#. The main entry point returns a *callable* (the "app") that wraps the application;
+#. The *app callable* is passed to ``RuntimeInterface::getResolver()``, which returns
+ a :class:`Symfony\\Component\\Runtime\\ResolverInterface`. This resolver returns
+ an array with the app callable (or something that decorates this callable) at
+ index 0 and all its resolved arguments at index 1.
+#. The *app callable* is invoked with its arguments, it will return an object that
+ represents the application.
+#. This *application object* is passed to ``RuntimeInterface::getRunner()``, which
+ returns a :class:`Symfony\\Component\\Runtime\\RunnerInterface`: an instance
+ that knows how to "run" the application object.
+#. The ``RunnerInterface::run(object $application)`` is called and it returns the
+ exit status code as ``int``.
+#. The PHP engine is terminated with this status code.
+
+When creating a new runtime, there are two things to consider: First, what arguments
+will the end user use? Second, what will the user's application look like?
+
+For instance, imagine you want to create a runtime for `ReactPHP`_:
+
+**What arguments will the end user use?**
+
+For a generic ReactPHP application, no special arguments are
+typically required. This means that you can use the
+:class:`Symfony\\Component\\Runtime\\GenericRuntime`.
+
+**What will the user's application look like?**
+
+There is also no typical React application, so you might want to rely on
+the `PSR-15`_ interfaces for HTTP request handling.
+
+However, a ReactPHP application will need some special logic to *run*. That logic
+is added in a new class implementing :class:`Symfony\\Component\\Runtime\\RunnerInterface`::
+
+ use Psr\Http\Message\ResponseInterface;
+ use Psr\Http\Message\ServerRequestInterface;
+ use Psr\Http\Server\RequestHandlerInterface;
+ use React\EventLoop\Factory as ReactFactory;
+ use React\Http\Server as ReactHttpServer;
+ use React\Socket\Server as ReactSocketServer;
+ use Symfony\Component\Runtime\RunnerInterface;
+
+ class ReactPHPRunner implements RunnerInterface
+ {
+ public function __construct(
+ private RequestHandlerInterface $application,
+ private int $port,
+ ) {
+ }
+
+ public function run(): int
+ {
+ $application = $this->application;
+ $loop = ReactFactory::create();
+
+ // configure ReactPHP to correctly handle the PSR-15 application
+ $server = new ReactHttpServer(
+ $loop,
+ function (ServerRequestInterface $request) use ($application): ResponseInterface {
+ return $application->handle($request);
+ }
+ );
+
+ // start the ReactPHP server
+ $socket = new ReactSocketServer($this->port, $loop);
+ $server->listen($socket);
+
+ $loop->run();
+
+ return 0;
+ }
+ }
+
+By extending the ``GenericRuntime``, you make sure that the application is
+always using this ``ReactPHPRunner``::
+
+ use Symfony\Component\Runtime\GenericRuntime;
+ use Symfony\Component\Runtime\RunnerInterface;
+
+ class ReactPHPRuntime extends GenericRuntime
+ {
+ private int $port;
+
+ public function __construct(array $options)
+ {
+ $this->port = $options['port'] ?? 8080;
+ parent::__construct($options);
+ }
+
+ public function getRunner(?object $application): RunnerInterface
+ {
+ if ($application instanceof RequestHandlerInterface) {
+ return new ReactPHPRunner($application, $this->port);
+ }
+
+ // if it's not a PSR-15 application, use the GenericRuntime to
+ // run the application (see "Resolvable Applications" above)
+ return parent::getRunner($application);
+ }
+ }
+
+The end user will now be able to create front controller like::
+
+ require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
+
+ return function (array $context): SomeCustomPsr15Application {
+ return new SomeCustomPsr15Application();
+ };
+
+.. _PHP-PM: https://github.com/php-pm/php-pm
+.. _Swoole: https://openswoole.com/
+.. _FrankenPHP: https://frankenphp.dev/
+.. _ReactPHP: https://reactphp.org/
+.. _`PSR-15`: https://www.php-fig.org/psr/psr-15/
+.. _`runtime template file`: https://github.com/symfony/symfony/blob/{version}/src/Symfony/Component/Runtime/Internal/autoload_runtime.template
diff --git a/components/security.rst b/components/security.rst
deleted file mode 100644
index 9985b611c63..00000000000
--- a/components/security.rst
+++ /dev/null
@@ -1,65 +0,0 @@
-.. index::
- single: Security
-
-The Security Component
-======================
-
- The Security component provides a complete security system for your web
- application. It ships with facilities for authenticating using HTTP basic
- authentication, interactive form login or X.509 certificate login, but also
- allows you to implement your own authentication strategies. Furthermore, the
- component provides ways to authorize authenticated users based on their
- roles.
-
-Installation
-------------
-
-The Security component is divided into several smaller sub-components which can
-be used separately:
-
-``symfony/security-core``
- It provides all the common security features, from authentication to
- authorization and from encoding passwords to loading users.
-
-``symfony/security-http``
- It integrates the core sub-component with the HTTP protocol to handle HTTP
- requests and responses.
-
-``symfony/security-csrf``
- It provides protection against `CSRF attacks`_.
-
-``symfony/security-guard``
- It brings many layers of authentication together, allowing the creation
- of complex authentication systems.
-
-You can install each of them separately in your project:
-
-.. code-block:: terminal
-
- $ composer require symfony/security-core
- $ composer require symfony/security-http
- $ composer require symfony/security-csrf
- $ composer require symfony/security-guard
-
-.. include:: /components/require_autoload.rst.inc
-
-.. seealso::
-
- This article explains how to use the Security features as an independent
- component in any PHP application. Read the :doc:`/security` article to learn
- about how to use it in Symfony applications.
-
-Learn More
-----------
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- /components/security/*
- /security
- /security/*
- /reference/configuration/security
- /reference/constraints/UserPassword
-
-.. _`CSRF attacks`: https://en.wikipedia.org/wiki/Cross-site_request_forgery
diff --git a/components/security/authentication.rst b/components/security/authentication.rst
deleted file mode 100644
index b3394dbb65e..00000000000
--- a/components/security/authentication.rst
+++ /dev/null
@@ -1,327 +0,0 @@
-.. index::
- single: Security, Authentication
-
-Authentication
-==============
-
-When a request points to a secured area, and one of the listeners from the
-firewall map is able to extract the user's credentials from the current
-:class:`Symfony\\Component\\HttpFoundation\\Request` object, it should create
-a token, containing these credentials. The next thing the listener should
-do is ask the authentication manager to validate the given token, and return
-an *authenticated* token if the supplied credentials were found to be valid.
-The listener should then store the authenticated token using
-:class:`the token storage `::
-
- use Symfony\Component\HttpKernel\Event\RequestEvent;
- use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
- use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
- use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
- use Symfony\Component\Security\Http\Firewall\ListenerInterface;
-
- class SomeAuthenticationListener implements ListenerInterface
- {
- /**
- * @var TokenStorageInterface
- */
- private $tokenStorage;
-
- /**
- * @var AuthenticationManagerInterface
- */
- private $authenticationManager;
-
- /**
- * @var string Uniquely identifies the secured area
- */
- private $providerKey;
-
- // ...
-
- public function handle(RequestEvent $event)
- {
- $request = $event->getRequest();
-
- $username = ...;
- $password = ...;
-
- $unauthenticatedToken = new UsernamePasswordToken(
- $username,
- $password,
- $this->providerKey
- );
-
- $authenticatedToken = $this
- ->authenticationManager
- ->authenticate($unauthenticatedToken);
-
- $this->tokenStorage->setToken($authenticatedToken);
- }
- }
-
-.. note::
-
- A token can be of any class, as long as it implements
- :class:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface`.
-
-The Authentication Manager
---------------------------
-
-The default authentication manager is an instance of
-:class:`Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationProviderManager`::
-
- use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
- use Symfony\Component\Security\Core\Exception\AuthenticationException;
-
- // instances of Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface
- $providers = [...];
-
- $authenticationManager = new AuthenticationProviderManager($providers);
-
- try {
- $authenticatedToken = $authenticationManager
- ->authenticate($unauthenticatedToken);
- } catch (AuthenticationException $exception) {
- // authentication failed
- }
-
-The ``AuthenticationProviderManager``, when instantiated, receives several
-authentication providers, each supporting a different type of token.
-
-.. note::
-
- You may write your own authentication manager, the only requirement is that
- it implements :class:`Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationManagerInterface`.
-
-.. _authentication_providers:
-
-Authentication Providers
-------------------------
-
-Each provider (since it implements
-:class:`Symfony\\Component\\Security\\Core\\Authentication\\Provider\\AuthenticationProviderInterface`)
-has a method :method:`Symfony\\Component\\Security\\Core\\Authentication\\Provider\\AuthenticationProviderInterface::supports`
-by which the ``AuthenticationProviderManager``
-can determine if it supports the given token. If this is the case, the
-manager then calls the provider's method :method:`Symfony\\Component\\Security\\Core\\Authentication\\Provider\\AuthenticationProviderInterface::authenticate`.
-This method should return an authenticated token or throw an
-:class:`Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException`
-(or any other exception extending it).
-
-Authenticating Users by their Username and Password
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-An authentication provider will attempt to authenticate a user based on
-the credentials they provided. Usually these are a username and a password.
-Most web applications store their user's username and a hash of the user's
-password combined with a randomly generated salt. This means that the average
-authentication would consist of fetching the salt and the hashed password
-from the user data storage, hash the password the user has just provided
-(e.g. using a login form) with the salt and compare both to determine if
-the given password is valid.
-
-This functionality is offered by the :class:`Symfony\\Component\\Security\\Core\\Authentication\\Provider\\DaoAuthenticationProvider`.
-It fetches the user's data from a :class:`Symfony\\Component\\Security\\Core\\User\\UserProviderInterface`,
-uses a :class:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface`
-to create a hash of the password and returns an authenticated token if the
-password was valid::
-
- use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;
- use Symfony\Component\Security\Core\Encoder\EncoderFactory;
- use Symfony\Component\Security\Core\User\InMemoryUserProvider;
- use Symfony\Component\Security\Core\User\UserChecker;
-
- $userProvider = new InMemoryUserProvider(
- [
- 'admin' => [
- // password is "foo"
- 'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==',
- 'roles' => ['ROLE_ADMIN'],
- ],
- ]
- );
-
- // for some extra checks: is account enabled, locked, expired, etc.
- $userChecker = new UserChecker();
-
- // an array of password encoders (see below)
- $encoderFactory = new EncoderFactory(...);
-
- $daoProvider = new DaoAuthenticationProvider(
- $userProvider,
- $userChecker,
- 'secured_area',
- $encoderFactory
- );
-
- $daoProvider->authenticate($unauthenticatedToken);
-
-.. note::
-
- The example above demonstrates the use of the "in-memory" user provider,
- but you may use any user provider, as long as it implements
- :class:`Symfony\\Component\\Security\\Core\\User\\UserProviderInterface`.
- It is also possible to let multiple user providers try to find the user's
- data, using the :class:`Symfony\\Component\\Security\\Core\\User\\ChainUserProvider`.
-
-The Password Encoder Factory
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The :class:`Symfony\\Component\\Security\\Core\\Authentication\\Provider\\DaoAuthenticationProvider`
-uses an encoder factory to create a password encoder for a given type of
-user. This allows you to use different encoding strategies for different
-types of users. The default :class:`Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactory`
-receives an array of encoders::
-
- use Acme\Entity\LegacyUser;
- use Symfony\Component\Security\Core\Encoder\EncoderFactory;
- use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
- use Symfony\Component\Security\Core\User\User;
-
- $defaultEncoder = new MessageDigestPasswordEncoder('sha512', true, 5000);
- $weakEncoder = new MessageDigestPasswordEncoder('md5', true, 1);
-
- $encoders = [
- User::class => $defaultEncoder,
- LegacyUser::class => $weakEncoder,
- // ...
- ];
- $encoderFactory = new EncoderFactory($encoders);
-
-Each encoder should implement :class:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface`
-or be an array with a ``class`` and an ``arguments`` key, which allows the
-encoder factory to construct the encoder only when it is needed.
-
-Creating a custom Password Encoder
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-There are many built-in password encoders. But if you need to create your
-own, it needs to follow these rules:
-
-#. The class must implement :class:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface`;
-
-#. The implementations of
- :method:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface::encodePassword`
- and
- :method:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface::isPasswordValid`
- must first of all make sure the password is not too long, i.e. the password length is no longer
- than 4096 characters. This is for security reasons (see `CVE-2013-5750`_), and you can use the
- :method:`Symfony\\Component\\Security\\Core\\Encoder\\BasePasswordEncoder::isPasswordTooLong`
- method for this check::
-
- use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;
- use Symfony\Component\Security\Core\Exception\BadCredentialsException;
-
- class FoobarEncoder extends BasePasswordEncoder
- {
- public function encodePassword($raw, $salt)
- {
- if ($this->isPasswordTooLong($raw)) {
- throw new BadCredentialsException('Invalid password.');
- }
-
- // ...
- }
-
- public function isPasswordValid($encoded, $raw, $salt)
- {
- if ($this->isPasswordTooLong($raw)) {
- return false;
- }
-
- // ...
- }
- }
-
-Using Password Encoders
-~~~~~~~~~~~~~~~~~~~~~~~
-
-When the :method:`Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactory::getEncoder`
-method of the password encoder factory is called with the user object as
-its first argument, it will return an encoder of type :class:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface`
-which should be used to encode this user's password::
-
- // a Acme\Entity\LegacyUser instance
- $user = ...;
-
- // the password that was submitted, e.g. when registering
- $plainPassword = ...;
-
- $encoder = $encoderFactory->getEncoder($user);
-
- // returns $weakEncoder (see above)
- $encodedPassword = $encoder->encodePassword($plainPassword, $user->getSalt());
-
- $user->setPassword($encodedPassword);
-
- // ... save the user
-
-Now, when you want to check if the submitted password (e.g. when trying to log
-in) is correct, you can use::
-
- // fetch the Acme\Entity\LegacyUser
- $user = ...;
-
- // the submitted password, e.g. from the login form
- $plainPassword = ...;
-
- $validPassword = $encoder->isPasswordValid(
- $user->getPassword(), // the encoded password
- $plainPassword, // the submitted password
- $user->getSalt()
- );
-
-Authentication Events
----------------------
-
-The security component provides 4 related authentication events:
-
-=============================== ================================================================= ==============================================================================
-Name Event Constant Argument Passed to the Listener
-=============================== ================================================================= ==============================================================================
-security.authentication.success ``AuthenticationEvents::AUTHENTICATION_SUCCESS`` :class:`Symfony\\Component\\Security\\Core\\Event\\AuthenticationEvent`
-security.authentication.failure ``AuthenticationEvents::AUTHENTICATION_FAILURE`` :class:`Symfony\\Component\\Security\\Core\\Event\\AuthenticationFailureEvent`
-security.interactive_login ``SecurityEvents::INTERACTIVE_LOGIN`` :class:`Symfony\\Component\\Security\\Http\\Event\\InteractiveLoginEvent`
-security.switch_user ``SecurityEvents::SWITCH_USER`` :class:`Symfony\\Component\\Security\\Http\\Event\\SwitchUserEvent`
-security.logout_on_change ``Symfony\Component\Security\Http\Event\DeauthenticatedEvent`` :class:`Symfony\\Component\\Security\\Http\\Event\\DeauthenticatedEvent`
-=============================== ================================================================= ==============================================================================
-
-Authentication Success and Failure Events
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When a provider authenticates the user, a ``security.authentication.success``
-event is dispatched. But beware - this event may fire, for example, on *every*
-request if you have session-based authentication, if ``always_authenticate_before_granting``
-is enabled or if token is not authenticated before AccessListener is invoked.
-See ``security.interactive_login`` below if you need to do something when a user *actually* logs in.
-
-When a provider attempts authentication but fails (i.e. throws an ``AuthenticationException``),
-a ``security.authentication.failure`` event is dispatched. You could listen on
-the ``security.authentication.failure`` event, for example, in order to log
-failed login attempts.
-
-Security Events
-~~~~~~~~~~~~~~~
-
-The ``security.interactive_login`` event is triggered after a user has actively
-logged into your website. It is important to distinguish this action from
-non-interactive authentication methods, such as:
-
-* authentication based on your session.
-* authentication using a HTTP basic header.
-
-You could listen on the ``security.interactive_login`` event, for example, in
-order to give your user a welcome flash message every time they log in.
-
-The ``security.switch_user`` event is triggered every time you activate
-the ``switch_user`` firewall listener.
-
-The ``Symfony\Component\Security\Http\Event\DeauthenticatedEvent`` event is triggered when a token has been deauthenticated
-because of a user change, it can help you doing some clean-up task when a logout has been triggered.
-
-.. seealso::
-
- For more information on switching users, see
- :doc:`/security/impersonating_user`.
-
-.. _`CVE-2013-5750`: https://symfony.com/blog/cve-2013-5750-security-issue-in-fosuserbundle-login-form
diff --git a/components/security/authorization.rst b/components/security/authorization.rst
deleted file mode 100644
index 647a204f0b5..00000000000
--- a/components/security/authorization.rst
+++ /dev/null
@@ -1,261 +0,0 @@
-.. index::
- single: Security, Authorization
-
-Authorization
-=============
-
-When any of the authentication providers (see :ref:`authentication_providers`)
-has verified the still-unauthenticated token, an authenticated token will
-be returned. The authentication listener should set this token directly
-in the :class:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\Storage\\TokenStorageInterface`
-using its :method:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\Storage\\TokenStorageInterface::setToken`
-method.
-
-From then on, the user is authenticated, i.e. identified. Now, other parts
-of the application can use the token to decide whether or not the user may
-request a certain URI, or modify a certain object. This decision will be made
-by an instance of :class:`Symfony\\Component\\Security\\Core\\Authorization\\AccessDecisionManagerInterface`.
-
-An authorization decision will always be based on a few things:
-
-* The current token
- For instance, the token's :method:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface::getRoleNames`
- method may be used to retrieve the roles of the current user (e.g.
- ``ROLE_SUPER_ADMIN``), or a decision may be based on the class of the token.
-* A set of attributes
- Each attribute stands for a certain right the user should have, e.g.
- ``ROLE_ADMIN`` to make sure the user is an administrator.
-* An object (optional)
- Any object for which access control needs to be checked, like
- an article or a comment object.
-
-.. _components-security-access-decision-manager:
-
-Access Decision Manager
------------------------
-
-Since deciding whether or not a user is authorized to perform a certain
-action can be a complicated process, the standard :class:`Symfony\\Component\\Security\\Core\\Authorization\\AccessDecisionManager`
-itself depends on multiple voters, and makes a final verdict based on all
-the votes (either positive, negative or neutral) it has received. It
-recognizes several strategies:
-
-``affirmative`` (default)
- grant access as soon as there is one voter granting access;
-
-``consensus``
- grant access if there are more voters granting access than there are denying;
-
-``unanimous``
- only grant access if none of the voters has denied access;
-
-Usage of the available options in detail::
-
- use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
-
- // instances of Symfony\Component\Security\Core\Authorization\Voter\VoterInterface
- $voters = [...];
-
- // one of "affirmative", "consensus", "unanimous"
- $strategy = ...;
-
- // whether or not to grant access when all voters abstain
- $allowIfAllAbstainDecisions = ...;
-
- // whether or not to grant access when there is no majority (applies only to the "consensus" strategy)
- $allowIfEqualGrantedDeniedDecisions = ...;
-
- $accessDecisionManager = new AccessDecisionManager(
- $voters,
- $strategy,
- $allowIfAllAbstainDecisions,
- $allowIfEqualGrantedDeniedDecisions
- );
-
-.. seealso::
-
- You can change the default strategy in the
- :ref:`configuration `.
-
-Voters
-------
-
-Voters are instances
-of :class:`Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface`,
-which means they have to implement a few methods which allows the decision
-manager to use them:
-
-``vote(TokenInterface $token, $object, array $attributes)``
- this method will do the actual voting and return a value equal to one
- of the class constants of :class:`Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface`,
- i.e. ``VoterInterface::ACCESS_GRANTED``, ``VoterInterface::ACCESS_DENIED``
- or ``VoterInterface::ACCESS_ABSTAIN``;
-
-The Security component contains some standard voters which cover many use
-cases:
-
-AuthenticatedVoter
-~~~~~~~~~~~~~~~~~~
-
-The :class:`Symfony\\Component\\Security\\Core\\Authorization\\Voter\\AuthenticatedVoter`
-voter supports the attributes ``IS_AUTHENTICATED_FULLY``, ``IS_AUTHENTICATED_REMEMBERED``,
-and ``IS_AUTHENTICATED_ANONYMOUSLY`` and grants access based on the current
-level of authentication, i.e. is the user fully authenticated, or only based
-on a "remember-me" cookie, or even authenticated anonymously?::
-
- use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
- use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
- use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
-
- $trustResolver = new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
-
- $authenticatedVoter = new AuthenticatedVoter($trustResolver);
-
- // instance of Symfony\Component\Security\Core\Authentication\Token\TokenInterface
- $token = ...;
-
- // any object
- $object = ...;
-
- $vote = $authenticatedVoter->vote($token, $object, ['IS_AUTHENTICATED_FULLY']);
-
-RoleVoter
-~~~~~~~~~
-
-The :class:`Symfony\\Component\\Security\\Core\\Authorization\\Voter\\RoleVoter`
-supports attributes starting with ``ROLE_`` and grants access to the user
-when the required ``ROLE_*`` attributes can all be found in the array of
-roles returned by the token's :method:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface::getRoleNames`
-method::
-
- use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
-
- $roleVoter = new RoleVoter('ROLE_');
-
- $roleVoter->vote($token, $object, ['ROLE_ADMIN']);
-
-RoleHierarchyVoter
-~~~~~~~~~~~~~~~~~~
-
-The :class:`Symfony\\Component\\Security\\Core\\Authorization\\Voter\\RoleHierarchyVoter`
-extends :class:`Symfony\\Component\\Security\\Core\\Authorization\\Voter\\RoleVoter`
-and provides some additional functionality: it knows how to handle a
-hierarchy of roles. For instance, a ``ROLE_SUPER_ADMIN`` role may have sub-roles
-``ROLE_ADMIN`` and ``ROLE_USER``, so that when a certain object requires the
-user to have the ``ROLE_ADMIN`` role, it grants access to users who in fact
-have the ``ROLE_ADMIN`` role, but also to users having the ``ROLE_SUPER_ADMIN``
-role::
-
- use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
- use Symfony\Component\Security\Core\Role\RoleHierarchy;
-
- $hierarchy = [
- 'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_USER'],
- ];
-
- $roleHierarchy = new RoleHierarchy($hierarchy);
-
- $roleHierarchyVoter = new RoleHierarchyVoter($roleHierarchy);
-
-ExpressionVoter
-~~~~~~~~~~~~~~~
-
-The :class:`Symfony\\Component\\Security\\Core\\Authorization\\Voter\\ExpressionVoter`
-grants access based on the evaluation of expressions created with the
-:doc:`ExpressionLanguage component `. These
-expressions have access to a number of
-:ref:`special security variables `::
-
- use Symfony\Component\ExpressionLanguage\Expression;
- use Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter;
-
- // Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
- $expressionLanguage = ...;
-
- // instance of Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface
- $trustResolver = ...;
-
- // Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface
- $authorizationChecker = ...;
-
- $expressionVoter = new ExpressionVoter($expressionLanguage, $trustResolver, $authorizationChecker);
-
- // instance of Symfony\Component\Security\Core\Authentication\Token\TokenInterface
- $token = ...;
-
- // any object
- $object = ...;
-
- $expression = new Expression(
- '"ROLE_ADMIN" in roles or (not is_anonymous() and user.isSuperAdmin())'
- )
-
- $vote = $expressionVoter->vote($token, $object, [$expression]);
-
-.. note::
-
- When you make your own voter, you can use its constructor to inject any
- dependencies it needs to come to a decision.
-
-Roles
------
-
-Roles are strings that give expression to a certain right the user has (e.g.
-*"edit a blog post"*, *"create an invoice"*). You can freely choose those
-strings. The only requirement is that they must start with the ``ROLE_`` prefix
-(e.g. ``ROLE_POST_EDIT``, ``ROLE_INVOICE_CREATE``).
-
-Using the Decision Manager
---------------------------
-
-The Access Listener
-~~~~~~~~~~~~~~~~~~~
-
-The access decision manager can be used at any point in a request to decide whether
-or not the current user is entitled to access a given resource. One optional,
-but useful, method for restricting access based on a URL pattern is the
-:class:`Symfony\\Component\\Security\\Http\\Firewall\\AccessListener`,
-which is one of the firewall listeners (see :ref:`firewall_listeners`) that
-is triggered for each request matching the firewall map (see :ref:`firewall`).
-
-It uses an access map (which should be an instance of :class:`Symfony\\Component\\Security\\Http\\AccessMapInterface`)
-which contains request matchers and a corresponding set of attributes that
-are required for the current user to get access to the application::
-
- use Symfony\Component\HttpFoundation\RequestMatcher;
- use Symfony\Component\Security\Http\AccessMap;
- use Symfony\Component\Security\Http\Firewall\AccessListener;
-
- $accessMap = new AccessMap();
- $requestMatcher = new RequestMatcher('^/admin');
- $accessMap->add($requestMatcher, ['ROLE_ADMIN']);
-
- $accessListener = new AccessListener(
- $securityContext,
- $accessDecisionManager,
- $accessMap,
- $authenticationManager
- );
-
-Authorization Checker
-~~~~~~~~~~~~~~~~~~~~~
-
-The access decision manager is also available to other parts of the application
-via the :method:`Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker::isGranted`
-method of the :class:`Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker`.
-A call to this method will directly delegate the question to the access
-decision manager::
-
- use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
- use Symfony\Component\Security\Core\Exception\AccessDeniedException;
-
- $authorizationChecker = new AuthorizationChecker(
- $tokenStorage,
- $authenticationManager,
- $accessDecisionManager
- );
-
- if (!$authorizationChecker->isGranted('ROLE_ADMIN')) {
- throw new AccessDeniedException();
- }
-
diff --git a/components/security/firewall.rst b/components/security/firewall.rst
deleted file mode 100644
index 17b7d03e0d2..00000000000
--- a/components/security/firewall.rst
+++ /dev/null
@@ -1,164 +0,0 @@
-.. index::
- single: Security, Firewall
-
-The Firewall and Authorization
-==============================
-
-Central to the Security component is authorization. This is handled by an instance
-of :class:`Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationCheckerInterface`.
-When all steps in the process of authenticating the user have been taken successfully,
-you can ask the authorization checker if the authenticated user has access to a
-certain action or resource of the application::
-
- use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
- use Symfony\Component\Security\Core\Exception\AccessDeniedException;
-
- // instance of Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface
- $tokenStorage = ...;
-
- // instance of Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface
- $authenticationManager = ...;
-
- // instance of Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface
- $accessDecisionManager = ...;
-
- $authorizationChecker = new AuthorizationChecker(
- $tokenStorage,
- $authenticationManager,
- $accessDecisionManager
- );
-
- // ... authenticate the user
-
- if (!$authorizationChecker->isGranted('ROLE_ADMIN')) {
- throw new AccessDeniedException();
- }
-
-.. note::
-
- Read the dedicated articles to learn more about :doc:`/components/security/authentication`
- and :doc:`/components/security/authorization`.
-
-.. _firewall:
-
-A Firewall for HTTP Requests
-----------------------------
-
-Authenticating a user is done by the firewall. An application may have
-multiple secured areas, so the firewall is configured using a map of these
-secured areas. For each of these areas, the map contains a request matcher
-and a collection of listeners. The request matcher gives the firewall the
-ability to find out if the current request points to a secured area.
-The listeners are then asked if the current request can be used to authenticate
-the user::
-
- use Symfony\Component\HttpFoundation\RequestMatcher;
- use Symfony\Component\Security\Http\Firewall\ExceptionListener;
- use Symfony\Component\Security\Http\FirewallMap;
-
- $firewallMap = new FirewallMap();
-
- $requestMatcher = new RequestMatcher('^/secured-area/');
-
- // instances of Symfony\Component\Security\Http\Firewall\ListenerInterface
- $listeners = [...];
-
- $exceptionListener = new ExceptionListener(...);
-
- $firewallMap->add($requestMatcher, $listeners, $exceptionListener);
-
-The firewall map will be given to the firewall as its first argument, together
-with the event dispatcher that is used by the :class:`Symfony\\Component\\HttpKernel\\HttpKernel`::
-
- use Symfony\Component\HttpKernel\KernelEvents;
- use Symfony\Component\Security\Http\Firewall;
-
- // the EventDispatcher used by the HttpKernel
- $dispatcher = ...;
-
- $firewall = new Firewall($firewallMap, $dispatcher);
-
- $dispatcher->addListener(
- KernelEvents::REQUEST,
- [$firewall, 'onKernelRequest']
- );
-
-The firewall is registered to listen to the ``kernel.request`` event that
-will be dispatched by the HttpKernel at the beginning of each request
-it processes. This way, the firewall may prevent the user from going any
-further than allowed.
-
-Firewall Config
-~~~~~~~~~~~~~~~
-
-The information about a given firewall, such as its name, provider, context,
-entry point and access denied URL, is provided by instances of the
-:class:`Symfony\\Bundle\\SecurityBundle\\Security\\FirewallConfig` class.
-
-This object can be accessed through the ``getFirewallConfig(Request $request)``
-method of the :class:`Symfony\\Component\\Security\\Http\\FirewallMap` class and
-through the ``getConfig()`` method of the
-:class:`Symfony\\Bundle\\SecurityBundle\\Security\\FirewallContext` class.
-
-.. _firewall_listeners:
-
-Firewall Listeners
-~~~~~~~~~~~~~~~~~~
-
-When the firewall gets notified of the ``kernel.request`` event, it asks
-the firewall map if the request matches one of the secured areas. The first
-secured area that matches the request will return a set of corresponding
-firewall listeners (which each implement :class:`Symfony\\Component\\Security\\Http\\Firewall\\ListenerInterface`).
-These listeners will all be asked to handle the current request. This basically
-means: find out if the current request contains any information by which
-the user might be authenticated (for instance the Basic HTTP authentication
-listener checks if the request has a header called ``PHP_AUTH_USER``).
-
-Exception Listener
-~~~~~~~~~~~~~~~~~~
-
-If any of the listeners throws an :class:`Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException`,
-the exception listener that was provided when adding secured areas to the
-firewall map will jump in.
-
-The exception listener determines what happens next, based on the arguments
-it received when it was created. It may start the authentication procedure,
-perhaps ask the user to supply their credentials again (when they have only been
-authenticated based on a "remember-me" cookie), or transform the exception
-into an :class:`Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException`,
-which will eventually result in an "HTTP/1.1 403: Access Denied" response.
-
-Entry Points
-~~~~~~~~~~~~
-
-When the user is not authenticated at all (i.e. when the token storage
-has no token yet), the firewall's entry point will be called to "start"
-the authentication process. An entry point should implement
-:class:`Symfony\\Component\\Security\\Http\\EntryPoint\\AuthenticationEntryPointInterface`,
-which has only one method: :method:`Symfony\\Component\\Security\\Http\\EntryPoint\\AuthenticationEntryPointInterface::start`.
-This method receives the current :class:`Symfony\\Component\\HttpFoundation\\Request`
-object and the exception by which the exception listener was triggered.
-The method should return a :class:`Symfony\\Component\\HttpFoundation\\Response`
-object. This could be, for instance, the page containing the login form or,
-in the case of Basic HTTP authentication, a response with a ``WWW-Authenticate``
-header, which will prompt the user to supply their username and password.
-
-Flow: Firewall, Authentication, Authorization
----------------------------------------------
-
-Hopefully you can now see a little bit about how the "flow" of the security
-context works:
-
-#. The Firewall is registered as a listener on the ``kernel.request`` event;
-#. At the beginning of the request, the Firewall checks the firewall map
- to see if any firewall should be active for this URL;
-#. If a firewall is found in the map for this URL, its listeners are notified;
-#. Each listener checks to see if the current request contains any authentication
- information - a listener may (a) authenticate a user, (b) throw an
- ``AuthenticationException``, or (c) do nothing (because there is no
- authentication information on the request);
-#. Once a user is authenticated, you'll use :doc:`/components/security/authorization`
- to deny access to certain resources.
-
-Read the next articles to find out more about :doc:`/components/security/authentication`
-and :doc:`/components/security/authorization`.
diff --git a/components/security/secure_tools.rst b/components/security/secure_tools.rst
deleted file mode 100644
index a9d6e0fec3a..00000000000
--- a/components/security/secure_tools.rst
+++ /dev/null
@@ -1,56 +0,0 @@
-Securely Generating Random Values
-=================================
-
-The Symfony Security component comes with a collection of nice utilities
-related to security. These utilities are used by Symfony, but you should
-also use them if you want to solve the problem they address.
-
-.. note::
-
- The functions described in this article were introduced in PHP 5.6 or 7.
- For older PHP versions, a polyfill is provided by the
- `Symfony Polyfill Component`_.
-
-Comparing Strings
-~~~~~~~~~~~~~~~~~
-
-The time it takes to compare two strings depends on their differences. This
-can be used by an attacker when the two strings represent a password for
-instance; it is known as a `Timing attack`_.
-
-When comparing two passwords, you should use the :phpfunction:`hash_equals`
-function::
-
- if (hash_equals($knownString, $userInput)) {
- // ...
- }
-
-Generating a Secure Random String
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Whenever you need to generate a secure random string, you are highly
-encouraged to use the :phpfunction:`random_bytes` function::
-
- $random = random_bytes(10);
-
-The function returns a random string, suitable for cryptographic use, of
-the number bytes passed as an argument (10 in the above example).
-
-.. tip::
-
- The ``random_bytes()`` function returns a binary string which may contain
- the ``\0`` character. This can cause trouble in several common scenarios,
- such as storing this value in a database or including it as part of the
- URL. The solution is to hash the value returned by ``random_bytes()`` with
- a hashing function such as :phpfunction:`md5` or :phpfunction:`sha1`.
-
-Generating a Secure Random Number
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-If you need to generate a cryptographically secure random integer, you should
-use the :phpfunction:`random_int` function::
-
- $random = random_int(1, 10);
-
-.. _`Timing attack`: https://en.wikipedia.org/wiki/Timing_attack
-.. _`Symfony Polyfill Component`: https://github.com/symfony/polyfill
diff --git a/components/semaphore.rst b/components/semaphore.rst
new file mode 100644
index 00000000000..5715b426053
--- /dev/null
+++ b/components/semaphore.rst
@@ -0,0 +1,73 @@
+The Semaphore Component
+=======================
+
+ The Semaphore Component manages `semaphores`_, a mechanism to provide
+ exclusive access to a shared resource.
+
+Installation
+------------
+
+.. code-block:: terminal
+
+ $ composer require symfony/semaphore
+
+.. include:: /components/require_autoload.rst.inc
+
+Usage
+-----
+
+In computer science, a semaphore is a variable or abstract data type used to
+control access to a common resource by multiple processes in a concurrent
+system such as a multitasking operating system. The main difference
+with :doc:`locks ` is that semaphores allow more than one process to
+access a resource, whereas locks only allow one process.
+
+Create semaphores with the :class:`Symfony\\Component\\Semaphore\\SemaphoreFactory`
+class, which in turn requires another class to manage the storage::
+
+ use Symfony\Component\Semaphore\SemaphoreFactory;
+ use Symfony\Component\Semaphore\Store\RedisStore;
+
+ $redis = new Redis();
+ $redis->connect('172.17.0.2');
+
+ $store = new RedisStore($redis);
+ $factory = new SemaphoreFactory($store);
+
+The semaphore is created by calling the
+:method:`Symfony\\Component\\Semaphore\\SemaphoreFactory::createSemaphore`
+method. Its first argument is an arbitrary string that represents the locked
+resource. Its second argument is the maximum number of processes allowed. Then, a
+call to the :method:`Symfony\\Component\\Semaphore\\SemaphoreInterface::acquire`
+method will try to acquire the semaphore::
+
+ // ...
+ $semaphore = $factory->createSemaphore('pdf-invoice-generation', 2);
+
+ if ($semaphore->acquire()) {
+ // The resource "pdf-invoice-generation" is locked.
+ // Here you can safely compute and generate the invoice.
+
+ $semaphore->release();
+ }
+
+If the semaphore can not be acquired, the method returns ``false``. The
+``acquire()`` method can be safely called repeatedly, even if the semaphore is
+already acquired.
+
+.. note::
+
+ Unlike other implementations, the Semaphore component distinguishes
+ semaphores instances even when they are created for the same resource. If a
+ semaphore has to be used by several services, they should share the same
+ ``Semaphore`` instance returned by the ``SemaphoreFactory::createSemaphore``
+ method.
+
+.. tip::
+
+ If you don't release the semaphore explicitly, it will be released
+ automatically on instance destruction. In some cases, it can be useful to
+ lock a resource across several requests. To disable the automatic release
+ behavior, set the fifth argument of the ``createSemaphore()`` method to ``false``.
+
+.. _`semaphores`: https://en.wikipedia.org/wiki/Semaphore_(programming)
diff --git a/components/serializer.rst b/components/serializer.rst
deleted file mode 100644
index f614b9b3396..00000000000
--- a/components/serializer.rst
+++ /dev/null
@@ -1,1473 +0,0 @@
-.. index::
- single: Serializer
- single: Components; Serializer
-
-The Serializer Component
-========================
-
- The Serializer component is meant to be used to turn objects into a
- specific format (XML, JSON, YAML, ...) and the other way around.
-
-In order to do so, the Serializer component follows the following schema.
-
-.. raw:: html
-
-
-
-As you can see in the picture above, an array is used as an intermediary between
-objects and serialized contents. This way, encoders will only deal with turning
-specific **formats** into **arrays** and vice versa. The same way, Normalizers
-will deal with turning specific **objects** into **arrays** and vice versa.
-
-Serialization is a complex topic. This component may not cover all your use cases out of the box,
-but it can be useful for developing tools to serialize and deserialize your objects.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/serializer
-
-.. include:: /components/require_autoload.rst.inc
-
-To use the ``ObjectNormalizer``, the :doc:`PropertyAccess component `
-must also be installed.
-
-Usage
------
-
-.. seealso::
-
- This article explains the philosophy of the Serializer and gets you familiar
- with the concepts of normalizers and encoders. The code examples assume
- that you use the Serializer as an independent component. If you are using
- the Serializer in a Symfony application, read :doc:`/serializer` after you
- finish this article.
-
-To use the Serializer component, set up the
-:class:`Symfony\\Component\\Serializer\\Serializer` specifying which encoders
-and normalizer are going to be available::
-
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\Encoder\XmlEncoder;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $encoders = [new XmlEncoder(), new JsonEncoder()];
- $normalizers = [new ObjectNormalizer()];
-
- $serializer = new Serializer($normalizers, $encoders);
-
-The preferred normalizer is the
-:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`,
-but other normalizers are available. All the examples shown below use
-the ``ObjectNormalizer``.
-
-Serializing an Object
----------------------
-
-For the sake of this example, assume the following class already
-exists in your project::
-
- namespace App\Model;
-
- class Person
- {
- private $age;
- private $name;
- private $sportsperson;
- private $createdAt;
-
- // Getters
- public function getName()
- {
- return $this->name;
- }
-
- public function getAge()
- {
- return $this->age;
- }
-
- public function getCreatedAt()
- {
- return $this->createdAt;
- }
-
- // Issers
- public function isSportsperson()
- {
- return $this->sportsperson;
- }
-
- // Setters
- public function setName($name)
- {
- $this->name = $name;
- }
-
- public function setAge($age)
- {
- $this->age = $age;
- }
-
- public function setSportsperson($sportsperson)
- {
- $this->sportsperson = $sportsperson;
- }
-
- public function setCreatedAt($createdAt)
- {
- $this->createdAt = $createdAt;
- }
- }
-
-Now, if you want to serialize this object into JSON, you only need to
-use the Serializer service created before::
-
- $person = new App\Model\Person();
- $person->setName('foo');
- $person->setAge(99);
- $person->setSportsperson(false);
-
- $jsonContent = $serializer->serialize($person, 'json');
-
- // $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null}
-
- echo $jsonContent; // or return it in a Response
-
-The first parameter of the :method:`Symfony\\Component\\Serializer\\Serializer::serialize`
-is the object to be serialized and the second is used to choose the proper encoder,
-in this case :class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder`.
-
-Deserializing an Object
------------------------
-
-You'll now learn how to do the exact opposite. This time, the information
-of the ``Person`` class would be encoded in XML format::
-
- use App\Model\Person;
-
- $data = <<
- foo
- 99
- false
-
- EOF;
-
- $person = $serializer->deserialize($data, Person::class, 'xml');
-
-In this case, :method:`Symfony\\Component\\Serializer\\Serializer::deserialize`
-needs three parameters:
-
-#. The information to be decoded
-#. The name of the class this information will be decoded to
-#. The encoder used to convert that information into an array
-
-By default, additional attributes that are not mapped to the denormalized object
-will be ignored by the Serializer component. If you prefer to throw an exception
-when this happens, set the ``AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES`` context option to
-``false`` and provide an object that implements ``ClassMetadataFactoryInterface``
-when constructing the normalizer::
-
- $data = <<
- foo
- 99
- Paris
-
- EOF;
-
- // $loader is any of the valid loaders explained later in this article
- $classMetadataFactory = new ClassMetadataFactory($loader);
- $normalizer = new ObjectNormalizer($classMetadataFactory);
- $serializer = new Serializer([$normalizer]);
-
- // this will throw a Symfony\Component\Serializer\Exception\ExtraAttributesException
- // because "city" is not an attribute of the Person class
- $person = $serializer->deserialize($data, 'App\Model\Person', 'xml', [
- AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false,
- ]);
-
-Deserializing in an Existing Object
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The serializer can also be used to update an existing object::
-
- // ...
- $person = new Person();
- $person->setName('bar');
- $person->setAge(99);
- $person->setSportsperson(true);
-
- $data = <<
- foo
- 69
-
- EOF;
-
- $serializer->deserialize($data, Person::class, 'xml', [AbstractNormalizer::OBJECT_TO_POPULATE => $person]);
- // $person = App\Model\Person(name: 'foo', age: '69', sportsperson: true)
-
-This is a common need when working with an ORM.
-
-The ``AbstractNormalizer::OBJECT_TO_POPULATE`` is only used for the top level object. If that object
-is the root of a tree structure, all child elements that exist in the
-normalized data will be re-created with new instances.
-
-When the ``AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE`` option is set to
-true, existing children of the root ``OBJECT_TO_POPULATE`` are updated from the
-normalized data, instead of the denormalizer re-creating them. Note that
-``DEEP_OBJECT_TO_POPULATE`` only works for single child objects, but not for
-arrays of objects. Those will still be replaced when present in the normalized
-data.
-
-.. _component-serializer-attributes-groups:
-
-Attributes Groups
------------------
-
-Sometimes, you want to serialize different sets of attributes from your
-entities. Groups are a handy way to achieve this need.
-
-Assume you have the following plain-old-PHP object::
-
- namespace Acme;
-
- class MyObj
- {
- public $foo;
-
- private $bar;
-
- public function getBar()
- {
- return $this->bar;
- }
-
- public function setBar($bar)
- {
- return $this->bar = $bar;
- }
- }
-
-The definition of serialization can be specified using annotations, XML
-or YAML. The :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory`
-that will be used by the normalizer must be aware of the format to use.
-
-The following code shows how to initialize the :class:`Symfony\\Component\\Serializer\\Mapping\\Factory\\ClassMetadataFactory`
-for each format:
-
-* Annotations in PHP files::
-
- use Doctrine\Common\Annotations\AnnotationReader;
- use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
- use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
-
- $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
-
-* YAML files::
-
- use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
- use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader;
-
- $classMetadataFactory = new ClassMetadataFactory(new YamlFileLoader('/path/to/your/definition.yaml'));
-
-* XML files::
-
- use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
- use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader;
-
- $classMetadataFactory = new ClassMetadataFactory(new XmlFileLoader('/path/to/your/definition.xml'));
-
-.. _component-serializer-attributes-groups-annotations:
-
-Then, create your groups definition:
-
-.. configuration-block::
-
- .. code-block:: php-annotations
-
- namespace Acme;
-
- use Symfony\Component\Serializer\Annotation\Groups;
-
- class MyObj
- {
- /**
- * @Groups({"group1", "group2"})
- */
- public $foo;
-
- /**
- * @Groups("group3")
- */
- public function getBar() // is* methods are also supported
- {
- return $this->bar;
- }
-
- // ...
- }
-
- .. code-block:: yaml
-
- Acme\MyObj:
- attributes:
- foo:
- groups: ['group1', 'group2']
- bar:
- groups: ['group3']
-
- .. code-block:: xml
-
-
-
-
-
- group1
- group2
-
-
-
- group3
-
-
-
-
-You are now able to serialize only attributes in the groups you want::
-
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $obj = new MyObj();
- $obj->foo = 'foo';
- $obj->setBar('bar');
-
- $normalizer = new ObjectNormalizer($classMetadataFactory);
- $serializer = new Serializer([$normalizer]);
-
- $data = $serializer->normalize($obj, null, ['groups' => 'group1']);
- // $data = ['foo' => 'foo'];
-
- $obj2 = $serializer->denormalize(
- ['foo' => 'foo', 'bar' => 'bar'],
- 'MyObj',
- null,
- ['groups' => ['group1', 'group3']]
- );
- // $obj2 = MyObj(foo: 'foo', bar: 'bar')
-
-.. _ignoring-attributes-when-serializing:
-
-Selecting Specific Attributes
------------------------------
-
-It is also possible to serialize only a set of specific attributes::
-
- use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- class User
- {
- public $familyName;
- public $givenName;
- public $company;
- }
-
- class Company
- {
- public $name;
- public $address;
- }
-
- $company = new Company();
- $company->name = 'Les-Tilleuls.coop';
- $company->address = 'Lille, France';
-
- $user = new User();
- $user->familyName = 'Dunglas';
- $user->givenName = 'Kévin';
- $user->company = $company;
-
- $serializer = new Serializer([new ObjectNormalizer()]);
-
- $data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]);
- // $data = ['familyName' => 'Dunglas', 'company' => ['name' => 'Les-Tilleuls.coop']];
-
-Only attributes that are not ignored (see below) are available.
-If some serialization groups are set, only attributes allowed by those groups can be used.
-
-As for groups, attributes can be selected during both the serialization and deserialization process.
-
-Ignoring Attributes
--------------------
-
-As an option, there's a way to ignore attributes from the origin object.
-To remove those attributes provide an array via the ``AbstractNormalizer::IGNORED_ATTRIBUTES``
-key in the ``context`` parameter of the desired serializer method::
-
- use Acme\Person;
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $person = new Person();
- $person->setName('foo');
- $person->setAge(99);
-
- $normalizer = new ObjectNormalizer();
- $encoder = new JsonEncoder();
-
- $serializer = new Serializer([$normalizer], [$encoder]);
- $serializer->serialize($person, 'json', [AbstractNormalizer::IGNORED_ATTRIBUTES => ['age']]); // Output: {"name":"foo"}
-
-.. _component-serializer-converting-property-names-when-serializing-and-deserializing:
-
-Converting Property Names when Serializing and Deserializing
-------------------------------------------------------------
-
-Sometimes serialized attributes must be named differently than properties
-or getter/setter methods of PHP classes.
-
-The Serializer component provides a handy way to translate or map PHP field
-names to serialized names: The Name Converter System.
-
-Given you have the following object::
-
- class Company
- {
- public $name;
- public $address;
- }
-
-And in the serialized form, all attributes must be prefixed by ``org_`` like
-the following::
-
- {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}
-
-A custom name converter can handle such cases::
-
- use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
-
- class OrgPrefixNameConverter implements NameConverterInterface
- {
- public function normalize($propertyName)
- {
- return 'org_'.$propertyName;
- }
-
- public function denormalize($propertyName)
- {
- // removes 'org_' prefix
- return 'org_' === substr($propertyName, 0, 4) ? substr($propertyName, 4) : $propertyName;
- }
- }
-
-The custom name converter can be used by passing it as second parameter of any
-class extending :class:`Symfony\\Component\\Serializer\\Normalizer\\AbstractNormalizer`,
-including :class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer`
-and :class:`Symfony\\Component\\Serializer\\Normalizer\\PropertyNormalizer`::
-
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $nameConverter = new OrgPrefixNameConverter();
- $normalizer = new ObjectNormalizer(null, $nameConverter);
-
- $serializer = new Serializer([$normalizer], [new JsonEncoder()]);
-
- $company = new Company();
- $company->name = 'Acme Inc.';
- $company->address = '123 Main Street, Big City';
-
- $json = $serializer->serialize($company, 'json');
- // {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}
- $companyCopy = $serializer->deserialize($json, Company::class, 'json');
- // Same data as $company
-
-.. note::
-
- You can also implement
- :class:`Symfony\\Component\\Serializer\\NameConverter\\AdvancedNameConverterInterface`
- to access to the current class name, format and context.
-
-.. _using-camelized-method-names-for-underscored-attributes:
-
-CamelCase to snake_case
-~~~~~~~~~~~~~~~~~~~~~~~
-
-In many formats, it's common to use underscores to separate words (also known
-as snake_case). However, in Symfony applications is common to use CamelCase to
-name properties (even though the `PSR-1 standard`_ doesn't recommend any
-specific case for property names).
-
-Symfony provides a built-in name converter designed to transform between
-snake_case and CamelCased styles during serialization and deserialization
-processes::
-
- use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
-
- $normalizer = new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter());
-
- class Person
- {
- private $firstName;
-
- public function __construct($firstName)
- {
- $this->firstName = $firstName;
- }
-
- public function getFirstName()
- {
- return $this->firstName;
- }
- }
-
- $kevin = new Person('Kévin');
- $normalizer->normalize($kevin);
- // ['first_name' => 'Kévin'];
-
- $anne = $normalizer->denormalize(['first_name' => 'Anne'], 'Person');
- // Person object with firstName: 'Anne'
-
-Configure name conversion using metadata
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When using this component inside a Symfony application and the class metadata
-factory is enabled as explained in the :ref:`Attributes Groups section `,
-this is already set up and you only need to provide the configuration. Otherwise::
-
- // ...
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
-
- $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
-
- $serializer = new Serializer(
- [new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)],
- ['json' => new JsonEncoder()]
- );
-
-Now configure your name conversion mapping. Consider an application that
-defines a ``Person`` entity with a ``firstName`` property:
-
-.. configuration-block::
-
- .. code-block:: php-annotations
-
- namespace App\Entity;
-
- use Symfony\Component\Serializer\Annotation\SerializedName;
-
- class Person
- {
- /**
- * @SerializedName("customer_name")
- */
- private $firstName;
-
- public function __construct($firstName)
- {
- $this->firstName = $firstName;
- }
-
- // ...
- }
-
- .. code-block:: yaml
-
- App\Entity\Person:
- attributes:
- firstName:
- serialized_name: customer_name
-
- .. code-block:: xml
-
-
-
-
-
-
-
-
-This custom mapping is used to convert property names when serializing and
-deserializing objects::
-
- $serialized = $serializer->serialize(new Person("Kévin"));
- // {"customer_name": "Kévin"}
-
-Serializing Boolean Attributes
-------------------------------
-
-If you are using isser methods (methods prefixed by ``is``, like
-``App\Model\Person::isSportsperson()``), the Serializer component will
-automatically detect and use it to serialize related attributes.
-
-The ``ObjectNormalizer`` also takes care of methods starting with ``has``, ``add``
-and ``remove``.
-
-Using Callbacks to Serialize Properties with Object Instances
--------------------------------------------------------------
-
-When serializing, you can set a callback to format a specific object property::
-
- use App\Model\Person;
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $encoder = new JsonEncoder();
-
- // all callback parameters are optional (you can omit the ones you don't use)
- $dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
- return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : '';
- };
-
- $defaultContext = [
- AbstractNormalizer::CALLBACKS => [
- 'createdAt' => $dateCallback,
- ],
- ];
-
- $normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
-
- $serializer = new Serializer([$normalizer], [$encoder]);
-
- $person = new Person();
- $person->setName('cordoval');
- $person->setAge(34);
- $person->setCreatedAt(new \DateTime('now'));
-
- $serializer->serialize($person, 'json');
- // Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
-
-.. _component-serializer-normalizers:
-
-Normalizers
------------
-
-There are several types of normalizers available:
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`
- This normalizer leverages the :doc:`PropertyAccess Component `
- to read and write in the object. It means that it can access to properties
- directly and through getters, setters, hassers, adders and removers. It supports
- calling the constructor during the denormalization process.
-
- Objects are normalized to a map of property names and values (names are
- generated removing the ``get``, ``set``, ``has``, ``is`` or ``remove`` prefix from
- the method name and transforming the first letter to lowercase; e.g.
- ``getFirstName()`` -> ``firstName``).
-
- The ``ObjectNormalizer`` is the most powerful normalizer. It is configured by
- default in Symfony applications with the Serializer component enabled.
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer`
- This normalizer reads the content of the class by calling the "getters"
- (public methods starting with "get"). It will denormalize data by calling
- the constructor and the "setters" (public methods starting with "set").
-
- Objects are normalized to a map of property names and values (names are
- generated removing the ``get`` prefix from the method name and transforming
- the first letter to lowercase; e.g. ``getFirstName()`` -> ``firstName``).
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\PropertyNormalizer`
- This normalizer directly reads and writes public properties as well as
- **private and protected** properties (from both the class and all of its
- parent classes). It supports calling the constructor during the denormalization process.
-
- Objects are normalized to a map of property names to property values.
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\JsonSerializableNormalizer`
- This normalizer works with classes that implement :phpclass:`JsonSerializable`.
-
- It will call the :phpmethod:`JsonSerializable::jsonSerialize` method and
- then further normalize the result. This means that nested
- :phpclass:`JsonSerializable` classes will also be normalized.
-
- This normalizer is particularly helpful when you want to gradually migrate
- from an existing codebase using simple :phpfunction:`json_encode` to the Symfony
- Serializer by allowing you to mix which normalizers are used for which classes.
-
- Unlike with :phpfunction:`json_encode` circular references can be handled.
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer`
- This normalizer converts :phpclass:`DateTimeInterface` objects (e.g.
- :phpclass:`DateTime` and :phpclass:`DateTimeImmutable`) into strings.
- By default, it uses the `RFC3339`_ format.
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\DateTimeZoneNormalizer`
- This normalizer converts :phpclass:`DateTimeZone` objects into strings that
- represent the name of the timezone according to the `list of PHP timezones`_.
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\DataUriNormalizer`
- This normalizer converts :phpclass:`SplFileInfo` objects into a data URI
- string (``data:...``) such that files can be embedded into serialized data.
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\DateIntervalNormalizer`
- This normalizer converts :phpclass:`DateInterval` objects into strings.
- By default, it uses the ``P%yY%mM%dDT%hH%iM%sS`` format.
-
-:class:`Symfony\\Component\\Serializer\\Normalizer\\ConstraintViolationListNormalizer`
- This normalizer converts objects that implement
- :class:`Symfony\\Component\\Validator\\ConstraintViolationListInterface`
- into a list of errors according to the `RFC 7807`_ standard.
-
-.. _component-serializer-encoders:
-
-Encoders
---------
-
-Encoders turn **arrays** into **formats** and vice versa. They implement
-:class:`Symfony\\Component\\Serializer\\Encoder\\EncoderInterface`
-for encoding (array to format) and
-:class:`Symfony\\Component\\Serializer\\Encoder\\DecoderInterface` for decoding
-(format to array).
-
-You can add new encoders to a Serializer instance by using its second constructor argument::
-
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\Encoder\XmlEncoder;
- use Symfony\Component\Serializer\Serializer;
-
- $encoders = [new XmlEncoder(), new JsonEncoder()];
- $serializer = new Serializer([], $encoders);
-
-Built-in Encoders
-~~~~~~~~~~~~~~~~~
-
-The Serializer component provides several built-in encoders:
-
-:class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder`
- This class encodes and decodes data in `JSON`_.
-
-:class:`Symfony\\Component\\Serializer\\Encoder\\XmlEncoder`
- This class encodes and decodes data in `XML`_.
-
-:class:`Symfony\\Component\\Serializer\\Encoder\\YamlEncoder`
- This encoder encodes and decodes data in `YAML`_. This encoder requires the
- :doc:`Yaml Component `.
-
-:class:`Symfony\\Component\\Serializer\\Encoder\\CsvEncoder`
- This encoder encodes and decodes data in `CSV`_.
-
-All these encoders are enabled by default when using the Serializer component
-in a Symfony application.
-
-The ``JsonEncoder``
-~~~~~~~~~~~~~~~~~~~
-
-The ``JsonEncoder`` encodes to and decodes from JSON strings, based on the PHP
-:phpfunction:`json_encode` and :phpfunction:`json_decode` functions.
-
-The ``CsvEncoder``
-~~~~~~~~~~~~~~~~~~~
-
-The ``CsvEncoder`` encodes to and decodes from CSV.
-
-You can pass the context key ``as_collection`` in order to have the results
-always as a collection.
-
-The ``XmlEncoder``
-~~~~~~~~~~~~~~~~~~
-
-This encoder transforms arrays into XML and vice versa.
-
-For example, take an object normalized as following::
-
- ['foo' => [1, 2], 'bar' => true];
-
-The ``XmlEncoder`` will encode this object like that::
-
-
-
- 1
- 2
- 1
-
-
-Be aware that this encoder will consider keys beginning with ``@`` as attributes, and will use
-the key ``#comment`` for encoding XML comments::
-
- $encoder = new XmlEncoder();
- $encoder->encode([
- 'foo' => ['@bar' => 'value'],
- 'qux' => ['#comment' => 'A comment'],
- ], 'xml');
- // will return:
- //
- //
- //
- //
- //
-
-You can pass the context key ``as_collection`` in order to have the results
-always as a collection.
-
-.. tip::
-
- XML comments are ignored by default when decoding contents, but this
- behavior can be changed with the optional ``$decoderIgnoredNodeTypes`` argument of
- the ``XmlEncoder`` class constructor.
-
- Data with ``#comment`` keys are encoded to XML comments by default. This can be
- changed with the optional ``$encoderIgnoredNodeTypes`` argument of the
- ``XmlEncoder`` class constructor.
-
-The ``YamlEncoder``
-~~~~~~~~~~~~~~~~~~~
-
-This encoder requires the :doc:`Yaml Component ` and
-transforms from and to Yaml.
-
-Skipping ``null`` Values
-------------------------
-
-By default, the Serializer will preserve properties containing a ``null`` value.
-You can change this behavior by setting the ``AbstractObjectNormalizer::SKIP_NULL_VALUES`` context option
-to ``true``::
-
- $dummy = new class {
- public $foo;
- public $bar = 'notNull';
- };
-
- $normalizer = new ObjectNormalizer();
- $result = $normalizer->normalize($dummy, 'json', [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]);
- // ['bar' => 'notNull']
-
-.. _component-serializer-handling-circular-references:
-
-Handling Circular References
-----------------------------
-
-Circular references are common when dealing with entity relations::
-
- class Organization
- {
- private $name;
- private $members;
-
- public function setName($name)
- {
- $this->name = $name;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function setMembers(array $members)
- {
- $this->members = $members;
- }
-
- public function getMembers()
- {
- return $this->members;
- }
- }
-
- class Member
- {
- private $name;
- private $organization;
-
- public function setName($name)
- {
- $this->name = $name;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function setOrganization(Organization $organization)
- {
- $this->organization = $organization;
- }
-
- public function getOrganization()
- {
- return $this->organization;
- }
- }
-
-To avoid infinite loops, :class:`Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer`
-or :class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`
-throw a :class:`Symfony\\Component\\Serializer\\Exception\\CircularReferenceException`
-when such a case is encountered::
-
- $member = new Member();
- $member->setName('Kévin');
-
- $organization = new Organization();
- $organization->setName('Les-Tilleuls.coop');
- $organization->setMembers([$member]);
-
- $member->setOrganization($organization);
-
- echo $serializer->serialize($organization, 'json'); // Throws a CircularReferenceException
-
-The key ``circular_reference_limit`` in the default context sets the number of
-times it will serialize the same object before considering it a circular
-reference. The default value is ``1``.
-
-Instead of throwing an exception, circular references can also be handled
-by custom callables. This is especially useful when serializing entities
-having unique identifiers::
-
- $encoder = new JsonEncoder();
- $defaultContext = [
- AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object, $format, $context) {
- return $object->getName();
- },
- ];
- $normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext);
-
- $serializer = new Serializer([$normalizer], [$encoder]);
- var_dump($serializer->serialize($org, 'json'));
- // {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]}
-
-Handling Serialization Depth
-----------------------------
-
-The Serializer component is able to detect and limit the serialization depth.
-It is especially useful when serializing large trees. Assume the following data
-structure::
-
- namespace Acme;
-
- class MyObj
- {
- public $foo;
-
- /**
- * @var self
- */
- public $child;
- }
-
- $level1 = new MyObj();
- $level1->foo = 'level1';
-
- $level2 = new MyObj();
- $level2->foo = 'level2';
- $level1->child = $level2;
-
- $level3 = new MyObj();
- $level3->foo = 'level3';
- $level2->child = $level3;
-
-The serializer can be configured to set a maximum depth for a given property.
-Here, we set it to 2 for the ``$child`` property:
-
-.. configuration-block::
-
- .. code-block:: php-annotations
-
- namespace Acme;
-
- use Symfony\Component\Serializer\Annotation\MaxDepth;
-
- class MyObj
- {
- /**
- * @MaxDepth(2)
- */
- public $child;
-
- // ...
- }
-
- .. code-block:: yaml
-
- Acme\MyObj:
- attributes:
- child:
- max_depth: 2
-
- .. code-block:: xml
-
-
-
-
-
-
-
-
-The metadata loader corresponding to the chosen format must be configured in
-order to use this feature. It is done automatically when using the Serializer component
-in a Symfony application. When using the standalone component, refer to
-:ref:`the groups documentation ` to
-learn how to do that.
-
-The check is only done if the ``AbstractObjectNormalizer::ENABLE_MAX_DEPTH`` key of the serializer context
-is set to ``true``. In the following example, the third level is not serialized
-because it is deeper than the configured maximum depth of 2::
-
- $result = $serializer->normalize($level1, null, [AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true]);
- /*
- $result = [
- 'foo' => 'level1',
- 'child' => [
- 'foo' => 'level2',
- 'child' => [
- 'child' => null,
- ],
- ],
- ];
- */
-
-Instead of throwing an exception, a custom callable can be executed when the
-maximum depth is reached. This is especially useful when serializing entities
-having unique identifiers::
-
- use Doctrine\Common\Annotations\AnnotationReader;
- use Symfony\Component\Serializer\Annotation\MaxDepth;
- use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
- use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
- use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- class Foo
- {
- public $id;
-
- /**
- * @MaxDepth(1)
- */
- public $child;
- }
-
- $level1 = new Foo();
- $level1->id = 1;
-
- $level2 = new Foo();
- $level2->id = 2;
- $level1->child = $level2;
-
- $level3 = new Foo();
- $level3->id = 3;
- $level2->child = $level3;
-
- $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
-
- // all callback parameters are optional (you can omit the ones you don't use)
- $maxDepthHandler = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
- return '/foos/'.$innerObject->id;
- };
-
- $defaultContext = [
- AbstractObjectNormalizer::MAX_DEPTH_HANDLER => $maxDepthHandler,
- ];
- $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext);
-
- $serializer = new Serializer([$normalizer]);
-
- $result = $serializer->normalize($level1, null, [AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true]);
- /*
- $result = [
- 'id' => 1,
- 'child' => [
- 'id' => 2,
- 'child' => '/foos/3',
- ],
- ];
- */
-
-Handling Arrays
----------------
-
-The Serializer component is capable of handling arrays of objects as well.
-Serializing arrays works just like serializing a single object::
-
- use Acme\Person;
-
- $person1 = new Person();
- $person1->setName('foo');
- $person1->setAge(99);
- $person1->setSportsman(false);
-
- $person2 = new Person();
- $person2->setName('bar');
- $person2->setAge(33);
- $person2->setSportsman(true);
-
- $persons = [$person1, $person2];
- $data = $serializer->serialize($persons, 'json');
-
- // $data contains [{"name":"foo","age":99,"sportsman":false},{"name":"bar","age":33,"sportsman":true}]
-
-If you want to deserialize such a structure, you need to add the
-:class:`Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer`
-to the set of normalizers. By appending ``[]`` to the type parameter of the
-:method:`Symfony\\Component\\Serializer\\Serializer::deserialize` method,
-you indicate that you're expecting an array instead of a single object::
-
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
- use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $serializer = new Serializer(
- [new GetSetMethodNormalizer(), new ArrayDenormalizer()],
- [new JsonEncoder()]
- );
-
- $data = ...; // The serialized data from the previous example
- $persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');
-
-The ``XmlEncoder``
-------------------
-
-This encoder transforms arrays into XML and vice versa. For example, take an
-object normalized as following::
-
- ['foo' => [1, 2], 'bar' => true];
-
-The ``XmlEncoder`` encodes this object as follows:
-
-.. code-block:: xml
-
-
-
- 1
- 2
- 1
-
-
-The array keys beginning with ``@`` are considered XML attributes::
-
- ['foo' => ['@bar' => 'value']];
-
- // is encoded as follows:
- //
- //
- //
- //
-
-Use the special ``#`` key to define the data of a node::
-
- ['foo' => ['@bar' => 'value', '#' => 'baz']];
-
- // is encoded as follows:
- //
- //
- //
- // baz
- //
- //
-
-Context
-~~~~~~~
-
-The ``encode()`` method defines a third optional parameter called ``context``
-which defines the configuration options for the XmlEncoder an associative array::
-
- $xmlEncoder->encode($array, 'xml', $context);
-
-These are the options available:
-
-``xml_format_output``
- If set to true, formats the generated XML with line breaks and indentation.
-
-``xml_version``
- Sets the XML version attribute (default: ``1.1``).
-
-``xml_encoding``
- Sets the XML encoding attribute (default: ``utf-8``).
-
-``xml_standalone``
- Adds standalone attribute in the generated XML (default: ``true``).
-
-``xml_root_node_name``
- Sets the root node name (default: ``response``).
-
-``remove_empty_tags``
- If set to true, removes all empty tags in the generated XML.
-
-Handling Constructor Arguments
-------------------------------
-
-If the class constructor defines arguments, as usually happens with
-`Value Objects`_, the serializer won't be able to create the object if some
-arguments are missing. In those cases, use the ``default_constructor_arguments``
-context option::
-
- use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- class MyObj
- {
- private $foo;
- private $bar;
-
- public function __construct($foo, $bar)
- {
- $this->foo = $foo;
- $this->bar = $bar;
- }
- }
-
- $normalizer = new ObjectNormalizer($classMetadataFactory);
- $serializer = new Serializer([$normalizer]);
-
- $data = $serializer->denormalize(
- ['foo' => 'Hello'],
- 'MyObj',
- [AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => [
- 'MyObj' => ['foo' => '', 'bar' => ''],
- ]]
- );
- // $data = new MyObj('Hello', '');
-
-Recursive Denormalization and Type Safety
------------------------------------------
-
-The Serializer component can use the :doc:`PropertyInfo Component ` to denormalize
-complex types (objects). The type of the class' property will be guessed using the provided
-extractor and used to recursively denormalize the inner data.
-
-When using this component in a Symfony application, all normalizers are automatically configured to use the registered extractors.
-When using the component standalone, an implementation of :class:`Symfony\\Component\\PropertyInfo\\PropertyTypeExtractorInterface`,
-(usually an instance of :class:`Symfony\\Component\\PropertyInfo\\PropertyInfoExtractor`) must be passed as the 4th
-parameter of the ``ObjectNormalizer``::
-
- namespace Acme;
-
- use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
- use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- class ObjectOuter
- {
- private $inner;
- private $date;
-
- public function getInner()
- {
- return $this->inner;
- }
-
- public function setInner(ObjectInner $inner)
- {
- $this->inner = $inner;
- }
-
- public function setDate(\DateTimeInterface $date)
- {
- $this->date = $date;
- }
-
- public function getDate()
- {
- return $this->date;
- }
- }
-
- class ObjectInner
- {
- public $foo;
- public $bar;
- }
-
- $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
- $serializer = new Serializer([new DateTimeNormalizer(), $normalizer]);
-
- $obj = $serializer->denormalize(
- ['inner' => ['foo' => 'foo', 'bar' => 'bar'], 'date' => '1988/01/21'],
- 'Acme\ObjectOuter'
- );
-
- dump($obj->getInner()->foo); // 'foo'
- dump($obj->getInner()->bar); // 'bar'
- dump($obj->getDate()->format('Y-m-d')); // '1988-01-21'
-
-When a ``PropertyTypeExtractor`` is available, the normalizer will also check that the data to denormalize
-matches the type of the property (even for primitive types). For instance, if a ``string`` is provided, but
-the type of the property is ``int``, an :class:`Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException`
-will be thrown. The type enforcement of the properties can be disabled by setting
-the serializer context option ``ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT``
-to ``true``.
-
-Serializing Interfaces and Abstract Classes
--------------------------------------------
-
-When dealing with objects that are fairly similar or share properties, you may
-use interfaces or abstract classes. The Serializer component allows you to
-serialize and deserialize these objects using a *"discriminator class mapping"*.
-
-The discriminator is the field (in the serialized string) used to differentiate
-between the possible objects. In practice, when using the Serializer component,
-pass a :class:`Symfony\\Component\\Serializer\\Mapping\\ClassDiscriminatorResolverInterface`
-implementation to the :class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`.
-
-The Serializer component provides an implementation of ``ClassDiscriminatorResolverInterface``
-called :class:`Symfony\\Component\\Serializer\\Mapping\\ClassDiscriminatorFromClassMetadata`
-which uses the class metadata factory and a mapping configuration to serialize
-and deserialize objects of the correct class.
-
-When using this component inside a Symfony application and the class metadata factory is enabled
-as explained in the :ref:`Attributes Groups section `,
-this is already set up and you only need to provide the configuration. Otherwise::
-
- // ...
- use Symfony\Component\Serializer\Encoder\JsonEncoder;
- use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
- use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
- use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
- use Symfony\Component\Serializer\Serializer;
-
- $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
-
- $discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory);
-
- $serializer = new Serializer(
- [new ObjectNormalizer($classMetadataFactory, null, null, null, $discriminator)],
- ['json' => new JsonEncoder()]
- );
-
-Now configure your discriminator class mapping. Consider an application that
-defines an abstract ``CodeRepository`` class extended by ``GitHubCodeRepository``
-and ``BitBucketCodeRepository`` classes:
-
-.. configuration-block::
-
- .. code-block:: php-annotations
-
- namespace App;
-
- use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
-
- /**
- * @DiscriminatorMap(typeProperty="type", mapping={
- * "github"="App\GitHubCodeRepository",
- * "bitbucket"="App\BitBucketCodeRepository"
- * })
- */
- interface CodeRepository
- {
- // ...
- }
-
- .. code-block:: yaml
-
- App\CodeRepository:
- discriminator_map:
- type_property: type
- mapping:
- github: 'App\GitHubCodeRepository'
- bitbucket: 'App\BitBucketCodeRepository'
-
- .. code-block:: xml
-
-
-
-
-
-
-
-
-
-
-
-Once configured, the serializer uses the mapping to pick the correct class::
-
- $serialized = $serializer->serialize(new GitHubCodeRepository());
- // {"type": "github"}
-
- $repository = $serializer->deserialize($serialized, CodeRepository::class, 'json');
- // instanceof GitHubCodeRepository
-
-Performance
------------
-
-To figure which normalizer (or denormalizer) must be used to handle an object,
-the :class:`Symfony\\Component\\Serializer\\Serializer` class will call the
-:method:`Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface::supportsNormalization`
-(or :method:`Symfony\\Component\\Serializer\\Normalizer\\DenormalizerInterface::supportsDenormalization`)
-of all registered normalizers (or denormalizers) in a loop.
-
-The result of these methods can vary depending on the object to serialize, the
-format and the context. That's why the result **is not cached** by default and
-can result in a significant performance bottleneck.
-
-However, most normalizers (and denormalizers) always return the same result when
-the object's type and the format are the same, so the result can be cached. To
-do so, make those normalizers (and denormalizers) implement the
-:class:`Symfony\\Component\\Serializer\\Normalizer\\CacheableSupportsMethodInterface`
-and return ``true`` when
-:method:`Symfony\\Component\\Serializer\\Normalizer\\CacheableSupportsMethodInterface::hasCacheableSupportsMethod`
-is called.
-
-.. note::
-
- All built-in :ref:`normalizers and denormalizers `
- as well the ones included in `API Platform`_ natively implement this interface.
-
-Learn more
-----------
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- /serializer
-
-.. seealso::
-
- Normalizers for the Symfony Serializer Component supporting popular web API formats
- (JSON-LD, GraphQL, OpenAPI, HAL, JSON:API) are available as part of the `API Platform`_ project.
-
-.. seealso::
-
- A popular alternative to the Symfony Serializer component is the third-party
- library, `JMS serializer`_ (versions before ``v1.12.0`` were released under
- the Apache license, so incompatible with GPLv2 projects).
-
-.. _`PSR-1 standard`: https://www.php-fig.org/psr/psr-1/
-.. _`JMS serializer`: https://github.com/schmittjoh/serializer
-.. _RFC3339: https://tools.ietf.org/html/rfc3339#section-5.8
-.. _JSON: http://www.json.org/
-.. _XML: https://www.w3.org/XML/
-.. _YAML: http://yaml.org/
-.. _CSV: https://tools.ietf.org/html/rfc4180
-.. _`RFC 7807`: https://tools.ietf.org/html/rfc7807
-.. _`Value Objects`: https://en.wikipedia.org/wiki/Value_object
-.. _`API Platform`: https://api-platform.com
-.. _`list of PHP timezones`: https://www.php.net/manual/en/timezones.php
diff --git a/components/stopwatch.rst b/components/stopwatch.rst
deleted file mode 100644
index 4f6c8dc0420..00000000000
--- a/components/stopwatch.rst
+++ /dev/null
@@ -1,121 +0,0 @@
-.. index::
- single: Stopwatch
- single: Components; Stopwatch
-
-The Stopwatch Component
-=======================
-
- The Stopwatch component provides a way to profile code.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/stopwatch
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-The Stopwatch component provides a consistent way to measure execution
-time of certain parts of code so that you don't constantly have to parse
-:phpfunction:`microtime` by yourself. Instead, use the
-:class:`Symfony\\Component\\Stopwatch\\Stopwatch` class::
-
- use Symfony\Component\Stopwatch\Stopwatch;
-
- $stopwatch = new Stopwatch();
- // starts event named 'eventName'
- $stopwatch->start('eventName');
- // ... some code goes here
- $event = $stopwatch->stop('eventName');
-
-The :class:`Symfony\\Component\\Stopwatch\\StopwatchEvent` object can be retrieved
-from the :method:`Symfony\\Component\\Stopwatch\\Stopwatch::start`,
-:method:`Symfony\\Component\\Stopwatch\\Stopwatch::stop`,
-:method:`Symfony\\Component\\Stopwatch\\Stopwatch::lap` and
-:method:`Symfony\\Component\\Stopwatch\\Stopwatch::getEvent` methods.
-The latter should be used when you need to retrieve the duration of an event
-while it is still running.
-
-.. tip::
-
- By default, the stopwatch truncates any sub-millisecond time measure to ``0``,
- so you can't measure microseconds or nanoseconds. If you need more precision,
- pass ``true`` to the ``Stopwatch`` class constructor to enable full precision::
-
- $stopwatch = new Stopwatch(true);
-
-The stopwatch can be reset to its original state at any given time with the
-:method:`Symfony\\Component\\Stopwatch\\Stopwatch::reset` method, which deletes
-all the data measured so far.
-
-You can also provide a category name to an event::
-
- $stopwatch->start('eventName', 'categoryName');
-
-You can consider categories as a way of tagging events. For example, the
-Symfony Profiler tool uses categories to nicely color-code different events.
-
-.. tip::
-
- Read :ref:`this article ` to learn more about
- integrating the Stopwatch component into the Symfony profiler.
-
-Periods
--------
-
-As you know from the real world, all stopwatches come with two buttons:
-one to start and stop the stopwatch, and another to measure the lap time.
-This is exactly what the :method:`Symfony\\Component\\Stopwatch\\Stopwatch::lap`
-method does::
-
- $stopwatch = new Stopwatch();
- // starts event named 'foo'
- $stopwatch->start('foo');
- // ... some code goes here
- $stopwatch->lap('foo');
- // ... some code goes here
- $stopwatch->lap('foo');
- // ... some other code goes here
- $event = $stopwatch->stop('foo');
-
-Lap information is stored as "periods" within the event. To get lap information
-call::
-
- $event->getPeriods();
-
-In addition to periods, you can get other useful information from the event object.
-For example::
-
- $event->getCategory(); // returns the category the event was started in
- $event->getOrigin(); // returns the event start time in milliseconds
- $event->ensureStopped(); // stops all periods not already stopped
- $event->getStartTime(); // returns the start time of the very first period
- $event->getEndTime(); // returns the end time of the very last period
- $event->getDuration(); // returns the event duration, including all periods
- $event->getMemory(); // returns the max memory usage of all periods
-
-Sections
---------
-
-Sections are a way to logically split the timeline into groups. You can see
-how Symfony uses sections to nicely visualize the framework lifecycle in the
-Symfony Profiler tool. Here is a basic usage example using sections::
-
- $stopwatch = new Stopwatch();
-
- $stopwatch->openSection();
- $stopwatch->start('parsing_config_file', 'filesystem_operations');
- $stopwatch->stopSection('routing');
-
- $events = $stopwatch->getSectionEvents('routing');
-
-You can reopen a closed section by calling the :method:`Symfony\\Component\\Stopwatch\\Stopwatch::openSection`
-method and specifying the id of the section to be reopened::
-
- $stopwatch->openSection('routing');
- $stopwatch->start('building_config_tree');
- $stopwatch->stopSection('routing');
diff --git a/components/templating.rst b/components/templating.rst
deleted file mode 100644
index a104ea3e1d8..00000000000
--- a/components/templating.rst
+++ /dev/null
@@ -1,215 +0,0 @@
-.. index::
- single: Templating
- single: Components; Templating
-
-The Templating Component
-========================
-
- The Templating component provides all the tools needed to build any kind
- of template system.
-
- It provides an infrastructure to load template files and optionally
- monitor them for changes. It also provides a concrete template engine
- implementation using PHP with additional tools for escaping and separating
- templates into blocks and layouts.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/templating
-
-.. include:: /components/require_autoload.rst.inc
-
-Usage
------
-
-.. seealso::
-
- This article explains how to use the Templating features as an independent
- component in any PHP application. Read the article about :doc:`templates `
- to learn about how to work with templates in Symfony applications.
-
-The :class:`Symfony\\Component\\Templating\\PhpEngine` class is the entry point
-of the component. It needs a
-template name parser (:class:`Symfony\\Component\\Templating\\TemplateNameParserInterface`)
-to convert a template name to a
-template reference (:class:`Symfony\\Component\\Templating\\TemplateReferenceInterface`).
-It also needs a template loader (:class:`Symfony\\Component\\Templating\\Loader\\LoaderInterface`)
-which uses the template reference to actually find and load the template::
-
- use Symfony\Component\Templating\Loader\FilesystemLoader;
- use Symfony\Component\Templating\PhpEngine;
- use Symfony\Component\Templating\TemplateNameParser;
-
- $filesystemLoader = new FilesystemLoader(__DIR__.'/views/%name%');
-
- $templating = new PhpEngine(new TemplateNameParser(), $filesystemLoader);
-
- echo $templating->render('hello.php', ['firstname' => 'Fabien']);
-
-.. code-block:: html+php
-
-
- Hello, = $firstname ?>!
-
-The :method:`Symfony\\Component\\Templating\\PhpEngine::render` method parses
-the ``views/hello.php`` file and returns the output text. The second argument
-of ``render`` is an array of variables to use in the template. In this
-example, the result will be ``Hello, Fabien!``.
-
-.. note::
-
- Templates will be cached in the memory of the engine. This means that if
- you render the same template multiple times in the same request, the
- template will only be loaded once from the file system.
-
-The ``$view`` Variable
-----------------------
-
-In all templates parsed by the ``PhpEngine``, you get access to a mysterious
-variable called ``$view``. That variable holds the current ``PhpEngine``
-instance. That means you get access to a bunch of methods that make your life
-easier.
-
-Including Templates
--------------------
-
-The best way to share a snippet of template code is to create a template that
-can then be included by other templates. As the ``$view`` variable is an
-instance of ``PhpEngine``, you can use the ``render()`` method (which was used
-to render the template originally) inside the template to render another template::
-
-
-
- = $view->render('hello.php', ['firstname' => $name]) ?>
-
-
-Global Variables
-----------------
-
-Sometimes, you need to set a variable which is available in all templates
-rendered by an engine (like the ``$app`` variable when using the Symfony
-Framework). These variables can be set by using the
-:method:`Symfony\\Component\\Templating\\PhpEngine::addGlobal` method and they
-can be accessed in the template as normal variables::
-
- $templating->addGlobal('ga_tracking', 'UA-xxxxx-x');
-
-In a template:
-
-.. code-block:: html+php
-
- The google tracking code is: = $ga_tracking ?>
-
-.. caution::
-
- The global variables cannot be called ``this`` or ``view``, since they are
- already used by the PHP engine.
-
-.. note::
-
- The global variables can be overridden by a local variable in the template
- with the same name.
-
-Output Escaping
----------------
-
-When you render variables, you should probably escape them so that HTML or
-JavaScript code isn't written out to your page. This will prevent things like
-XSS attacks. To do this, use the
-:method:`Symfony\\Component\\Templating\\PhpEngine::escape` method::
-
- = $view->escape($firstname) ?>
-
-By default, the ``escape()`` method assumes that the variable is outputted
-within an HTML context. The second argument lets you change the context. For
-example, to output something inside JavaScript, use the ``js`` context::
-
- = $view->escape($var, 'js') ?>
-
-The component comes with an HTML and JS escaper. You can register your own
-escaper using the
-:method:`Symfony\\Component\\Templating\\PhpEngine::setEscaper` method::
-
- $templating->setEscaper('css', function ($value) {
- // ... all CSS escaping
-
- return $escapedValue;
- });
-
-Helpers
--------
-
-The Templating component can be extended via helpers. Helpers are PHP objects
-that provide features useful in a template context. The component has one
-built-in helper:
-
-* :doc:`/components/templating/slotshelper`
-
-Before you can use these helpers, you need to register them using
-:method:`Symfony\\Component\\Templating\\PhpEngine::set`::
-
- use Symfony\Component\Templating\Helper\SlotsHelper;
- // ...
-
- $templating->set(new SlotsHelper());
-
-Custom Helpers
-~~~~~~~~~~~~~~
-
-You can create your own helpers by creating a class which implements
-:class:`Symfony\\Component\\Templating\\Helper\\HelperInterface`. However,
-most of the time you'll extend
-:class:`Symfony\\Component\\Templating\\Helper\\Helper`.
-
-The ``Helper`` has one required method:
-:method:`Symfony\\Component\\Templating\\Helper\\HelperInterface::getName`.
-This is the name that is used to get the helper from the ``$view`` object.
-
-Creating a Custom Engine
-------------------------
-
-Besides providing a PHP templating engine, you can also create your own engine
-using the Templating component. To do that, create a new class which
-implements the :class:`Symfony\\Component\\Templating\\EngineInterface`. This
-requires 3 method:
-
-* :method:`render($name, array $parameters = []) `
- - Renders a template
-* :method:`exists($name) `
- - Checks if the template exists
-* :method:`supports($name) `
- - Checks if the given template can be handled by this engine.
-
-Using Multiple Engines
-----------------------
-
-It is possible to use multiple engines at the same time using the
-:class:`Symfony\\Component\\Templating\\DelegatingEngine` class. This class
-takes a list of engines and acts just like a normal templating engine. The
-only difference is that it delegates the calls to one of the other engines. To
-choose which one to use for the template, the
-:method:`EngineInterface::supports() `
-method is used::
-
- use Acme\Templating\CustomEngine;
- use Symfony\Component\Templating\DelegatingEngine;
- use Symfony\Component\Templating\PhpEngine;
-
- $templating = new DelegatingEngine([
- new PhpEngine(...),
- new CustomEngine(...),
- ]);
-
-Learn More
-----------
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- /components/templating/*
- /templates
- /templating/*
diff --git a/components/templating/slotshelper.rst b/components/templating/slotshelper.rst
deleted file mode 100644
index 42c088c9fd9..00000000000
--- a/components/templating/slotshelper.rst
+++ /dev/null
@@ -1,87 +0,0 @@
-.. index::
- single: Templating Helpers; Slots Helper
-
-Slots Helper
-============
-
-More often than not, templates in a project share common elements, like the
-well-known header and footer. Using this helper, the static HTML code can
-be placed in a layout file along with "slots", which represent the dynamic
-parts that will change on a page-by-page basis. These slots are then filled
-in by different children template. In other words, the layout file decorates
-the child template.
-
-Displaying Slots
-----------------
-
-The slots are accessible by using the slots helper (``$view['slots']``). Use
-:method:`Symfony\\Component\\Templating\\Helper\\SlotsHelper::output` to
-display the content of the slot on that place:
-
-.. code-block:: html+php
-
-
-
-
-
-
- output('title', 'Default title') ?>
-
-
-
- output('_content') ?>
-
-
-
-The first argument of the method is the name of the slot. The method has an
-optional second argument, which is the default value to use if the slot is not
-available.
-
-The ``_content`` slot is a special slot set by the ``PhpEngine``. It contains
-the content of the sub-template.
-
-.. caution::
-
- If you're using the standalone component, make sure you registered the
- :class:`Symfony\\Component\\Templating\\Helper\\SlotsHelper`::
-
- use Symfony\Component\Templating\Helper\SlotsHelper;
-
- // ...
- $templateEngine->set(new SlotsHelper());
-
-Extending Templates
--------------------
-
-The :method:`Symfony\\Component\\Templating\\PhpEngine::extend` method is called in the
-sub-template to set its parent template. Then
-:method:`$view['slots']->set() `
-can be used to set the content of a slot. All content which is not explicitly
-set in a slot is in the ``_content`` slot.
-
-.. code-block:: html+php
-
-
- extend('layout.php') ?>
-
- set('title', $page->title) ?>
-
-
- = $page->title ?>
-
-
- = $page->body ?>
-
-
-.. note::
-
- Multiple levels of inheritance is possible: a layout can extend another
- layout.
-
-For large slots, there is also an extended syntax:
-
-.. code-block:: html+php
-
- start('title') ?>
- Some large amount of HTML
- stop() ?>
diff --git a/components/translation.rst b/components/translation.rst
deleted file mode 100644
index fe7ab4c3d79..00000000000
--- a/components/translation.rst
+++ /dev/null
@@ -1,236 +0,0 @@
-.. index::
- single: Translation
- single: Components; Translation
-
-The Translation Component
-=========================
-
- The Translation component provides tools to internationalize your
- application.
-
-Installation
-------------
-
-.. code-block:: terminal
-
- $ composer require symfony/translation
-
-.. include:: /components/require_autoload.rst.inc
-
-.. seealso::
-
- This article explains how to use the Translation features as an independent
- component in any PHP application. Read the :doc:`/translation` article to
- learn about how to internationalize and manage the user locale in Symfony
- applications.
-
-Constructing the Translator
----------------------------
-
-The main access point of the Translation component is
-:class:`Symfony\\Component\\Translation\\Translator`. Before you can use it,
-you need to configure it and load the messages to translate (called *message
-catalogs*).
-
-Configuration
-~~~~~~~~~~~~~
-
-The constructor of the ``Translator`` class needs one argument: The locale::
-
- use Symfony\Component\Translation\Translator;
-
- $translator = new Translator('fr_FR');
-
-.. note::
-
- The locale set here is the default locale to use. You can override this
- locale when translating strings.
-
-.. note::
-
- The term *locale* refers roughly to the user's language and country. It
- can be any string that your application uses to manage translations and
- other format differences (e.g. currency format). The `ISO 639-1`_
- *language* code, an underscore (``_``), then the `ISO 3166-1 alpha-2`_
- *country* code (e.g. ``fr_FR`` for French/France) is recommended.
-
-.. _component-translator-message-catalogs:
-
-Loading Message Catalogs
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-The messages are stored in message catalogs inside the ``Translator``
-class. A message catalog is like a dictionary of translations for a specific
-locale.
-
-The Translation component uses Loader classes to load catalogs. You can load
-multiple resources for the same locale, which will then be combined into one
-catalog.
-
-The component comes with some default Loaders and you can create your own
-Loader too. The default loaders are:
-
-* :class:`Symfony\\Component\\Translation\\Loader\\ArrayLoader` - to load
- catalogs from PHP arrays.
-* :class:`Symfony\\Component\\Translation\\Loader\\CsvFileLoader` - to load
- catalogs from CSV files.
-* :class:`Symfony\\Component\\Translation\\Loader\\IcuDatFileLoader` - to load
- catalogs from resource bundles.
-* :class:`Symfony\\Component\\Translation\\Loader\\IcuResFileLoader` - to load
- catalogs from resource bundles.
-* :class:`Symfony\\Component\\Translation\\Loader\\IniFileLoader` - to load
- catalogs from ini files.
-* :class:`Symfony\\Component\\Translation\\Loader\\MoFileLoader` - to load
- catalogs from gettext files.
-* :class:`Symfony\\Component\\Translation\\Loader\\PhpFileLoader` - to load
- catalogs from PHP files.
-* :class:`Symfony\\Component\\Translation\\Loader\\PoFileLoader` - to load
- catalogs from gettext files.
-* :class:`Symfony\\Component\\Translation\\Loader\\QtFileLoader` - to load
- catalogs from QT XML files.
-* :class:`Symfony\\Component\\Translation\\Loader\\XliffFileLoader` - to load
- catalogs from Xliff files.
-* :class:`Symfony\\Component\\Translation\\Loader\\JsonFileLoader` - to load
- catalogs from JSON files.
-* :class:`Symfony\\Component\\Translation\\Loader\\YamlFileLoader` - to load
- catalogs from Yaml files (requires the :doc:`Yaml component`).
-
-All file loaders require the :doc:`Config component `.
-
-You can also :doc:`create your own Loader `,
-in case the format is not already supported by one of the default loaders.
-
-At first, you should add one or more loaders to the ``Translator``::
-
- // ...
- $translator->addLoader('array', new ArrayLoader());
-
-The first argument is the name to which you can refer the loader in the
-translator and the second argument is an instance of the loader itself. After
-this, you can add your resources using the correct loader.
-
-Loading Messages with the ``ArrayLoader``
-.........................................
-
-Loading messages can be done by calling
-:method:`Symfony\\Component\\Translation\\Translator::addResource`. The first
-argument is the loader name (this was the first argument of the ``addLoader()``
-method), the second is the resource and the third argument is the locale::
-
- // ...
- $translator->addResource('array', [
- 'Hello World!' => 'Bonjour',
- ], 'fr_FR');
-
-Loading Messages with the File Loaders
-......................................
-
-If you use one of the file loaders, you should also use the ``addResource()``
-method. The only difference is that you should put the file name to the resource
-file as the second argument, instead of an array::
-
- // ...
- $translator->addLoader('yaml', new YamlFileLoader());
- $translator->addResource('yaml', 'path/to/messages.fr.yaml', 'fr_FR');
-
-The Translation Process
------------------------
-
-To actually translate the message, the Translator uses the following process:
-
-* A catalog of translated messages is loaded from translation resources defined
- for the ``locale`` (e.g. ``fr_FR``). Messages from the
- :ref:`components-fallback-locales` are also loaded and added to the
- catalog, if they don't already exist. The end result is a large "dictionary"
- of translations;
-
-* If the message is located in the catalog, the translation is returned. If
- not, the translator returns the original message.
-
-You start this process by calling
-:method:`Symfony\\Component\\Translation\\Translator::trans` or
-:method:`Symfony\\Component\\Translation\\Translator::transChoice`. Then, the
-Translator looks for the exact string inside the appropriate message catalog
-and returns it (if it exists).
-
-.. _components-fallback-locales:
-
-Fallback Locales
-~~~~~~~~~~~~~~~~
-
-If the message is not located in the catalog of the specific locale, the
-translator will look into the catalog of one or more fallback locales. For
-example, assume you're trying to translate into the ``es_AR`` locale:
-
-#. First, the translator looks for the translation in the ``es_AR``
- (Argentinean Spanish) locale;
-
-#. If it wasn't found, the translator looks for the translation in the parent
- locale, which is automatically defined only for some locales. In this
- example, the parent locale is ``es_419`` (Latin American Spanish);
-
-#. If it wasn't found, the translator looks for the translation in the ``es``
- (Spanish) locale;
-
-#. If the translation still isn't found, the translator uses the one or more
- fallback locales set explicitly on the translator.
-
-For (3), the fallback locales can be set by calling
-:method:`Symfony\\Component\\Translation\\Translator::setFallbackLocales`::
-
- // ...
- $translator->setFallbackLocales(['en']);
-
-.. _using-message-domains:
-
-Using Message Domains
----------------------
-
-As you've seen, message files are organized into the different locales that
-they translate. The message files can also be organized further into "domains".
-
-The domain is specified in the fourth argument of the ``addResource()``
-method. The default domain is ``messages``. For example, suppose that, for
-organization, translations were split into three different domains:
-``messages``, ``admin`` and ``navigation``. The French translation would be
-loaded like this::
-
- // ...
- $translator->addLoader('xlf', new XliffFileLoader());
-
- $translator->addResource('xlf', 'messages.fr.xlf', 'fr_FR');
- $translator->addResource('xlf', 'admin.fr.xlf', 'fr_FR', 'admin');
- $translator->addResource(
- 'xlf',
- 'navigation.fr.xlf',
- 'fr_FR',
- 'navigation'
- );
-
-When translating strings that are not in the default domain (``messages``),
-you must specify the domain as the third argument of ``trans()``::
-
- $translator->trans('Symfony is great', [], 'admin');
-
-Symfony will now look for the message in the ``admin`` domain of the
-specified locale.
-
-Usage
------
-
-Read how to use the Translation component in :doc:`/components/translation/usage`.
-
-Learn More
-----------
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- /components/translation/*
- /translation
- /translation/*
- /validation/translations
-
-.. _`ISO 3166-1 alpha-2`: https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes
-.. _`ISO 639-1`: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
diff --git a/components/translation/custom_formats.rst b/components/translation/custom_formats.rst
deleted file mode 100644
index 4795f1acc27..00000000000
--- a/components/translation/custom_formats.rst
+++ /dev/null
@@ -1,125 +0,0 @@
-.. index::
- single: Translation; Adding Custom Format Support
-
-Adding Custom Format Support
-============================
-
-Sometimes, you need to deal with custom formats for translation files. The
-Translation component is flexible enough to support this. Create a
-loader (to load translations) and, optionally, a dumper (to dump translations).
-
-Imagine that you have a custom format where translation messages are defined
-using one line for each translation and parentheses to wrap the key and the
-message. A translation file would look like this:
-
-.. code-block:: text
-
- (welcome)(accueil)
- (goodbye)(au revoir)
- (hello)(bonjour)
-
-.. _components-translation-custom-loader:
-
-Creating a Custom Loader
-------------------------
-
-To define a custom loader that is able to read these kinds of files, you must create a
-new class that implements the
-:class:`Symfony\\Component\\Translation\\Loader\\LoaderInterface`. The
-:method:`Symfony\\Component\\Translation\\Loader\\LoaderInterface::load`
-method will get a filename and parse it into an array. Then, it will
-create the catalog that will be returned::
-
- use Symfony\Component\Translation\Loader\LoaderInterface;
- use Symfony\Component\Translation\MessageCatalogue;
-
- class MyFormatLoader implements LoaderInterface
- {
- public function load($resource, $locale, $domain = 'messages')
- {
- $messages = [];
- $lines = file($resource);
-
- foreach ($lines as $line) {
- if (preg_match('/\(([^\)]+)\)\(([^\)]+)\)/', $line, $matches)) {
- $messages[$matches[1]] = $matches[2];
- }
- }
-
- $messageCatalog = new MessageCatalogue($locale);
- $messageCatalog->add($messages, $domain);
-
- return $messageCatalog;
- }
-
- }
-
-Once created, it can be used as any other loader::
-
- use Symfony\Component\Translation\Translator;
-
- $translator = new Translator('fr_FR');
- $translator->addLoader('my_format', new MyFormatLoader());
-
- $translator->addResource('my_format', __DIR__.'/translations/messages.txt', 'fr_FR');
-
- var_dump($translator->trans('welcome'));
-
-It will print *"accueil"*.
-
-.. _components-translation-custom-dumper:
-
-Creating a Custom Dumper
-------------------------
-
-It is also possible to create a custom dumper for your format, which is
-useful when using the extraction commands. To do so, a new class
-implementing the
-:class:`Symfony\\Component\\Translation\\Dumper\\DumperInterface`
-must be created. To write the dump contents into a file, extending the
-:class:`Symfony\\Component\\Translation\\Dumper\\FileDumper` class
-will save a few lines::
-
- use Symfony\Component\Translation\Dumper\FileDumper;
- use Symfony\Component\Translation\MessageCatalogue;
-
- class MyFormatDumper extends FileDumper
- {
- public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = [])
- {
- $output = '';
-
- foreach ($messages->all($domain) as $source => $target) {
- $output .= sprintf("(%s)(%s)\n", $source, $target);
- }
-
- return $output;
- }
-
- protected function getExtension()
- {
- return 'txt';
- }
- }
-
-.. sidebar:: Format a message catalog
-
- In some cases, you want to send the dump contents as a response instead of
- writing them in files. To do this, you can use the ``formatCatalogue``
- method. In this case, you must pass the domain argument, which determines
- the list of messages that should be dumped.
-
-The :method:`Symfony\\Component\\Translation\\Dumper\\FileDumper::formatCatalogue`
-method creates the output string, that will be used by the
-:method:`Symfony\\Component\\Translation\\Dumper\\FileDumper::dump` method
-of the FileDumper class to create the file. The dumper can be used like any other
-built-in dumper. In the following example, the translation messages defined in the
-YAML file are dumped into a text file with the custom format::
-
- use Symfony\Component\Translation\Loader\YamlFileLoader;
-
- $loader = new YamlFileLoader();
- $translations = $loader->load(__DIR__ . '/translations/messages.fr_FR.yaml' , 'fr_FR');
-
- $dumper = new MyFormatDumper();
- $dumper->dump($translations, ['path' => __DIR__.'/dumps']);
diff --git a/components/translation/custom_message_formatter.rst b/components/translation/custom_message_formatter.rst
deleted file mode 100644
index 81e40a4c544..00000000000
--- a/components/translation/custom_message_formatter.rst
+++ /dev/null
@@ -1,38 +0,0 @@
-.. index::
- single: Translation; Create Custom Message formatter
-
-Create a Custom Message Formatter
-=================================
-
-The default message formatter provided by Symfony solves the most common needs
-when translating messages, such as using variables and pluralization. However,
-if your needs are different, you can create your own message formatter.
-
-Message formatters are PHP classes that implement the
-:class:`Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface`::
-
-
- use Symfony\Component\Translation\Formatter\MessageFormatterInterface;
-
- class MyCustomMessageFormatter implements MessageFormatterInterface
- {
- public function format($message, $locale, array $parameters = [])
- {
- // ... format the message according to your needs
-
- return $message;
- }
- }
-
-Now, pass an instance of this formatter as the second argument of the translator
-to use it when translating messages::
-
- use Symfony\Component\Translation\Translator;
-
- $translator = new Translator('fr_FR', new IntlMessageFormatter());
- $message = $translator->trans($originalMessage, $translationParameters);
-
-If you want to use this formatter to translate all messages in your Symfony
-application, define a service for the formatter and use the
-:ref:`translator.formatter ` option
-to set that service as the default formatter.
diff --git a/components/translation/usage.rst b/components/translation/usage.rst
deleted file mode 100644
index 19369bf845c..00000000000
--- a/components/translation/usage.rst
+++ /dev/null
@@ -1,272 +0,0 @@
-.. index::
- single: Translation; Usage
-
-Using the Translator
-====================
-
-Imagine you want to translate the string *"Symfony is great"* into French::
-
- use Symfony\Component\Translation\Loader\ArrayLoader;
- use Symfony\Component\Translation\Translator;
-
- $translator = new Translator('fr_FR');
- $translator->addLoader('array', new ArrayLoader());
- $translator->addResource('array', [
- 'Symfony is great!' => 'Symfony est super !',
- ], 'fr_FR');
-
- var_dump($translator->trans('Symfony is great!'));
-
-In this example, the message *"Symfony is great!"* will be translated into
-the locale set in the constructor (``fr_FR``) if the message exists in one of
-the message catalogs.
-
-Creating Translations
----------------------
-
-The act of creating translation files is an important part of "localization"
-(often abbreviated `L10n`_). Translation files consist of a series of
-id-translation pairs for the given domain and locale. The source is the identifier
-for the individual translation, and can be the message in the main locale (e.g.
-*"Symfony is great"*) of your application or a unique identifier (e.g.
-``symfony.great`` - see the sidebar below).
-
-Translation files can be created in several formats, XLIFF being the
-recommended format. These files are parsed by one of the loader classes.
-
-.. configuration-block::
-
- .. code-block:: xml
-
-
-
-
-
-
- Symfony is great
- J'aime Symfony
-
-
- symfony.great
- J'aime Symfony
-
-
-
-
-
- .. code-block:: yaml
-
- Symfony is great: J'aime Symfony
- symfony.great: J'aime Symfony
-
- .. code-block:: php
-
- return [
- 'Symfony is great' => 'J\'aime Symfony',
- 'symfony.great' => 'J\'aime Symfony',
- ];
-
-.. _translation-real-vs-keyword-messages:
-
-.. sidebar:: Using Real or Keyword Messages
-
- This example illustrates the two different philosophies when creating
- messages to be translated::
-
- $translator->trans('Symfony is great');
-
- $translator->trans('symfony.great');
-
- In the first method, messages are written in the language of the default
- locale (English in this case). That message is then used as the "id"
- when creating translations.
-
- In the second method, messages are actually "keywords" that convey the
- idea of the message. The keyword message is then used as the "id" for
- any translations. In this case, translations must be made for the default
- locale (i.e. to translate ``symfony.great`` to ``Symfony is great``).
-
- The second method is handy because the message key won't need to be changed
- in every translation file if you decide that the message should actually
- read "Symfony is really great" in the default locale.
-
- The choice of which method to use is entirely up to you, but the "keyword"
- format is often recommended for multi-language applications, whereas for
- shared bundles that contain translation resources we recommend the real
- message, so your application can choose to disable the translator layer
- and you will see a readable message.
-
- Additionally, the ``php`` and ``yaml`` file formats support nested ids to
- avoid repeating yourself if you use keywords instead of real text for your
- ids:
-
- .. configuration-block::
-
- .. code-block:: yaml
-
- symfony:
- is:
- great: Symfony is great
- amazing: Symfony is amazing
- has:
- bundles: Symfony has bundles
- user:
- login: Login
-
- .. code-block:: php
-
- [
- 'symfony' => [
- 'is' => [
- 'great' => 'Symfony is great',
- 'amazing' => 'Symfony is amazing',
- ],
- 'has' => [
- 'bundles' => 'Symfony has bundles',
- ],
- ],
- 'user' => [
- 'login' => 'Login',
- ],
- ];
-
- The multiple levels are flattened into single id/translation pairs by
- adding a dot (``.``) between every level, therefore the above examples are
- equivalent to the following:
-
- .. configuration-block::
-
- .. code-block:: yaml
-
- symfony.is.great: Symfony is great
- symfony.is.amazing: Symfony is amazing
- symfony.has.bundles: Symfony has bundles
- user.login: Login
-
- .. code-block:: php
-
- return [
- 'symfony.is.great' => 'Symfony is great',
- 'symfony.is.amazing' => 'Symfony is amazing',
- 'symfony.has.bundles' => 'Symfony has bundles',
- 'user.login' => 'Login',
- ];
-
-Forcing the Translator Locale
------------------------------
-
-When translating a message, the Translator uses the specified locale or the
-``fallback`` locale if necessary. You can also manually specify the locale to
-use for translation::
-
- $translator->trans(
- 'Symfony is great',
- [],
- 'messages',
- 'fr_FR'
- );
-
- $translator->transChoice(
- '{0} There are no apples|{1} There is one apple|]1,Inf[ There are %count% apples',
- 10,
- [],
- 'messages',
- 'fr_FR'
- );
-
-.. note::
-
- Starting from Symfony 3.2, the third argument of ``transChoice()`` is
- optional when the only placeholder in use is ``%count%``. In previous
- Symfony versions you needed to always define it::
-
- $translator->transChoice(
- '{0} There are no apples|{1} There is one apple|]1,Inf[ There are %count% apples',
- 10,
- ['%count%' => 10],
- 'messages',
- 'fr_FR'
- );
-
-.. _retrieving-the-message-catalogue:
-
-Retrieving the Message Catalog
-------------------------------
-
-In case you want to use the same translation catalog outside your application
-(e.g. use translation on the client side), it's possible to fetch raw translation
-messages. Specify the required locale::
-
- $catalog = $translator->getCatalogue('fr_FR');
- $messages = $catalog->all();
- while ($catalog = $catalog->getFallbackCatalogue()) {
- $messages = array_replace_recursive($catalog->all(), $messages);
- }
-
-The ``$messages`` variable will have the following structure::
-
- [
- 'messages' => [
- 'Hello world' => 'Bonjour tout le monde',
- ],
- 'validators' => [
- 'Value should not be empty' => 'Valeur ne doit pas être vide',
- 'Value is too long' => 'Valeur est trop long',
- ],
- ];
-
-Adding Notes to Translation Contents
-------------------------------------
-
-Sometimes translators need additional context to better decide how to translate
-some content. This context can be provided with notes, which are a collection of
-comments used to store end user readable information. The only format that
-supports loading and dumping notes is XLIFF version 2.0.
-
-If the XLIFF 2.0 document contains ```` nodes, they are automatically
-loaded/dumped when using this component inside a Symfony application:
-
-.. code-block:: xml
-
-
-
-
-
-
- new
- true
- user login
-
-
- original-content
- translated-content
-
-
-
-
-
-When using the standalone Translation component, call the ``setMetadata()``
-method of the catalog and pass the notes as arrays. This is for example the
-code needed to generate the previous XLIFF file::
-
- use Symfony\Component\Translation\Dumper\XliffFileDumper;
- use Symfony\Component\Translation\MessageCatalogue;
-
- $catalog = new MessageCatalogue('en_US');
- $catalog->add([
- 'original-content' => 'translated-content',
- ]);
- $catalog->setMetadata('original-content', ['notes' => [
- ['category' => 'state', 'content' => 'new'],
- ['category' => 'approved', 'content' => 'true'],
- ['category' => 'section', 'content' => 'user login', 'priority' => '1'],
- ]]);
-
- $dumper = new XliffFileDumper();
- $dumper->formatCatalogue($catalog, 'messages', [
- 'default_locale' => 'fr_FR',
- 'xliff_version' => '2.0'
- ]);
-
-.. _`L10n`: https://en.wikipedia.org/wiki/Internationalization_and_localization
diff --git a/components/type_info.rst b/components/type_info.rst
new file mode 100644
index 00000000000..817c7f1d61a
--- /dev/null
+++ b/components/type_info.rst
@@ -0,0 +1,202 @@
+The TypeInfo Component
+======================
+
+The TypeInfo component extracts type information from PHP elements like properties,
+arguments and return types.
+
+This component provides:
+
+* A powerful ``Type`` definition that can handle unions, intersections, and generics
+ (and can be extended to support more types in the future);
+* A way to get types from PHP elements such as properties, method arguments,
+ return types, and raw strings.
+
+Installation
+------------
+
+.. code-block:: terminal
+
+ $ composer require symfony/type-info
+
+.. include:: /components/require_autoload.rst.inc
+
+Usage
+-----
+
+This component gives you a :class:`Symfony\\Component\\TypeInfo\\Type` object that
+represents the PHP type of anything you built or asked to resolve.
+
+There are two ways to use this component. First one is to create a type manually thanks
+to the :class:`Symfony\\Component\\TypeInfo\\Type` static methods as following::
+
+ use Symfony\Component\TypeInfo\Type;
+
+ Type::int();
+ Type::nullable(Type::string());
+ Type::generic(Type::object(Collection::class), Type::int());
+ Type::list(Type::bool());
+ Type::intersection(Type::object(\Stringable::class), Type::object(\Iterator::class));
+
+Many others methods are available and can be found
+in :class:`Symfony\\Component\\TypeInfo\\TypeFactoryTrait`.
+
+You can also use a generic method that detects the type automatically::
+
+ Type::fromValue(1.1); // same as Type::float()
+ Type::fromValue('...'); // same as Type::string()
+ Type::fromValue(false); // same as Type::false()
+
+.. versionadded:: 7.3
+
+ The ``fromValue()`` method was introduced in Symfony 7.3.
+
+Resolvers
+~~~~~~~~~
+
+The second way to use the component is by using ``TypeInfo`` to resolve a type
+based on reflection or a simple string. This approach is designed for libraries
+that need a simple way to describe a class or anything with a type::
+
+ use Symfony\Component\TypeInfo\Type;
+ use Symfony\Component\TypeInfo\TypeResolver\TypeResolver;
+
+ class Dummy
+ {
+ public function __construct(
+ public int $id,
+ ) {
+ }
+ }
+
+ // Instantiate a new resolver
+ $typeResolver = TypeResolver::create();
+
+ // Then resolve types for any subject
+ $typeResolver->resolve(new \ReflectionProperty(Dummy::class, 'id')); // returns an "int" Type instance
+ $typeResolver->resolve('bool'); // returns a "bool" Type instance
+
+ // Types can be instantiated thanks to static factories
+ $type = Type::list(Type::nullable(Type::bool()));
+
+ // Type instances have several helper methods
+
+ // for collections, it returns the type of the item used as the key;
+ // in this example, the collection is a list, so it returns an "int" Type instance
+ $keyType = $type->getCollectionKeyType();
+
+ // you can chain the utility methods (e.g. to introspect the values of the collection)
+ // the following code will return true
+ $isValueNullable = $type->getCollectionValueType()->isNullable();
+
+Each of these calls will return you a ``Type`` instance that corresponds to the
+static method used. You can also resolve types from a string (as shown in the
+``bool`` parameter of the previous example)
+
+PHPDoc Parsing
+~~~~~~~~~~~~~~
+
+In many cases, you may not have cleanly typed properties or may need more precise
+type definitions provided by advanced PHPDoc. To achieve this, you can use a string
+resolver based on the PHPDoc annotations.
+
+First, run the command ``composer require phpstan/phpdoc-parser`` to install the
+PHP package required for string resolving. Then, follow these steps::
+
+ use Symfony\Component\TypeInfo\TypeResolver\TypeResolver;
+
+ class Dummy
+ {
+ public function __construct(
+ public int $id,
+ /** @var string[] $tags */
+ public array $tags,
+ ) {
+ }
+ }
+
+ $typeResolver = TypeResolver::create();
+ $typeResolver->resolve(new \ReflectionProperty(Dummy::class, 'id')); // returns an "int" Type
+ $typeResolver->resolve(new \ReflectionProperty(Dummy::class, 'tags')); // returns a collection with "int" as key and "string" as values Type
+
+Advanced Usages
+~~~~~~~~~~~~~~~
+
+The TypeInfo component provides various methods to manipulate and check types,
+depending on your needs.
+
+**Identify** a type::
+
+ // define a simple integer type
+ $type = Type::int();
+ // check if the type matches a specific identifier
+ $type->isIdentifiedBy(TypeIdentifier::INT); // true
+ $type->isIdentifiedBy(TypeIdentifier::STRING); // false
+
+ // define a union type (equivalent to PHP's int|string)
+ $type = Type::union(Type::string(), Type::int());
+ // now the second check is true because the union type contains the string type
+ $type->isIdentifiedBy(TypeIdentifier::INT); // true
+ $type->isIdentifiedBy(TypeIdentifier::STRING); // true
+
+ class DummyParent {}
+ class Dummy extends DummyParent implements DummyInterface {}
+
+ // define an object type
+ $type = Type::object(Dummy::class);
+
+ // check if the type is an object or matches a specific class
+ $type->isIdentifiedBy(TypeIdentifier::OBJECT); // true
+ $type->isIdentifiedBy(Dummy::class); // true
+ // check if it inherits/implements something
+ $type->isIdentifiedBy(DummyParent::class); // true
+ $type->isIdentifiedBy(DummyInterface::class); // true
+
+Checking if a type **accepts a value**::
+
+ $type = Type::int();
+ // check if the type accepts a given value
+ $type->accepts(123); // true
+ $type->accepts('z'); // false
+
+ $type = Type::union(Type::string(), Type::int());
+ // now the second check is true because the union type accepts either an int or a string value
+ $type->accepts(123); // true
+ $type->accepts('z'); // true
+
+.. versionadded:: 7.3
+
+ The :method:`Symfony\\Component\\TypeInfo\\Type::accepts`
+ method was introduced in Symfony 7.3.
+
+Using callables for **complex checks**::
+
+ class Foo
+ {
+ private int $integer;
+ private string $string;
+ private ?float $float;
+ }
+
+ $reflClass = new \ReflectionClass(Foo::class);
+
+ $resolver = TypeResolver::create();
+ $integerType = $resolver->resolve($reflClass->getProperty('integer'));
+ $stringType = $resolver->resolve($reflClass->getProperty('string'));
+ $floatType = $resolver->resolve($reflClass->getProperty('float'));
+
+ // define a callable to validate non-nullable number types
+ $isNonNullableNumber = function (Type $type): bool {
+ if ($type->isNullable()) {
+ return false;
+ }
+
+ if ($type->isIdentifiedBy(TypeIdentifier::INT) || $type->isIdentifiedBy(TypeIdentifier::FLOAT)) {
+ return true;
+ }
+
+ return false;
+ };
+
+ $integerType->isSatisfiedBy($isNonNullableNumber); // true
+ $stringType->isSatisfiedBy($isNonNullableNumber); // false
+ $floatType->isSatisfiedBy($isNonNullableNumber); // false
diff --git a/components/uid.rst b/components/uid.rst
new file mode 100644
index 00000000000..b4083765436
--- /dev/null
+++ b/components/uid.rst
@@ -0,0 +1,727 @@
+The UID Component
+=================
+
+ The UID component provides utilities to work with `unique identifiers`_ (UIDs)
+ such as UUIDs and ULIDs.
+
+Installation
+------------
+
+.. code-block:: terminal
+
+ $ composer require symfony/uid
+
+.. include:: /components/require_autoload.rst.inc
+
+.. _uuid:
+
+UUIDs
+-----
+
+`UUIDs`_ (*universally unique identifiers*) are one of the most popular UIDs in
+the software industry. UUIDs are 128-bit numbers usually represented as five
+groups of hexadecimal characters: ``xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx``
+(the ``M`` digit is the UUID version and the ``N`` digit is the UUID variant).
+
+Generating UUIDs
+~~~~~~~~~~~~~~~~
+
+Use the named constructors of the ``Uuid`` class or any of the specific classes
+to create each type of UUID:
+
+**UUID v1** (time-based)
+
+Generates the UUID using a timestamp and the MAC address of your device
+(`read the UUIDv1 spec `__).
+Both are obtained automatically, so you don't have to pass any constructor argument::
+
+ use Symfony\Component\Uid\Uuid;
+
+ $uuid = Uuid::v1();
+ // $uuid is an instance of Symfony\Component\Uid\UuidV1
+
+.. tip::
+
+ It's recommended to use UUIDv7 instead of UUIDv1 because it provides
+ better entropy.
+
+**UUID v2** (DCE security)
+
+Similar to UUIDv1 but with a very high likelihood of ID collision
+(`read the UUIDv2 spec `__).
+It's part of the authentication mechanism of DCE (Distributed Computing Environment)
+and the UUID includes the POSIX UIDs (user/group ID) of the user who generated it.
+This UUID variant is **not implemented** by the Uid component.
+
+**UUID v3** (name-based, MD5)
+
+Generates UUIDs from names that belong, and are unique within, some given namespace
+(`read the UUIDv3 spec `__).
+This variant is useful to generate deterministic UUIDs from arbitrary strings.
+It works by populating the UUID contents with the``md5`` hash of concatenating
+the namespace and the name::
+
+ use Symfony\Component\Uid\Uuid;
+
+ // you can use any of the predefined namespaces...
+ $namespace = Uuid::fromString(Uuid::NAMESPACE_OID);
+ // ...or use a random namespace:
+ // $namespace = Uuid::v4();
+
+ // $name can be any arbitrary string
+ $uuid = Uuid::v3($namespace, $name);
+ // $uuid is an instance of Symfony\Component\Uid\UuidV3
+
+These are the default namespaces defined by the standard:
+
+* ``Uuid::NAMESPACE_DNS`` if you are generating UUIDs for `DNS entries `__
+* ``Uuid::NAMESPACE_URL`` if you are generating UUIDs for `URLs `__
+* ``Uuid::NAMESPACE_OID`` if you are generating UUIDs for `OIDs (object identifiers) `__
+* ``Uuid::NAMESPACE_X500`` if you are generating UUIDs for `X500 DNs (distinguished names) `__
+
+**UUID v4** (random)
+
+Generates a random UUID (`read the UUIDv4 spec `__).
+Because of its randomness, it ensures uniqueness across distributed systems
+without the need for a central coordinating entity. It's privacy-friendly
+because it doesn't contain any information about where and when it was generated::
+
+ use Symfony\Component\Uid\Uuid;
+
+ $uuid = Uuid::v4();
+ // $uuid is an instance of Symfony\Component\Uid\UuidV4
+
+**UUID v5** (name-based, SHA-1)
+
+It's the same as UUIDv3 (explained above) but it uses ``sha1`` instead of
+``md5`` to hash the given namespace and name (`read the UUIDv5 spec `__).
+This makes it more secure and less prone to hash collisions.
+
+.. _uid-uuid-v6:
+
+**UUID v6** (reordered time-based)
+
+It rearranges the time-based fields of the UUIDv1 to make it lexicographically
+sortable (like :ref:`ULIDs `). It's more efficient for database indexing
+(`read the UUIDv6 spec `__)::
+
+ use Symfony\Component\Uid\Uuid;
+
+ $uuid = Uuid::v6();
+ // $uuid is an instance of Symfony\Component\Uid\UuidV6
+
+.. tip::
+
+ It's recommended to use UUIDv7 instead of UUIDv6 because it provides
+ better entropy.
+
+.. _uid-uuid-v7:
+
+**UUID v7** (UNIX timestamp)
+
+Generates time-ordered UUIDs based on a high-resolution Unix Epoch timestamp
+source (the number of milliseconds since midnight 1 Jan 1970 UTC, leap seconds excluded)
+(`read the UUIDv7 spec `__).
+It's recommended to use this version over UUIDv1 and UUIDv6 because it provides
+better entropy (and a more strict chronological order of UUID generation)::
+
+ use Symfony\Component\Uid\Uuid;
+
+ $uuid = Uuid::v7();
+ // $uuid is an instance of Symfony\Component\Uid\UuidV7
+
+**UUID v8** (custom)
+
+Provides an RFC-compatible format intended for experimental or vendor-specific use cases
+(`read the UUIDv8 spec `__).
+You must generate the UUID value yourself. The only requirement is to set the
+variant and version bits of the UUID correctly. The rest of the UUID content is
+implementation-specific, and no particular format should be assumed::
+
+ use Symfony\Component\Uid\Uuid;
+
+ // pass your custom UUID value as the argument
+ $uuid = Uuid::v8('d9e7a184-5d5b-11ea-a62a-3499710062d0');
+ // $uuid is an instance of Symfony\Component\Uid\UuidV8
+
+If your UUID value is already generated in another format, use any of the
+following methods to create a ``Uuid`` object from it::
+
+ // all the following examples would generate the same Uuid object
+ $uuid = Uuid::fromString('d9e7a184-5d5b-11ea-a62a-3499710062d0');
+ $uuid = Uuid::fromBinary("\xd9\xe7\xa1\x84\x5d\x5b\x11\xea\xa6\x2a\x34\x99\x71\x00\x62\xd0");
+ $uuid = Uuid::fromBase32('6SWYGR8QAV27NACAHMK5RG0RPG');
+ $uuid = Uuid::fromBase58('TuetYWNHhmuSQ3xPoVLv9M');
+ $uuid = Uuid::fromRfc4122('d9e7a184-5d5b-11ea-a62a-3499710062d0');
+
+You can also use the ``UuidFactory`` to generate UUIDs. First, you may
+configure the behavior of the factory using configuration files::
+
+.. configuration-block::
+
+ .. code-block:: yaml
+
+ # config/packages/uid.yaml
+ framework:
+ uid:
+ default_uuid_version: 7
+ name_based_uuid_version: 5
+ name_based_uuid_namespace: 6ba7b810-9dad-11d1-80b4-00c04fd430c8
+ time_based_uuid_version: 7
+ time_based_uuid_node: 121212121212
+
+ .. code-block:: xml
+
+
+
+