From 50905ff253e5e1164b377ad5f285d1c439e7bdb7 Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Tue, 7 May 2013 22:32:26 +0200 Subject: [PATCH 001/146] Adding lazy services documentation as of symfony/symfony#7890 --- components/dependency_injection/index.rst | 1 + .../dependency_injection/lazy_services.rst | 68 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 components/dependency_injection/lazy_services.rst diff --git a/components/dependency_injection/index.rst b/components/dependency_injection/index.rst index e1d6b0eab8d..b3960eb8e00 100644 --- a/components/dependency_injection/index.rst +++ b/components/dependency_injection/index.rst @@ -14,5 +14,6 @@ configurators parentservices advanced + lazy_services workflow diff --git a/components/dependency_injection/lazy_services.rst b/components/dependency_injection/lazy_services.rst new file mode 100644 index 00000000000..ca97b5cad24 --- /dev/null +++ b/components/dependency_injection/lazy_services.rst @@ -0,0 +1,68 @@ +.. index:: + single: Dependency Injection; Lazy Services + +Lazy Services +============= + +.. versionadded:: 2.3 + Lazy services were added in Symfony 2.3. + +Configuring lazy services +------------------------- + +In some particular cases where a very heavy service is always requested, +but not always used, you may want to mark it as ``lazy`` to delay its instantiation. + +In order to have services to lazily instantiate, you will first need to install +the `ProxyManager bridge`_:: + + php composer.phar require symfony/proxy-manager-bridge:2.3.* + +You can mark the service as ``lazy`` by manipulating its definitions: + + +.. configuration-block:: + + .. code-block:: yaml + + services: + foo: + class: Example\Foo + lazy: true + + .. code-block:: xml + + + + .. code-block:: php + + $definition = new Definition('Example\Foo'); + $definition->setLazy(true); + $container->setDefinition('foo', $definition); + +You can then require the service from the container:: + + $service = $container->get($serviceId); + +At this point the retrieved ``$service`` should be a virtual `proxy`_ with the same +signature of the class representing the service. + +.. note:: + + If you don't install the `ProxyManager bridge`_, the container will just skip + over the ``lazy`` flag and simply instantiate the service as it would normally do. + +The proxy gets initialized and the actual service is instantiated as soon as you interact +in any way with this object. + +Additional resources +-------------------- + + +You can read more about how proxies are instantiated, generated and initialized in +the `documentation of ProxyManager`_. + + +.. _`ProxyManager bridge`: https://github.com/symfony/symfony/tree/2.3/src/Symfony/Bridge/ProxyManager +.. _`proxy`: http://en.wikipedia.org/wiki/Proxy_pattern +.. _`documentation of ProxyManager`: https://github.com/Ocramius/ProxyManager/blob/master/docs/lazy-loading-value-holder.md \ No newline at end of file From c3c3e98bab34427db516ab391bca73dbd0b04a3a Mon Sep 17 00:00:00 2001 From: Pierre du Plessis Date: Wed, 8 May 2013 18:35:49 +0200 Subject: [PATCH 002/146] [Components][Console] Fixed typos for table helper --- components/console/helpers/tablehelper.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/components/console/helpers/tablehelper.rst b/components/console/helpers/tablehelper.rst index 04301af5048..1145dd7b603 100644 --- a/components/console/helpers/tablehelper.rst +++ b/components/console/helpers/tablehelper.rst @@ -48,8 +48,8 @@ You can also control table rendering by setting custom rendering option values: * :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setPaddingChar` * :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setHorizontalBorderChar` * :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setVerticalBorderChar` -* :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setVrossingChar` -* :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setVellHeaderFormat` -* :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setVellRowFormat` +* :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setCrossingChar` +* :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setCellHeaderFormat` +* :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setCellRowFormat` * :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setBorderFormat` * :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setPadType` From 931091d8e3aa0b9d4f1393d313388d5ee1a5d47d Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Thu, 9 May 2013 20:18:51 +0200 Subject: [PATCH 003/146] Applying changes suggested by @WouterJ, adding lazy_services to components map --- .../dependency_injection/lazy_services.rst | 17 ++++++++--------- components/map.rst.inc | 1 + 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/components/dependency_injection/lazy_services.rst b/components/dependency_injection/lazy_services.rst index ca97b5cad24..599d503f7e6 100644 --- a/components/dependency_injection/lazy_services.rst +++ b/components/dependency_injection/lazy_services.rst @@ -14,35 +14,35 @@ In some particular cases where a very heavy service is always requested, but not always used, you may want to mark it as ``lazy`` to delay its instantiation. In order to have services to lazily instantiate, you will first need to install -the `ProxyManager bridge`_:: +the `ProxyManager bridge`_: - php composer.phar require symfony/proxy-manager-bridge:2.3.* +.. code-block:: bash + $ php composer.phar require symfony/proxy-manager-bridge:2.3.* You can mark the service as ``lazy`` by manipulating its definitions: - .. configuration-block:: .. code-block:: yaml services: foo: - class: Example\Foo + class: Acme\Foo lazy: true .. code-block:: xml - + .. code-block:: php - $definition = new Definition('Example\Foo'); + $definition = new Definition('Acme\Foo'); $definition->setLazy(true); $container->setDefinition('foo', $definition); You can then require the service from the container:: - $service = $container->get($serviceId); + $service = $container->get('foo'); At this point the retrieved ``$service`` should be a virtual `proxy`_ with the same signature of the class representing the service. @@ -55,10 +55,9 @@ signature of the class representing the service. The proxy gets initialized and the actual service is instantiated as soon as you interact in any way with this object. -Additional resources +Additional Resources -------------------- - You can read more about how proxies are instantiated, generated and initialized in the `documentation of ProxyManager`_. diff --git a/components/map.rst.inc b/components/map.rst.inc index e29df506e55..d360c65a706 100644 --- a/components/map.rst.inc +++ b/components/map.rst.inc @@ -39,6 +39,7 @@ * :doc:`/components/dependency_injection/configurators` * :doc:`/components/dependency_injection/parentservices` * :doc:`/components/dependency_injection/advanced` + * :doc:`/components/dependency_injection/lazy_services` * :doc:`/components/dependency_injection/workflow` * **DOM Crawler** From 2d9316f6d0a9808c6265881b81ecf4d15b1a45a3 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Fri, 10 May 2013 19:56:56 +0200 Subject: [PATCH 004/146] Added new tag --- reference/twig_reference.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index b6960b1e729..a6cbfc1d8a4 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -134,6 +134,9 @@ Filters Tags ---- +.. versionadded:: 2.3 + The stopwatch tag was added in Symfony 2.3 + +---------------------------------------------------+--------------------------------------------------------------------+ | Tag Syntax | Usage | +===================================================+====================================================================+ @@ -150,6 +153,9 @@ Tags | ``{% trans_default_domain language %}`` | This will set the default domain for message catalogues in the | | | current template | +---------------------------------------------------+--------------------------------------------------------------------+ +| ``{% stopwatch name %}...{% endstopwatch %}`` | This will time the run time of the code inside it and put that on | +| | the timeline of the WebDeveloperBundle. | ++---------------------------------------------------+--------------------------------------------------------------------+ Tests ----- From 438c8244e04e8c9ad818d93f22699ab5c8aa0289 Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Wed, 15 May 2013 13:01:26 +0200 Subject: [PATCH 005/146] Made the Icu component compatible with ICU 3.8 --- components/intl.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/intl.rst b/components/intl.rst index cf42b9778d5..e9c5028d4c2 100644 --- a/components/intl.rst +++ b/components/intl.rst @@ -72,7 +72,7 @@ expose them manually by adding the following lines to your autoload code:: but usually Composer does this for you automatically: * 1.0.*: when the intl extension is not available - * 1.1.*: when intl is compiled with ICU 4.0 or higher + * 1.1.*: when intl is compiled with ICU 3.8 or higher * 1.2.*: when intl is compiled with ICU 4.4 or higher These versions are important when you deploy your application to a **server with From d7ea3a540a5dc425bf1d16f4113746975404da38 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 15 May 2013 22:04:52 -0500 Subject: [PATCH 006/146] [#2619] Tweaks for new proxy/lazy services entry --- .../dependency_injection/lazy_services.rst | 55 ++++++++++++++----- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/components/dependency_injection/lazy_services.rst b/components/dependency_injection/lazy_services.rst index 599d503f7e6..88ad0c51f59 100644 --- a/components/dependency_injection/lazy_services.rst +++ b/components/dependency_injection/lazy_services.rst @@ -7,19 +7,41 @@ Lazy Services .. versionadded:: 2.3 Lazy services were added in Symfony 2.3. -Configuring lazy services -------------------------- +Why Lazy Services? +------------------ -In some particular cases where a very heavy service is always requested, -but not always used, you may want to mark it as ``lazy`` to delay its instantiation. +In some cases, you may want to inject a service that is a bit heavy to instantiate, +but is not always used inside your object. For example, imagine you have +a ``NewsletterManager`` and you inject a ``mailer`` service into it. Only +a few methods on your ``NewsletterManager`` actually use the ``mailer``, +but even when you don't need it, a ``mailer`` service is always instantiated +in order to construct your ``NewsletterManager``. -In order to have services to lazily instantiate, you will first need to install +Configuring lazy services is one answer to this. With a lazy service, a "proxy" +of the ``mailer`` service is actually injected. It looks and acts just like +the ``mailer``, except that the ``mailer`` isn't actually instantiated until +you interact with the proxy in some way. + +Installation +------------ + +In order to use the lazy service instantiation, you will first need to install the `ProxyManager bridge`_: .. code-block:: bash + $ php composer.phar require symfony/proxy-manager-bridge:2.3.* -You can mark the service as ``lazy`` by manipulating its definitions: +.. note:: + + If you're using the full-stack framework, this package is not included + and needs to be added to ``composer.json`` and installed (which is what + the above command does). + +Configuration +------------- + +You can mark the service as ``lazy`` by manipulating its definition: .. configuration-block:: @@ -44,24 +66,27 @@ You can then require the service from the container:: $service = $container->get('foo'); -At this point the retrieved ``$service`` should be a virtual `proxy`_ with the same -signature of the class representing the service. +At this point the retrieved ``$service`` should be a virtual `proxy`_ with +the same signature of the class representing the service. You can also inject +the service just like normal into other services. The object that's actually +injected will be the proxy. .. note:: - If you don't install the `ProxyManager bridge`_, the container will just skip - over the ``lazy`` flag and simply instantiate the service as it would normally do. + If you don't install the `ProxyManager bridge`_, the container will just + skip over the ``lazy`` flag and simply instantiate the service as it would + normally do. -The proxy gets initialized and the actual service is instantiated as soon as you interact -in any way with this object. +The proxy gets initialized and the actual service is instantiated as soon +as you interact in any way with this object. Additional Resources -------------------- -You can read more about how proxies are instantiated, generated and initialized in -the `documentation of ProxyManager`_. +You can read more about how proxies are instantiated, generated and initialized +in the `documentation of ProxyManager`_. -.. _`ProxyManager bridge`: https://github.com/symfony/symfony/tree/2.3/src/Symfony/Bridge/ProxyManager +.. _`ProxyManager bridge`: https://github.com/symfony/symfony/tree/master/src/Symfony/Bridge/ProxyManager .. _`proxy`: http://en.wikipedia.org/wiki/Proxy_pattern .. _`documentation of ProxyManager`: https://github.com/Ocramius/ProxyManager/blob/master/docs/lazy-loading-value-holder.md \ No newline at end of file From ac3df5725ac4e8b775992ed7777ca4b75dba978a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20P=C3=A4rtel?= Date: Fri, 17 May 2013 16:15:11 +0300 Subject: [PATCH 007/146] Documented ProgressHelper's clear() method. --- components/console/helpers/progresshelper.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/components/console/helpers/progresshelper.rst b/components/console/helpers/progresshelper.rst index cadf41d947d..1c3635e93c6 100644 --- a/components/console/helpers/progresshelper.rst +++ b/components/console/helpers/progresshelper.rst @@ -10,6 +10,9 @@ Progress Helper .. versionadded:: 2.3 The ``setCurrent`` method was added in Symfony 2.3. +.. versionadded:: 2.4 + The ``clear`` method was added in Symfony 2.4. + When executing longer-running commands, it may be helpful to show progress information, which updates as your command runs: @@ -37,6 +40,12 @@ pass it a total number of units, and advance the progress as your command execut :method:`Symfony\\Component\\Console\\Helper\\ProgressHelper::setCurrent` method. +If you want to output something while the progress bar is running, +call :method:`Symfony\\Component\\Console\\Helper\\ProgressHelper::clear` first. +After you're done, call +:method:`Symfony\\Component\\Console\\Helper\\ProgressHelper::display` +to show the progress bar again. + The appearance of the progress output can be customized as well, with a number of different levels of verbosity. Each of these displays different possible items - like percentage completion, a moving progress bar, or current/total From 3ca7875b1de0b1cbd56c92bbc671899297986ea0 Mon Sep 17 00:00:00 2001 From: Juan Traverso Date: Sun, 16 Jun 2013 12:40:39 +0200 Subject: [PATCH 008/146] [Process] Doc for output flush methods. --- components/process.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/components/process.rst b/components/process.rst index 6c7c9205454..b0ec4d9788b 100644 --- a/components/process.rst +++ b/components/process.rst @@ -45,6 +45,15 @@ output. Alternatively, the :method:`Symfony\\Component\\Process\\Process::getInc and :method:`Symfony\\Component\\Process\\Process::getIncrementalErrorOutput` methods returns the new outputs since the last call. +.. versionadded:: 2.4 + The ``getAndFlushOutput()``, ``getAndFlushIncrementalOutput()``, ``getAndFlushErrorOutput()``, ` + ``getAndFlushIncrementalErrorOutput()``, ``flushOutput()`` and ``flushErrorOutput()`` methods were + added in Symfony 2.4. + +These methods clears the output and error output buffers. Also, ``getAndFlushOutput()``, +``getAndFlushIncrementalOutput()``, ``getAndFlushErrorOutput()`` and ``getAndFlushIncrementalErrorOutput()`` +returns the outputs as well. + Getting real-time Process Output -------------------------------- From f9f20e5523c4c600c7aa3c8bbcb187e84efe1910 Mon Sep 17 00:00:00 2001 From: Juan Traverso Date: Sun, 16 Jun 2013 13:58:42 +0200 Subject: [PATCH 009/146] [Process] Rewriting to avoid wrong sentences. --- components/process.rst | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/components/process.rst b/components/process.rst index b0ec4d9788b..afc9e85c98b 100644 --- a/components/process.rst +++ b/components/process.rst @@ -46,13 +46,16 @@ and :method:`Symfony\\Component\\Process\\Process::getIncrementalErrorOutput` methods returns the new outputs since the last call. .. versionadded:: 2.4 - The ``getAndFlushOutput()``, ``getAndFlushIncrementalOutput()``, ``getAndFlushErrorOutput()``, ` + The ``getAndFlushOutput()``, ``getAndFlushIncrementalOutput()``, ``getAndFlushErrorOutput()``, ``getAndFlushIncrementalErrorOutput()``, ``flushOutput()`` and ``flushErrorOutput()`` methods were added in Symfony 2.4. -These methods clears the output and error output buffers. Also, ``getAndFlushOutput()``, -``getAndFlushIncrementalOutput()``, ``getAndFlushErrorOutput()`` and ``getAndFlushIncrementalErrorOutput()`` -returns the outputs as well. +The :method:`Symfony\\Component\\Process\\Process::flushOutput()` method flushes the contents of the output and +and :method:`Symfony\\Component\\Process\\Process::flushErrorOutput()` the content of the error output. You can get the +contents and flush the whole output or the error output by using :method:`Symfony\\Component\\Process\\Process::getAndFlushOutput()` +and :method:`Symfony\\Component\\Process\\Process::getAndFlushErrorOutput()` methods, or the outputs since the last call +by using the :method:`Symfony\\Component\\Process\\Process::getAndFlushIncrementalOutput()` and +:method:`Symfony\\Component\\Process\\Process::getAndFlushIncrementalErrorOutput()` methods. Getting real-time Process Output -------------------------------- From 1f7898045f3f1ad06dc63f32f4d921519fc5e3d7 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 29 Jun 2013 17:42:06 -0500 Subject: [PATCH 010/146] [#2720] Playing "catch-up" to get the master branch up to date with the new documentation standards Specifically, I'm pretending as if 2.1 had reached its end-of-life today, and am applying all the needed changes to the master branch --- book/security.rst | 4 ++-- book/stable_api.rst | 5 +++-- components/filesystem.rst | 6 ++---- components/stopwatch.rst | 2 +- cookbook/bundles/installation.rst | 9 ++------- cookbook/configuration/override_dir_structure.rst | 4 ++-- reference/constraints/Image.rst | 4 ++-- reference/forms/types/options/error_mapping.rst.inc | 3 --- reference/forms/types/options/property_path.rst.inc | 3 --- 9 files changed, 14 insertions(+), 26 deletions(-) diff --git a/book/security.rst b/book/security.rst index ee45430393e..aa1463a2da7 100644 --- a/book/security.rst +++ b/book/security.rst @@ -1702,8 +1702,8 @@ a route so that you can use it to generate the URL: .. caution:: - As of Symfony 2.1, you *must* have a route that corresponds to your logout - path. Without this route, logging out will not work. + You *must* have a route that corresponds to your logout path. Without + this route, logging out will not work. .. configuration-block:: diff --git a/book/stable_api.rst b/book/stable_api.rst index 0d92777bdd0..8980f0274dc 100644 --- a/book/stable_api.rst +++ b/book/stable_api.rst @@ -22,7 +22,8 @@ everything not tagged explicitly is not part of the stable API. Any third party bundle should also publish its own stable API. -As of Symfony 2.0, the following components have a public tagged API: +As of the latest stable release of Symfony, the following components have +a public tagged API: * BrowserKit * ClassLoader @@ -31,7 +32,7 @@ As of Symfony 2.0, the following components have a public tagged API: * DependencyInjection * DomCrawler * EventDispatcher -* Filesystem (as of Symfony 2.1) +* Filesystem * Finder * HttpFoundation * HttpKernel diff --git a/components/filesystem.rst b/components/filesystem.rst index d8386ae69fb..9e93336b239 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -258,9 +258,7 @@ thrown. .. note:: - Prior to version 2.1, ``mkdir`` returned a boolean and did not throw - exceptions. As of 2.1, a - :class:`Symfony\\Component\\Filesystem\\Exception\\IOException` is thrown - if a directory creation fails. + An :class:`Symfony\\Component\\Filesystem\\Exception\\IOException` is + thrown if directory creation fails. .. _`Packagist`: https://packagist.org/packages/symfony/filesystem diff --git a/components/stopwatch.rst b/components/stopwatch.rst index af5f98e823b..06908f13ee0 100644 --- a/components/stopwatch.rst +++ b/components/stopwatch.rst @@ -9,7 +9,7 @@ The Stopwatch Component .. versionadded:: 2.2 The Stopwatch Component is new to Symfony 2.2. Previously, the ``Stopwatch`` - class was located in the ``HttpKernel`` component (and was new in 2.1). + class was located in the ``HttpKernel`` component. Installation ------------ diff --git a/cookbook/bundles/installation.rst b/cookbook/bundles/installation.rst index c844d067ca3..84d17cda70a 100644 --- a/cookbook/bundles/installation.rst +++ b/cookbook/bundles/installation.rst @@ -10,8 +10,8 @@ basic steps for installing a bundle are the same. Add Composer Dependencies ------------------------- -Starting from Symfony 2.1, dependencies are managed with Composer. It's -a good idea to learn some basics of Composer in `their documentation`_. +In Symfony, dependencies are managed with Composer. It's a good idea to learn +some basics of Composer in `their documentation`_. Before you can use composer to install a bundle, you should look for a `Packagist`_ package of that bundle. For example, if you search for the popular @@ -33,11 +33,6 @@ file. If it isn't, you can use the version you want. If you choose an incompatib version, Composer will throw dependency errors when you try to install. If this happens, you can try a different version. -In the case of the FOSUserBundle, the ``README`` file has a caution that version -1.2.0 must be used for Symfony 2.0 and 1.3+ for Symfony 2.1+. Packagist displays -example ``require`` statements for all existing versions of a package. The -current development version of FOSUserBundle is ``"friendsofsymfony/user-bundle": "2.0.*@dev"``. - Now you can add the bundle to your ``composer.json`` file and update the dependencies. You can do this manually: diff --git a/cookbook/configuration/override_dir_structure.rst b/cookbook/configuration/override_dir_structure.rst index 31aeb973847..6112b67edde 100644 --- a/cookbook/configuration/override_dir_structure.rst +++ b/cookbook/configuration/override_dir_structure.rst @@ -91,8 +91,8 @@ may need to modify the paths inside these files:: require_once __DIR__.'/../Symfony/app/bootstrap.php.cache'; require_once __DIR__.'/../Symfony/app/AppKernel.php'; -Since Symfony 2.1 (in which Composer is introduced), you also need to change -the ``extra.symfony-web-dir`` option in the ``composer.json`` file: +You also need to change the ``extra.symfony-web-dir`` option in the ``composer.json`` +file: .. code-block:: json diff --git a/reference/constraints/Image.rst b/reference/constraints/Image.rst index 180397330a3..7c4b094b201 100644 --- a/reference/constraints/Image.rst +++ b/reference/constraints/Image.rst @@ -5,8 +5,8 @@ The Image constraint works exactly like the :doc:`File` constraint for the bulk of the documentation on this constraint. diff --git a/reference/forms/types/options/error_mapping.rst.inc b/reference/forms/types/options/error_mapping.rst.inc index 8c03180db7c..05ad2148c34 100644 --- a/reference/forms/types/options/error_mapping.rst.inc +++ b/reference/forms/types/options/error_mapping.rst.inc @@ -1,6 +1,3 @@ -.. versionadded:: 2.1 - The ``error_mapping`` option is new to Symfony 2.1. - error_mapping ~~~~~~~~~~~~~ diff --git a/reference/forms/types/options/property_path.rst.inc b/reference/forms/types/options/property_path.rst.inc index 540d17063ea..3d75992d1cb 100644 --- a/reference/forms/types/options/property_path.rst.inc +++ b/reference/forms/types/options/property_path.rst.inc @@ -14,6 +14,3 @@ If you wish the field to be ignored when reading or writing to the object you can set the ``property_path`` option to ``false``, but using ``property_path`` for this purpose is deprecated, you should use the ``mapped`` option. - -.. versionadded:: 2.1 - Since 2.1, the ``mapped`` option has been added for this use-case. From f8974119c1310bdf6ae9e0feafc8bc0d596c3b43 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 20 Jul 2013 14:59:05 -0500 Subject: [PATCH 011/146] [#2797] Removing the 2.1 version notes on master (since 2.1 has been deprecated - see documentation release directions) --- reference/constraints/UniqueEntity.rst | 6 ------ 1 file changed, 6 deletions(-) diff --git a/reference/constraints/UniqueEntity.rst b/reference/constraints/UniqueEntity.rst index fb50ad03c3b..19a855d9a36 100644 --- a/reference/constraints/UniqueEntity.rst +++ b/reference/constraints/UniqueEntity.rst @@ -153,9 +153,6 @@ errorPath **type**: ``string`` **default**: The name of the first `field`_ -.. versionadded:: 2.1 - The ``errorPath`` option was added in Symfony 2.1. - If the entity violates constraint the error message is bound to the first field in `fields`_. If there are more than one fields, you may want to map the error message to another field. @@ -254,9 +251,6 @@ ignoreNull **type**: ``Boolean`` **default**: ``true`` -.. versionadded:: 2.1 - The ``ignoreNull`` option was added in Symfony 2.1. - If this option is set to ``true``, then the constraint will allow multiple entities to have a ``null`` value for a field without failing validation. If set to ``false``, only one ``null`` value is allowed - if a second entity From f57b569a46b77a9cd57f8baa179da82bf67d79f7 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 20 Jul 2013 16:44:59 -0500 Subject: [PATCH 012/146] [#2829] Changing reference back to master - eventually we'll need an extension that helps us manage this version stuff --- cookbook/form/form_customization.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cookbook/form/form_customization.rst b/cookbook/form/form_customization.rst index f1585e0513d..02caa9cbd12 100644 --- a/cookbook/form/form_customization.rst +++ b/cookbook/form/form_customization.rst @@ -948,4 +948,4 @@ customizations directly. Look at the following example: The array passed as the second argument contains form "variables". For more details about this concept in Twig, see :ref:`twig-reference-form-variables`. -.. _`form_div_layout.html.twig`: https://github.com/symfony/symfony/blob/2.3/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig +.. _`form_div_layout.html.twig`: https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig From c80e4e71df8e0a9be60ac6d5b1f19541bbb00d57 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 28 Jul 2013 19:54:43 -0500 Subject: [PATCH 013/146] [#2783] Removing 2.1 versionadded that came back due to a tweak on the 2.2 branch --- book/security.rst | 5 ----- 1 file changed, 5 deletions(-) diff --git a/book/security.rst b/book/security.rst index 3cd4a8a1760..071ce973635 100644 --- a/book/security.rst +++ b/book/security.rst @@ -1803,11 +1803,6 @@ a route so that you can use it to generate the URL: return $collection; -.. caution:: - - As of Symfony 2.1, you *must* have a route that corresponds to your logout - path. Without this route, logging out will not work. - Once the user has been logged out, he will be redirected to whatever path is defined by the ``target`` parameter above (e.g. the ``homepage``). For more information on configuring the logout, see the From b6d5606a9124fa18e81c82f23fe14eb6cc7c4148 Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Thu, 1 Aug 2013 15:44:38 +0200 Subject: [PATCH 014/146] Updated rounding_mode documentation to reflect changed ROUND_ constants. --- reference/forms/types/integer.rst | 24 ++++++++++++++-------- reference/forms/types/number.rst | 34 ++++++++++++++----------------- 2 files changed, 31 insertions(+), 27 deletions(-) diff --git a/reference/forms/types/integer.rst b/reference/forms/types/integer.rst index b1a3d518eea..0ea2e2d1405 100644 --- a/reference/forms/types/integer.rst +++ b/reference/forms/types/integer.rst @@ -48,17 +48,25 @@ By default, if the user enters a non-integer number, it will be rounded down. There are several other rounding methods, and each is a constant on the :class:`Symfony\\Component\\Form\\Extension\\Core\\DataTransformer\\IntegerToLocalizedStringTransformer`: -* ``IntegerToLocalizedStringTransformer::ROUND_DOWN`` Rounding mode to - round towards zero. +* ``IntegerToLocalizedStringTransformer::ROUND_DOWN`` Round towards zero. -* ``IntegerToLocalizedStringTransformer::ROUND_FLOOR`` Rounding mode to - round towards negative infinity. +* ``IntegerToLocalizedStringTransformer::ROUND_FLOOR`` Round towards negative + infinity. -* ``IntegerToLocalizedStringTransformer::ROUND_UP`` Rounding mode to round - away from zero. +* ``IntegerToLocalizedStringTransformer::ROUND_UP`` Round away from zero. -* ``IntegerToLocalizedStringTransformer::ROUND_CEILING`` Rounding mode - to round towards positive infinity. +* ``IntegerToLocalizedStringTransformer::ROUND_CEILING`` Round towards + positive infinity. + +* ``IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN`` Round towards the + "nearest neighbor". If both neighbors are equidistant, round down. + +* ``IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN`` Round towards the + "nearest neighbor". If both neighbors are equidistant, round towards the + even neighbor. + +* ``IntegerToLocalizedStringTransformer::ROUND_HALF_UP`` Round towards the + "nearest neighbor". If both neighbors are equidistant, round up. .. include:: /reference/forms/types/options/grouping.rst.inc diff --git a/reference/forms/types/number.rst b/reference/forms/types/number.rst index ce40bce055c..6445efcc407 100644 --- a/reference/forms/types/number.rst +++ b/reference/forms/types/number.rst @@ -38,35 +38,31 @@ Field Options rounding_mode ~~~~~~~~~~~~~ -**type**: ``integer`` **default**: ``IntegerToLocalizedStringTransformer::ROUND_HALFUP`` +**type**: ``integer`` **default**: ``NumberToLocalizedStringTransformer::ROUND_HALFUP`` If a submitted number needs to be rounded (based on the ``precision`` option), you have several configurable options for that rounding. Each -option is a constant on the :class:`Symfony\\Component\\Form\\Extension\\Core\\DataTransformer\\IntegerToLocalizedStringTransformer`: +option is a constant on the :class:`Symfony\\Component\\Form\\Extension\\Core\\DataTransformer\\NumberToLocalizedStringTransformer`: -* ``IntegerToLocalizedStringTransformer::ROUND_DOWN`` Rounding mode to - round towards zero. +* ``NumberToLocalizedStringTransformer::ROUND_DOWN`` Round towards zero. -* ``IntegerToLocalizedStringTransformer::ROUND_FLOOR`` Rounding mode to - round towards negative infinity. +* ``NumberToLocalizedStringTransformer::ROUND_FLOOR`` Round towards negative + infinity. -* ``IntegerToLocalizedStringTransformer::ROUND_UP`` Rounding mode to round - away from zero. +* ``NumberToLocalizedStringTransformer::ROUND_UP`` Round away from zero. -* ``IntegerToLocalizedStringTransformer::ROUND_CEILING`` Rounding mode - to round towards positive infinity. +* ``NumberToLocalizedStringTransformer::ROUND_CEILING`` Round towards + positive infinity. -* ``IntegerToLocalizedStringTransformer::ROUND_HALFDOWN`` Rounding mode - to round towards "nearest neighbor" unless both neighbors are equidistant, - in which case round down. +* ``NumberToLocalizedStringTransformer::ROUND_HALF_DOWN`` Round towards the + "nearest neighbor". If both neighbors are equidistant, round down. -* ``IntegerToLocalizedStringTransformer::ROUND_HALFEVEN`` Rounding mode - to round towards the "nearest neighbor" unless both neighbors are equidistant, - in which case, round towards the even neighbor. +* ``NumberToLocalizedStringTransformer::ROUND_HALF_EVEN`` Round towards the + "nearest neighbor". If both neighbors are equidistant, round towards the + even neighbor. -* ``IntegerToLocalizedStringTransformer::ROUND_HALFUP`` Rounding mode to - round towards "nearest neighbor" unless both neighbors are equidistant, - in which case round up. +* ``NumberToLocalizedStringTransformer::ROUND_HALF_UP`` Round towards the + "nearest neighbor". If both neighbors are equidistant, round up. .. include:: /reference/forms/types/options/grouping.rst.inc From 2e25e0037c2d67872c3775ec1a515329beeb1d46 Mon Sep 17 00:00:00 2001 From: Johannes Date: Sun, 4 Aug 2013 16:08:10 +0200 Subject: [PATCH 015/146] adds docs for idle timeout (see symfony/symfony#8651) --- components/process.rst | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/components/process.rst b/components/process.rst index 56ba1686513..9c459dc742d 100644 --- a/components/process.rst +++ b/components/process.rst @@ -210,6 +210,25 @@ check regularly:: .. _reference-process-signal: +Process Idle Timeout +-------------------- + +.. versionadded:: 2.4 + The ``setIdleTimeout`` method was added in Symfony 2.4. + +In contrast to the timeout of the previous paragraph, the idle timeout only +considers the time since the last output was produced by the process:: + + use Symfony\Component\Process\Process; + + $process = new Process('something-with-variable-runtime'); + $process->setTimeout(3600); + $process->setIdleTimeout(60); + $process->run(); + +In the case above, a process is considered timed out, when either the total runtime +exceeds 3600 seconds, or the process does not produce any output for 60 seconds. + Process Signals --------------- From 3fa71b83602864c10af749d698bf64cfd4b6bb9b Mon Sep 17 00:00:00 2001 From: Johannes Date: Sun, 4 Aug 2013 16:37:52 +0200 Subject: [PATCH 016/146] adds api link --- components/process.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/process.rst b/components/process.rst index 9c459dc742d..c10824d77dd 100644 --- a/components/process.rst +++ b/components/process.rst @@ -214,7 +214,7 @@ Process Idle Timeout -------------------- .. versionadded:: 2.4 - The ``setIdleTimeout`` method was added in Symfony 2.4. + The :method:`Symfony\\Component\\Process\\Process::setIdleTimeout` method was added in Symfony 2.4. In contrast to the timeout of the previous paragraph, the idle timeout only considers the time since the last output was produced by the process:: From 1891edd61ec713d12b114dcbd59dd442b23ee13a Mon Sep 17 00:00:00 2001 From: Luciano Mammino Date: Mon, 22 Jul 2013 01:22:53 +0200 Subject: [PATCH 017/146] Updated documentation for PR https://github.com/symfony/symfony/pull/8490 --- reference/constraints/Image.rst | 182 ++++++++++++++++++++++++++++++-- 1 file changed, 175 insertions(+), 7 deletions(-) diff --git a/reference/constraints/Image.rst b/reference/constraints/Image.rst index ca90c6476c7..7364f319f64 100644 --- a/reference/constraints/Image.rst +++ b/reference/constraints/Image.rst @@ -8,6 +8,11 @@ automatically setup to work for image files specifically. Additionally, as of Symfony 2.1, it has options so you can validate against the width and height of the image. +.. versionadded:: 2.4 + As of Symfony 2.4 you can also validate against the image aspect ratio ( defined + as ``width / height``) and selectively allow square, landscape and portrait + image orientations. + See the :doc:`File` constraint for the bulk of the documentation on this constraint. @@ -19,12 +24,22 @@ the documentation on this constraint. | | - `maxWidth`_ | | | - `maxHeight`_ | | | - `minHeight`_ | +| | - `maxRatio`_ | +| | - `minRatio`_ | +| | - `allowSquare`_ | +| | - `allowLandscape`_ | +| | - `allowPortrait`_ | | | - `mimeTypesMessage`_ | | | - `sizeNotDetectedMessage`_ | | | - `maxWidthMessage`_ | | | - `minWidthMessage`_ | | | - `maxHeightMessage`_ | | | - `minHeightMessage`_ | +| | - `maxRatioMessage`_ | +| | - `minRatioMessage`_ | +| | - `allowSquareMessage`_ | +| | - `allowLandscapeMessage`_ | +| | - `allowPortraitMessage`_ | | | - See :doc:`File` for inherited options | +----------------+----------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Validator\\Constraints\\File` | @@ -82,6 +97,8 @@ it is between a certain size, add the following: .. code-block:: php-annotations // src/Acme/BlogBundle/Entity/Author.php + namespace Acme\BlogBundle\Entity; + use Symfony\Component\Validator\Constraints as Assert; class Author @@ -114,10 +131,10 @@ it is between a certain size, add the following: .. code-block:: php // src/Acme/BlogBundle/Entity/Author.php - // ... + namespace Acme/BlogBundle/Entity use Symfony\Component\Validator\Mapping\ClassMetadata; - use Symfony\Component\Validator\Constraints\Image; + use Symfony\Component\Validator\Constraints as Assert; class Author { @@ -125,7 +142,7 @@ it is between a certain size, add the following: public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('headshot', new Image(array( + $metadata->addPropertyConstraint('headshot', new Assert\Image(array( 'minWidth' => 200, 'maxWidth' => 400, 'minHeight' => 200, @@ -137,6 +154,76 @@ it is between a certain size, add the following: The ``headshot`` property is validated to guarantee that it is a real image and that it is between a certain width and height. +You may also want to guarantee the ``headshot`` image to be square. In this +case you can disable portrait and landscape orientations as shown in the +following code: + +.. configuration-block:: + + .. code-block:: yaml + + # src/Acme/BlogBundle/Resources/config/validation.yml + Acme\BlogBundle\Entity\Author + properties: + headshot: + - Image: + allowLandscape: false + allowPortrait: false + + + .. code-block:: php-annotations + + // src/Acme/BlogBundle/Entity/Author.php + namespace Acme\BlogBundle\Entity; + + use Symfony\Component\Validator\Constraints as Assert; + + class Author + { + /** + * @Assert\Image( + * allowLandscape = false + * allowPortrait = false + * ) + */ + protected $headshot; + } + + .. code-block:: xml + + + + + + + + + + + + .. code-block:: php + + // src/Acme/BlogBundle/Entity/Author.php + namespace Acme\BlogBundle\Entity; + + use Symfony\Component\Validator\Mapping\ClassMetadata; + use Symfony\Component\Validator\Constraints as Assert; + + class Author + { + // ... + + public static function loadValidatorMetadata(ClassMetadata $metadata) + { + $metadata->addPropertyConstraint('headshot', new Assert\Image(array( + 'allowLandscape' => false, + 'allowPortrait' => false, + ))); + } + } + +You can mix all the constraint options to create powerful validation rules. + Options ------- @@ -191,6 +278,43 @@ maxHeight If set, the height of the image file must be less than or equal to this value in pixels. +maxRatio +~~~~~~~~ + +**type**: ``integer`` + +If set, the aspect ratio (``width / height``) of the image file must be less than or equal to this +value. + +minRatio +~~~~~~~~ + +**type**: ``integer`` + +If set, the aspect ratio (``width / height``) of the image file must be greater than or equal to this +value. + +allowSquare +~~~~~~~~~~~ + +**type**: ``Boolean`` **default**: ``true`` + +If this option is false, the image must not be square. + +allowLandscape +~~~~~~~~~~~~~~ + +**type**: ``Boolean`` **default**: ``true`` + +If this option is false, the image must not be landscape oriented. + +allowPortrait +~~~~~~~~~~~~~ + +**type**: ``Boolean`` **default**: ``true`` + +If this option is false, the image must not be portrait oriented. + sizeNotDetectedMessage ~~~~~~~~~~~~~~~~~~~~~~ @@ -203,29 +327,73 @@ options has been set. maxWidthMessage ~~~~~~~~~~~~~~~ -**type**: ``string`` **default**: ``The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px`` +**type**: ``string`` **default**: ``The image width is too big ({{ width }}px). +Allowed maximum width is {{ max_width }}px`` The error message if the width of the image exceeds `maxWidth`_. minWidthMessage ~~~~~~~~~~~~~~~ -**type**: ``string`` **default**: ``The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px`` +**type**: ``string`` **default**: ``The image width is too small ({{ width }}px). +Minimum width expected is {{ min_width }}px`` The error message if the width of the image is less than `minWidth`_. maxHeightMessage ~~~~~~~~~~~~~~~~ -**type**: ``string`` **default**: ``The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px`` +**type**: ``string`` **default**: ``The image height is too big ({{ height }}px). +Allowed maximum height is {{ max_height }}px`` The error message if the height of the image exceeds `maxHeight`_. minHeightMessage ~~~~~~~~~~~~~~~~ -**type**: ``string`` **default**: ``The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px`` +**type**: ``string`` **default**: ``The image height is too small ({{ height }}px). +Minimum height expected is {{ min_height }}px`` The error message if the height of the image is less than `minHeight`_. +maxRatioMessage +~~~~~~~~~~~~~~~ + +**type**: ``string`` **default**: ``The image ratio is too big ({{ ratio }}). +Allowed maximum ratio is {{ max_ratio }}`` + +The error message if the aspect ratio of the image exceeds `maxRatio`_. + +minRatioMessage +~~~~~~~~~~~~~~~ + +**type**: ``string`` **default**: ``The image ratio is too small ({{ ratio }}). +Minimum ratio expected is {{ min_ratio }}`` + +The error message if the aspect ratio of the image is less than `minRatio`_. + +allowSquareMessage +~~~~~~~~~~~~~~~~~~ + +**type**: ``string`` **default**: ``The image is square ({{ width }}x{{ height }}px). +Square images are not allowed`` + +The error message if the image is square and you set `allowSquare`_ to ``false``. + +allowLandscapeMessage +~~~~~~~~~~~~~~~~~~~~~ + +**type**: ``string`` **default**: ``The image is landscape oriented ({{ width }}x{{ height }}px). +Landscape oriented images are not allowed`` + +The error message if the image is landscape oriented and you set `allowLandscape`_ to ``false``. + +allowPortraitMessage +~~~~~~~~~~~~~~~~~~~~ + +**type**: ``string`` **default**: ``The image is portrait oriented ({{ width }}x{{ height }}px). +Portrait oriented images are not allowed`` + +The error message if the image is portrait oriented and you set `allowPoirtrait`_ to ``false``. + .. _`IANA website`: http://www.iana.org/assignments/media-types/image/index.html From 8b0611ab3e615edbfc6bd7c011549f5c7e737ea4 Mon Sep 17 00:00:00 2001 From: Juan Traverso Date: Fri, 9 Aug 2013 16:59:47 +0200 Subject: [PATCH 018/146] [Process] Update docs for modifications. --- components/process.rst | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/components/process.rst b/components/process.rst index afc9e85c98b..f05e6c70ca4 100644 --- a/components/process.rst +++ b/components/process.rst @@ -46,16 +46,10 @@ and :method:`Symfony\\Component\\Process\\Process::getIncrementalErrorOutput` methods returns the new outputs since the last call. .. versionadded:: 2.4 - The ``getAndFlushOutput()``, ``getAndFlushIncrementalOutput()``, ``getAndFlushErrorOutput()``, - ``getAndFlushIncrementalErrorOutput()``, ``flushOutput()`` and ``flushErrorOutput()`` methods were - added in Symfony 2.4. + The ``flushOutput()`` and ``flushErrorOutput()`` methods were added in Symfony 2.4. The :method:`Symfony\\Component\\Process\\Process::flushOutput()` method flushes the contents of the output and -and :method:`Symfony\\Component\\Process\\Process::flushErrorOutput()` the content of the error output. You can get the -contents and flush the whole output or the error output by using :method:`Symfony\\Component\\Process\\Process::getAndFlushOutput()` -and :method:`Symfony\\Component\\Process\\Process::getAndFlushErrorOutput()` methods, or the outputs since the last call -by using the :method:`Symfony\\Component\\Process\\Process::getAndFlushIncrementalOutput()` and -:method:`Symfony\\Component\\Process\\Process::getAndFlushIncrementalErrorOutput()` methods. +and :method:`Symfony\\Component\\Process\\Process::flushErrorOutput()` the content of the error output. Getting real-time Process Output -------------------------------- From 8e6f084a9a980fbd4f9a26328601653eb334a10b Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 10 Aug 2013 04:30:18 -0700 Subject: [PATCH 019/146] [#2840] Minor tweaks to new orientation Image validation constraints --- reference/constraints/Image.rst | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/reference/constraints/Image.rst b/reference/constraints/Image.rst index e376d875485..b303641f16c 100644 --- a/reference/constraints/Image.rst +++ b/reference/constraints/Image.rst @@ -9,9 +9,9 @@ Additionally it has options so you can validate against the width and height of the image. .. versionadded:: 2.4 - As of Symfony 2.4 you can also validate against the image aspect ratio ( defined - as ``width / height``) and selectively allow square, landscape and portrait - image orientations. + As of Symfony 2.4 you can also validate against the image aspect ratio + (defined as ``width / height``) and selectively allow square, landscape + and portrait image orientations. See the :doc:`File` constraint for the bulk of the documentation on this constraint. @@ -284,39 +284,41 @@ value in pixels. maxRatio ~~~~~~~~ -**type**: ``integer`` +**type**: ``float`` -If set, the aspect ratio (``width / height``) of the image file must be less than or equal to this -value. +If set, the aspect ratio (``width / height``) of the image file must be less +than or equal to this value. minRatio ~~~~~~~~ -**type**: ``integer`` +**type**: ``float`` -If set, the aspect ratio (``width / height``) of the image file must be greater than or equal to this -value. +If set, the aspect ratio (``width / height``) of the image file must be greater +than or equal to this value. allowSquare ~~~~~~~~~~~ **type**: ``Boolean`` **default**: ``true`` -If this option is false, the image must not be square. +If this option is false, the image cannot be a square. If you want to force +a square image, then set leave this option as its default ``true`` value +and set `allowLandscape`_ and `allowPortrait`_ both to ``false``. allowLandscape ~~~~~~~~~~~~~~ **type**: ``Boolean`` **default**: ``true`` -If this option is false, the image must not be landscape oriented. +If this option is false, the image cannot be landscape oriented. allowPortrait ~~~~~~~~~~~~~ **type**: ``Boolean`` **default**: ``true`` -If this option is false, the image must not be portrait oriented. +If this option is false, the image cannot be portrait oriented. sizeNotDetectedMessage ~~~~~~~~~~~~~~~~~~~~~~ @@ -324,7 +326,7 @@ sizeNotDetectedMessage **type**: ``string`` **default**: ``The size of the image could not be detected`` If the system is unable to determine the size of the image, this error will -be displayed. This will only occur when at least one of the four size constraint +be displayed. This will only occur when at least one of the size constraint options has been set. maxWidthMessage @@ -397,6 +399,6 @@ allowPortraitMessage **type**: ``string`` **default**: ``The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed`` -The error message if the image is portrait oriented and you set `allowPoirtrait`_ to ``false``. +The error message if the image is portrait oriented and you set `allowPortrait`_ to ``false``. .. _`IANA website`: http://www.iana.org/assignments/media-types/image/index.html From 03aaa5c195da6003faf3135d61a5c0c87ee5ad9e Mon Sep 17 00:00:00 2001 From: Jeroen van den Enden Date: Sun, 11 Aug 2013 14:12:13 +0200 Subject: [PATCH 020/146] Document possibility to use ContainerAwareTrait In addition to https://github.com/symfony/symfony/pull/8488 --- book/controller.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/book/controller.rst b/book/controller.rst index c8e01927de2..5955938a626 100644 --- a/book/controller.rst +++ b/book/controller.rst @@ -378,8 +378,11 @@ itself. Extending the base class is *optional* in Symfony; it contains useful shortcuts but nothing mandatory. You can also extend - :class:`Symfony\\Component\\DependencyInjection\\ContainerAware`. The service - container object will then be accessible via the ``container`` property. + :class:`Symfony\\Component\\DependencyInjection\\ContainerAware`or use the + :class:`Symfony\\Component\\DependencyInjection\\ContainerAwareTrait` (>= PHP 5.4). + Both provide an implementation to the + :class:`Symfony\\Component\\DependencyInjection\\ContainerAwareInterface`, making the + service container object accessible via the ``container`` property. .. note:: From 3d27f535b139d1abde92fea5ab3aec16731f675e Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 17 Aug 2013 12:23:10 -0400 Subject: [PATCH 021/146] [#2630] Tweaks for new stopwatch tag - updating version, syntax for using it, and wrong bundle name --- reference/twig_reference.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index a6cbfc1d8a4..c7abf7cb716 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -134,8 +134,8 @@ Filters Tags ---- -.. versionadded:: 2.3 - The stopwatch tag was added in Symfony 2.3 +.. versionadded:: 2.4 + The stopwatch tag was added in Symfony 2.4. +---------------------------------------------------+--------------------------------------------------------------------+ | Tag Syntax | Usage | @@ -153,8 +153,8 @@ Tags | ``{% trans_default_domain language %}`` | This will set the default domain for message catalogues in the | | | current template | +---------------------------------------------------+--------------------------------------------------------------------+ -| ``{% stopwatch name %}...{% endstopwatch %}`` | This will time the run time of the code inside it and put that on | -| | the timeline of the WebDeveloperBundle. | +| ``{% stopwatch 'name' %}...{% endstopwatch %}`` | This will time the run time of the code inside it and put that on | +| | the timeline of the WebProfilerBundle. | +---------------------------------------------------+--------------------------------------------------------------------+ Tests From c6e50b769ad5a4c4ddbc0492fa25c9e243b7ff54 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 17 Aug 2013 13:20:35 -0400 Subject: [PATCH 022/146] Removing several "2.1" references, which is consistent with our release process: "Remove all versionadded directives - and any other notes related to features changing or being new - for the version (e.g. 2.1) from the master branch. The result is that the next release (which is the first that comes entirely after the end of maintenance of this branch), will have no mentions of the old version (e.g. 2.1)." This should have been done when 2.1 reached end of maintenance, but the release process wasn't formed at that time. Also, the release of 2.3 and the end of maintenance for 2.1 were unique because they basically happened at the same time. For our purposes, we assume that 2.3 was released before the 2.1 end of life, which means that the 2.1 references are removed for 2.4 (master), not for 2.3. --- book/forms.rst | 5 ----- book/security.rst | 10 ++++------ book/translation.rst | 5 ----- components/config/definition.rst | 7 ++----- components/event_dispatcher/immutable_dispatcher.rst | 3 --- components/process.rst | 3 --- cookbook/configuration/pdo_session_storage.rst | 7 ------- reference/constraints/Regex.rst | 3 --- reference/dic_tags.rst | 6 ------ 9 files changed, 6 insertions(+), 43 deletions(-) diff --git a/book/forms.rst b/book/forms.rst index b23e895b1b6..70f0fc934ab 100644 --- a/book/forms.rst +++ b/book/forms.rst @@ -1792,11 +1792,6 @@ The answer is to setup the constraints yourself, and attach them to the individu fields. The overall approach is covered a bit more in the :ref:`validation chapter`, but here's a short example: -.. versionadded:: 2.1 - The ``constraints`` option, which accepts a single constraint or an array - of constraints (before 2.1, the option was called ``validation_constraint``, - and only accepted a single constraint) is new to Symfony 2.1. - .. code-block:: php use Symfony\Component\Validator\Constraints\Length; diff --git a/book/security.rst b/book/security.rst index 071ce973635..1cd411ac422 100644 --- a/book/security.rst +++ b/book/security.rst @@ -418,12 +418,8 @@ submission (i.e. ``/login_check``): You will *not* need to implement a controller for the ``/login_check`` URL as the firewall will automatically catch and process any form submitted - to this URL. - -.. versionadded:: 2.1 - As of Symfony 2.1, you *must* have routes configured for your ``login_path``, - ``check_path`` ``logout`` keys. These keys can be route names (as shown - in this example) or URLs that have routes configured for them. + to this URL. However, you *must* have a route (as shown here) for this + URL, as well as one for your logout path (see :ref:`book-security-logging-out`). Notice that the name of the ``login`` route matches the ``login_path`` config value, as that's where the security system will redirect users that need @@ -1700,6 +1696,8 @@ In the above configuration, users with ``ROLE_ADMIN`` role will also have the ``ROLE_USER`` role. The ``ROLE_SUPER_ADMIN`` role has ``ROLE_ADMIN``, ``ROLE_ALLOWED_TO_SWITCH`` and ``ROLE_USER`` (inherited from ``ROLE_ADMIN``). +.. _book-security-logging-out: + Logging Out ----------- diff --git a/book/translation.rst b/book/translation.rst index 360c17b602b..d9a3b1ddfe0 100644 --- a/book/translation.rst +++ b/book/translation.rst @@ -557,11 +557,6 @@ by defining a ``default_locale`` for the framework: 'default_locale' => 'en', )); -.. versionadded:: 2.1 - The ``default_locale`` parameter was defined under the session key - originally, however, as of 2.1 this has been moved. This is because the - locale is now set on the request instead of the session. - .. _book-translation-locale-url: The Locale and the URL diff --git a/components/config/definition.rst b/components/config/definition.rst index d43aea02052..cb901ceb169 100644 --- a/components/config/definition.rst +++ b/components/config/definition.rst @@ -100,8 +100,8 @@ node definition. Node type are available for: * scalar * boolean * integer (new in 2.2) -* float (new in 2.2) -* enum (new in 2.1) +* float +* enum * array * variable (no validation) @@ -136,9 +136,6 @@ allowing to validate the value:: Enum nodes ~~~~~~~~~~ -.. versionadded:: 2.1 - The enum node is new in Symfony 2.1 - Enum nodes provide a constraint to match the given input against a set of values:: diff --git a/components/event_dispatcher/immutable_dispatcher.rst b/components/event_dispatcher/immutable_dispatcher.rst index c5d17eb6f00..5b01136e558 100644 --- a/components/event_dispatcher/immutable_dispatcher.rst +++ b/components/event_dispatcher/immutable_dispatcher.rst @@ -4,9 +4,6 @@ The Immutable Event Dispatcher ============================== -.. versionadded:: 2.1 - This feature was added in Symfony 2.1. - The :class:`Symfony\\Component\\EventDispatcher\\ImmutableEventDispatcher` is a locked or frozen event dispatcher. The dispatcher cannot register new listeners or subscribers. diff --git a/components/process.rst b/components/process.rst index c10824d77dd..a13e901329a 100644 --- a/components/process.rst +++ b/components/process.rst @@ -64,9 +64,6 @@ anonymous function to the } }); -.. versionadded:: 2.1 - The non-blocking feature was added in 2.1. - Running Processes Asynchronously -------------------------------- diff --git a/cookbook/configuration/pdo_session_storage.rst b/cookbook/configuration/pdo_session_storage.rst index 758b7b0fb92..a6b1886682b 100644 --- a/cookbook/configuration/pdo_session_storage.rst +++ b/cookbook/configuration/pdo_session_storage.rst @@ -14,13 +14,6 @@ Symfony2 has a built-in solution for database session storage called To use it, you just need to change some parameters in ``config.yml`` (or the configuration format of your choice): -.. versionadded:: 2.1 - In Symfony2.1 the class and namespace are slightly modified. You can now - find the session storage classes in the `Session\\Storage` namespace: - ``Symfony\Component\HttpFoundation\Session\Storage``. Also - note that in Symfony2.1 you should configure ``handler_id`` not ``storage_id`` like in Symfony2.0. - Below, you'll notice that ``%session.storage.options%`` is not used anymore. - .. configuration-block:: .. code-block:: yaml diff --git a/reference/constraints/Regex.rst b/reference/constraints/Regex.rst index 2bdf0a8a87c..784600743e4 100644 --- a/reference/constraints/Regex.rst +++ b/reference/constraints/Regex.rst @@ -177,9 +177,6 @@ string *does* match this pattern. htmlPattern ~~~~~~~~~~~ -.. versionadded:: 2.1 - The ``htmlPattern`` option was added in Symfony 2.1 - **type**: ``string|Boolean`` **default**: null This option specifies the pattern to use in the HTML5 ``pattern`` attribute. diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index ca23140ddcb..fe284080688 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -964,9 +964,6 @@ translation.extractor **Purpose**: To register a custom service that extracts messages from a file -.. versionadded:: 2.1 - The ability to add message extractors is new in Symfony 2.1. - When executing the ``translation:update`` command, it uses extractors to extract translation messages from a file. By default, the Symfony2 framework has a :class:`Symfony\\Bridge\\Twig\\Translation\\TwigExtractor` and a @@ -1035,9 +1032,6 @@ translation.dumper **Purpose**: To register a custom service that dumps messages to a file -.. versionadded:: 2.1 - The ability to add message dumpers is new in Symfony 2.1. - After an `Extractor `_ has extracted all messages from the templates, the dumpers are executed to dump the messages to a translation file in a specific format. From a801c09bf18ac6ee67161230aa4e7361ad63824c Mon Sep 17 00:00:00 2001 From: endroid Date: Tue, 27 Aug 2013 18:53:36 -0400 Subject: [PATCH 023/146] Improve documentation of ContentAwareTrait --- book/controller.rst | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) mode change 100644 => 100755 book/controller.rst diff --git a/book/controller.rst b/book/controller.rst old mode 100644 new mode 100755 index 5955938a626..0c1ea72abb9 --- a/book/controller.rst +++ b/book/controller.rst @@ -378,11 +378,17 @@ itself. Extending the base class is *optional* in Symfony; it contains useful shortcuts but nothing mandatory. You can also extend - :class:`Symfony\\Component\\DependencyInjection\\ContainerAware`or use the - :class:`Symfony\\Component\\DependencyInjection\\ContainerAwareTrait` (>= PHP 5.4). - Both provide an implementation to the - :class:`Symfony\\Component\\DependencyInjection\\ContainerAwareInterface`, making the - service container object accessible via the ``container`` property. + :class:`Symfony\\Component\\DependencyInjection\\ContainerAware`. The service + container object will then be accessible via the ``container`` property. + +.. tip:: + + If your host uses PHP 5.4 or higher, you can also use the + class:`Symfony\\Component\\DependencyInjection\\ContainerAwareTrait` trait to + make the container accessible via the ``container`` property. + +.. versionadded:: 2.4 + The ``ContainerAwareTrait`` is new in Symfony 2.4 .. note:: From 066fcd5cac6293869c581058385add43891d1989 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20G=C3=A4rtner?= Date: Sun, 1 Sep 2013 15:49:13 +0200 Subject: [PATCH 024/146] Added docs for the changes proposed in symfony/symfony#8908 --- components/filesystem.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/filesystem.rst b/components/filesystem.rst index df97db82ca6..9b9ffef2eb1 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -28,7 +28,7 @@ endpoint for filesystem operations:: try { $fs->mkdir('/tmp/random/dir/' . mt_rand()); } catch (IOException $e) { - echo "An error occurred while creating your directory"; + echo "An error occurred while creating your directory at ".$e.getPath(); } .. note:: @@ -251,7 +251,7 @@ Error Handling -------------- Whenever something wrong happens, an exception implementing -:class:`Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface` is +:class:`Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface` and :class:`Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface` is thrown. .. note:: From 7afa87fbea5bba2b1799b1d2b93a0af3e20c31b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20G=C3=A4rtner?= Date: Sun, 1 Sep 2013 16:55:44 +0200 Subject: [PATCH 025/146] Update filesystem.rst --- components/filesystem.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/filesystem.rst b/components/filesystem.rst index 9b9ffef2eb1..60344f6212e 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -251,8 +251,8 @@ Error Handling -------------- Whenever something wrong happens, an exception implementing -:class:`Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface` and :class:`Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface` is -thrown. +:class:`Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface` and +:class:`Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface` is thrown. .. note:: From feb346d14c16b11d54136d4025b6ddeb335e8cc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20G=C3=A4rtner?= Date: Sun, 1 Sep 2013 21:59:54 +0200 Subject: [PATCH 026/146] Update filesystem.rst --- components/filesystem.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/filesystem.rst b/components/filesystem.rst index 60344f6212e..21c1afc1291 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -28,7 +28,7 @@ endpoint for filesystem operations:: try { $fs->mkdir('/tmp/random/dir/' . mt_rand()); } catch (IOException $e) { - echo "An error occurred while creating your directory at ".$e.getPath(); + echo "An error occurred while creating your directory at ".$e->getPath(); } .. note:: From d9050a56d6a2574b0be48c6a907dff647fb22f03 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 8 Sep 2013 08:30:32 +0200 Subject: [PATCH 027/146] added documentation for the new request_stack service --- book/service_container.rst | 38 +++++++++++++++++++++------ cookbook/service_container/scopes.rst | 16 +++++------ 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/book/service_container.rst b/book/service_container.rst index c8e64bc7c4f..d24b77d95d6 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -270,14 +270,6 @@ looks up the value of each parameter and uses it in the service definition. http://symfony.com/?foo=%%s&bar=%%d -.. caution:: - - You may receive a - :class:`Symfony\\Component\\DependencyInjection\\Exception\\ScopeWideningInjectionException` - when passing the ``request`` service as an argument. To understand this - problem better and learn how to solve it, refer to the cookbook article - :doc:`/cookbook/service_container/scopes`. - The purpose of parameters is to feed information into services. Of course there was nothing wrong with defining the service without using any parameters. Parameters, however, have several advantages: @@ -762,6 +754,36 @@ Injecting the dependency by the setter method just needs a change of syntax: and "setter injection". The Symfony2 service container also supports "property injection". +Injecting the Request +~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 2.4 + The ``request_stack`` service was introduced in version 2.4. + +Almost all Symfony2 built-in services behave in the same way: a single +instance is created by the container which it returns whenever you get it or +when it is injected into another service. There is one exception in a standard +Symfony2 application: the ``request`` service. + +If you try to inject the ``request`` into a service, you will probably receive +a +:class:`Symfony\\Component\\DependencyInjection\\Exception\\ScopeWideningInjectionException` +exception. That's because the ``request`` can **change** during the life-time +of a container (when a sub-request is created for instance). + +As of Symfony 2.4, instead of injecting the ``request`` service, you should +inject the ``request_stack`` service instead and access the Request by calling +the ``getCurrentRequest()`` method. For earlier versions, or if you want to +understand this problem better, refer to the cookbook article +:doc:`/cookbook/service_container/scopes`. + +.. tip:: + + If you define a controller as a service then you can get the ``Request`` + object without injecting the container by having it passed in as an + argument of your action method. See + :ref:`book-controller-request-argument` for details. + Making References Optional -------------------------- diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 8f5e8af0cfe..68a301a1101 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -6,8 +6,13 @@ How to work with Scopes This entry is all about scopes, a somewhat advanced topic related to the :doc:`/book/service_container`. If you've ever gotten an error mentioning -"scopes" when creating services, or need to create a service that depends -on the ``request`` service, then this entry is for you. +"scopes" when creating services, then this entry is for you. + +.. note:: + + If you are trying to inject the ``request`` service, the simple solution + is to inject the ``request_stack`` service instead and access the current + Request by calling the ``getCurrentRequest()`` method. Understanding Scopes -------------------- @@ -337,10 +342,3 @@ The service config for this class would look something like this: Injecting the whole container into a service is generally not a good idea (only inject what you need). - -.. tip:: - - If you define a controller as a service then you can get the ``Request`` - object without injecting the container by having it passed in as an - argument of your action method. See - :ref:`book-controller-request-argument` for details. From 3780933fb43bc357d94e196e3011b3599d3d87bc Mon Sep 17 00:00:00 2001 From: WouterJ Date: Tue, 10 Sep 2013 21:51:03 +0200 Subject: [PATCH 028/146] Documented Stopwatch Helper --- cookbook/templating/PHP.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/cookbook/templating/PHP.rst b/cookbook/templating/PHP.rst index a3454abbb29..759e124e0d2 100644 --- a/cookbook/templating/PHP.rst +++ b/cookbook/templating/PHP.rst @@ -310,6 +310,21 @@ portable. Thanks to this helper, you can move the application root directory anywhere under your web root directory without changing anything in your template's code. +Profiling Templates +~~~~~~~~~~~~~~~~~~~ + +Using the ``stopwatch`` helper, you are able to time parts of your template +and display it on the timeline of the WebProfilerBundle:: + + start('foo') ?> + ... things that gets timed + stop('foo') ?> + +.. tip:: + + If you use the same name more than once in your template, the times are + grouped on the same line in the timeline. + Output Escaping --------------- From b84f52c28d969b5143521261d818105824eaea5e Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 11 Sep 2013 21:40:59 -0500 Subject: [PATCH 029/146] [#2956] A few more changes to the scopes chapter to update the new way of working with the request service --- cookbook/service_container/scopes.rst | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 68a301a1101..f305a97837d 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -79,12 +79,14 @@ when compiling the container. Read the sidebar below for more details. Using a Service from a narrower Scope ------------------------------------- -If your service has a dependency on a scoped service (like the ``request``), -you have three ways to deal with it: +The most common problem with "scope" is when your service has a dependency +on the ``request`` service. The *easiest* way to solve this is to instead +inject the ``request_stack`` service and access the current Request by calling +the ``getCurrentRequest()`` method. -* Use setter injection if the dependency is "synchronized"; this is the - recommended way and the best solution for the ``request`` instance as it is - synchronized with the ``request`` scope (see +This solution is great, but there are also others: + +* Use setter injection if the dependency is "synchronized"; (see :ref:`using-synchronized-service`). * Put your service in the same scope as the dependency (or a narrower one). If @@ -108,7 +110,7 @@ Using a synchronized Service Injecting the container or setting your service to a narrower scope have drawbacks. For synchronized services (like the ``request``), using setter -injection is the best option as it has no drawbacks and everything works +injection is a nice option as it has no drawbacks and everything works without any special code in your service or in your definition:: // src/Acme/HelloBundle/Mail/Mailer.php From 67901ff4a4c4dbdedc6e4f11479759efdc4ed10a Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Thu, 12 Sep 2013 19:49:24 +0200 Subject: [PATCH 030/146] document the getEncodings() method of the Request class --- components/http_foundation/introduction.rst | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/components/http_foundation/introduction.rst b/components/http_foundation/introduction.rst index f15372da975..0f64bc3f59f 100644 --- a/components/http_foundation/introduction.rst +++ b/components/http_foundation/introduction.rst @@ -240,7 +240,13 @@ by using the following methods: returns the list of accepted languages ordered by descending quality; * :method:`Symfony\\Component\\HttpFoundation\\Request::getCharsets`: - returns the list of accepted charsets ordered by descending quality. + returns the list of accepted charsets ordered by descending quality; + +* :method:`Symfony\\Component\\HttpFoundation\\Request::getEncodings`: + returns the list of accepted encodings in preferable order. + + .. versionadded:: 2.4 + The ``getEncodings()`` method was added in Symfony 2.4. .. versionadded:: 2.2 The :class:`Symfony\\Component\\HttpFoundation\\AcceptHeader` class is new in Symfony 2.2. From 3210251af21fc96b0f23129c69517f5ff362531d Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 18 Sep 2013 09:09:39 -0500 Subject: [PATCH 031/146] [#2891] Shortening note about ContainerAwareTrait --- book/controller.rst | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/book/controller.rst b/book/controller.rst index 74979301a6d..6904bd10248 100755 --- a/book/controller.rst +++ b/book/controller.rst @@ -392,17 +392,13 @@ itself. Extending the base class is *optional* in Symfony; it contains useful shortcuts but nothing mandatory. You can also extend - :class:`Symfony\\Component\\DependencyInjection\\ContainerAware`. The service - container object will then be accessible via the ``container`` property. - -.. tip:: - - If your host uses PHP 5.4 or higher, you can also use the - class:`Symfony\\Component\\DependencyInjection\\ContainerAwareTrait` trait to - make the container accessible via the ``container`` property. + :class:`Symfony\\Component\\DependencyInjection\\ContainerAware` or use + the class:`Symfony\\Component\\DependencyInjection\\ContainerAwareTrait` trait + (if you have PHP 5.4). The service container object will then be accessible + via the ``container`` property. .. versionadded:: 2.4 - The ``ContainerAwareTrait`` is new in Symfony 2.4 + The ``ContainerAwareTrait`` is new in Symfony 2.4. .. note:: From 887f0d2b682f58b5205c23de1f434b4ea652180f Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Thu, 26 Sep 2013 13:06:36 +0200 Subject: [PATCH 032/146] Updated the documentation for the simplified Callback constraint --- reference/constraints/Callback.rst | 253 +++++++++++++++++------------ 1 file changed, 147 insertions(+), 106 deletions(-) diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index a367ac9f5d5..93a279068b5 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -1,7 +1,12 @@ Callback ======== -The purpose of the Callback assertion is to let you create completely custom +.. versionadded:: 2.4 + The ``Callback`` constraint was simplified in Symfony 2.4. For usage + examples with older Symfony versions, see the corresponding versions of this + documentation page. + +The purpose of the Callback constraint is to create completely custom validation rules and to assign any validation errors to specific fields on your object. If you're using validation with forms, this means that you can make these custom errors display next to a specific field, instead of simply @@ -20,15 +25,15 @@ can do anything, including creating and assigning validation errors. +----------------+------------------------------------------------------------------------+ | Applies to | :ref:`class` | +----------------+------------------------------------------------------------------------+ -| Options | - `methods`_ | +| Options | - `callback`_ | +----------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Validator\\Constraints\\Callback` | +----------------+------------------------------------------------------------------------+ | Validator | :class:`Symfony\\Component\\Validator\\Constraints\\CallbackValidator` | +----------------+------------------------------------------------------------------------+ -Setup ------ +Configuration +------------- .. configuration-block:: @@ -37,8 +42,7 @@ Setup # src/Acme/BlogBundle/Resources/config/validation.yml Acme\BlogBundle\Entity\Author: constraints: - - Callback: - methods: [isAuthorValid] + - Callback: validate .. code-block:: php-annotations @@ -46,12 +50,17 @@ Setup namespace Acme\BlogBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; + use Symfony\Component\Validator\ExecutionContextInterface; - /** - * @Assert\Callback(methods={"isAuthorValid"}) - */ class Author { + /** + * @Assert\Callback + */ + public function validate(ExecutionContextInterface $context) + { + // ... + } } .. code-block:: xml @@ -63,11 +72,7 @@ Setup xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd"> - - - + validate @@ -83,9 +88,7 @@ Setup { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addConstraint(new Assert\Callback(array( - 'methods' => array('isAuthorValid'), - ))); + $metadata->addConstraint(new Assert\Callback('validate')); } } @@ -98,133 +101,171 @@ those errors should be attributed:: // ... use Symfony\Component\Validator\ExecutionContextInterface; - + class Author { // ... private $firstName; - - public function isAuthorValid(ExecutionContextInterface $context) + + public function validate(ExecutionContextInterface $context) { // somehow you have an array of "fake names" - $fakeNames = array(); - + $fakeNames = array(/* ... */); + // check if the name is actually a fake name if (in_array($this->getFirstName(), $fakeNames)) { - $context->addViolationAt('firstname', 'This name sounds totally fake!', array(), null); + $context->addViolationAt('firstName', 'This name sounds totally fake!', array(), null); } } } -Options -------- +Static Callbacks +---------------- -methods -~~~~~~~ +You can also use the constraint with static methods. Since static methods don't +have access to the object instance, they receive the object as first argument:: -**type**: ``array`` **default**: ``array()`` [:ref:`default option`] + public static function validate($object, ExecutionContextInterface $context) + { + // somehow you have an array of "fake names" + $fakeNames = array(/* ... */); -This is an array of the methods that should be executed during the validation -process. Each method can be one of the following formats: + // check if the name is actually a fake name + if (in_array($object->getFirstName(), $fakeNames)) { + $context->addViolationAt('firstName', 'This name sounds totally fake!', array(), null); + } + } -1) **String method name** +External Callbacks and Closures +------------------------------- - If the name of a method is a simple string (e.g. ``isAuthorValid``), that - method will be called on the same object that's being validated and the - ``ExecutionContextInterface`` will be the only argument (see the above example). +If you want to execute a static callback method that is not located in the class +of the validated object, you can configure the constraint to invoke an array +callable as supported by PHP's :phpfunction:`call_user_func` function. Suppose +your validation function is `Vendor\Package\Validator::validate()`:: -2) **Static array callback** + namespace Vendor\Package; - Each method can also be specified as a standard array callback: + use Symfony\Component\Validator\ExecutionContextInterface; - .. configuration-block:: + class Validator + { + public function validate($object, ExecutionContextInterface $context) + { + // ... + } + } - .. code-block:: yaml +You can then use the following configuration to invoke this validator:: - # src/Acme/BlogBundle/Resources/config/validation.yml - Acme\BlogBundle\Entity\Author: - constraints: - - Callback: - methods: - - [Acme\BlogBundle\MyStaticValidatorClass, isAuthorValid] +.. configuration-block:: - .. code-block:: php-annotations + .. code-block:: yaml - // src/Acme/BlogBundle/Entity/Author.php - use Symfony\Component\Validator\Constraints as Assert; + # src/Acme/BlogBundle/Resources/config/validation.yml + Acme\BlogBundle\Entity\Author: + constraints: + - Callback: [Vendor\Package\Validator, validate] - /** - * @Assert\Callback(methods={ - * { "Acme\BlogBundle\MyStaticValidatorClass", "isAuthorValid"} - * }) - */ - class Author - { - } + .. code-block:: php-annotations - .. code-block:: xml + // src/Acme/BlogBundle/Entity/Author.php + namespace Acme\BlogBundle\Entity; - - - + use Symfony\Component\Validator\Constraints as Assert; + use Symfony\Component\Validator\ExecutionContextInterface; - - - - - - + /** + * @Assert\Callback({"Vendor\Package\Validator", "validate"}) + */ + class Author + { + } - .. code-block:: php + .. code-block:: xml - // src/Acme/BlogBundle/Entity/Author.php + + + + + + + Vendor\Package\Validator + validate + + + - use Symfony\Component\Validator\Mapping\ClassMetadata; - use Symfony\Component\Validator\Constraints\Callback; + .. code-block:: php - class Author + // src/Acme/BlogBundle/Entity/Author.php + namespace Acme\BlogBundle\Entity; + + use Symfony\Component\Validator\Mapping\ClassMetadata; + use Symfony\Component\Validator\Constraints as Assert; + + class Author + { + public static function loadValidatorMetadata(ClassMetadata $metadata) { - public $name; - - public static function loadValidatorMetadata(ClassMetadata $metadata) - { - $metadata->addConstraint(new Callback(array( - 'methods' => array( - array('Acme\BlogBundle\MyStaticValidatorClass', 'isAuthorValid'), - ), - ))); - } + $metadata->addConstraint(new Assert\Callback(array( + 'Vendor\Package\Validator', + 'validate' + ))); } + } - In this case, the static method ``isAuthorValid`` will be called on the - ``Acme\BlogBundle\MyStaticValidatorClass`` class. It's passed both the original - object being validated (e.g. ``Author``) as well as the ``ExecutionContextInterface``:: +.. note:: - namespace Acme\BlogBundle; - - use Symfony\Component\Validator\ExecutionContextInterface; - use Acme\BlogBundle\Entity\Author; - - class MyStaticValidatorClass + The Callback constraint does *not* support global callback functions or + It is *not* possible to specify a global function or a :term:`service` + method as callback. To validate using a service, you should + :doc:`create a custom validation constraint` + and add that new constraint to your class. + +When configuring the constraint via PHP, you can also pass a closure to the +constructor of the Callback constraint:: + + // src/Acme/BlogBundle/Entity/Author.php + namespace Acme\BlogBundle\Entity; + + use Symfony\Component\Validator\Mapping\ClassMetadata; + use Symfony\Component\Validator\Constraints as Assert; + + class Author + { + public static function loadValidatorMetadata(ClassMetadata $metadata) { - public static function isAuthorValid(Author $author, ExecutionContextInterface $context) - { + $callback = function ($object, ExecutionContextInterface $context) { // ... - } + }; + + $metadata->addConstraint(new Assert\Callback($callback)); } + } + +Options +------- + +callback +~~~~~~~~ + +**type**: ``string``, ``array`` or ``Closure`` [:ref:`default option`] + +The callback option accepts three different formats for specifying the +callback method: + +* A **string** containing the name of a concrete or static method. + +* An array callable with the format ``array('', '')``. + +* A closure. - .. tip:: +Concrete callbacks receive an :class:`Symfony\\Component\\Validator\\ExecutionContextInterface` +instance as only argument. - If you specify your ``Callback`` constraint via PHP, then you also have - the option to make your callback either a PHP closure or a non-static - callback. It is *not* currently possible, however, to specify a :term:`service` - as a constraint. To validate using a service, you should - :doc:`create a custom validation constraint` - and add that new constraint to your class. +Static or closure callbacks receive the validated object as first argument +and the :class:`Symfony\\Component\\Validator\\ExecutionContextInterface` +instance as second argument. From 893a7806c1c93c89f8435c414a7148cd2966d0e6 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 26 Sep 2013 14:33:14 -0500 Subject: [PATCH 033/146] [#3009] Updating information for 2.4 with the new checkPasswordLength method --- components/security/authentication.rst | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/components/security/authentication.rst b/components/security/authentication.rst index 016dde98c46..0f7c63d523b 100644 --- a/components/security/authentication.rst +++ b/components/security/authentication.rst @@ -198,10 +198,8 @@ own, it just needs to follow these rules: #. The class must implement :class:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface`; -#. The first line in ``encodePassword`` and ``isPasswordValid`` must check - to make sure the password is not too long (e.g. 4096). This is for security - (see `CVE-2013-5750`_), and you can copy the `BasePasswordEncoder::checkPasswordLength`_ - implementation from Symfony 2.4. +#. ``$this->checkPasswordLength($raw);`` must be the first code executed in + ``encodePassword()`` and ``isPasswordValid()`` (see `CVE-2013-5750`_). Using Password Encoders ~~~~~~~~~~~~~~~~~~~~~~~ @@ -227,5 +225,4 @@ which should be used to encode this user's password:: $password, $user->getSalt()); -.. _`CVE-2013-5750`: http://symfony.com/blog/cve-2013-5750-security-issue-in-fosuserbundle-login-form -.. _`BasePasswordEncoder::checkPasswordLength`: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Core/Encoder/BasePasswordEncoder.php \ No newline at end of file +.. _`CVE-2013-5750`: http://symfony.com/blog/cve-2013-5750-security-issue-in-fosuserbundle-login-form \ No newline at end of file From 574d7a826a15aaa83e96eb492437767016bb2551 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 28 Sep 2013 17:56:23 -0500 Subject: [PATCH 034/146] [#2913] Removing versionadded 2.1 messages from the master branch --- components/class_loader/cache_class_loader.rst | 6 ------ components/class_loader/class_loader.rst | 3 --- components/class_loader/debug_class_loader.rst | 3 --- 3 files changed, 12 deletions(-) diff --git a/components/class_loader/cache_class_loader.rst b/components/class_loader/cache_class_loader.rst index dbce3ce1929..01a393de216 100644 --- a/components/class_loader/cache_class_loader.rst +++ b/components/class_loader/cache_class_loader.rst @@ -26,9 +26,6 @@ for a class. ApcClassLoader -------------- -.. versionadded:: 2.1 - The ``ApcClassLoader`` class was added in Symfony 2.1. - ``ApcClassLoader`` wraps an existing class loader and caches calls to its ``findFile()`` method using `APC`_:: @@ -49,9 +46,6 @@ ApcClassLoader XcacheClassLoader ----------------- -.. versionadded:: 2.1 - The ``XcacheClassLoader`` class was added in Symfony 2.1. - ``XcacheClassLoader`` uses `XCache`_ to cache a class loader. Registering it is straightforward:: diff --git a/components/class_loader/class_loader.rst b/components/class_loader/class_loader.rst index c5f2d65b70d..44de944443e 100644 --- a/components/class_loader/class_loader.rst +++ b/components/class_loader/class_loader.rst @@ -4,9 +4,6 @@ The PSR-0 Class Loader ====================== -.. versionadded:: 2.1 - The ``ClassLoader`` class was added in Symfony 2.1. - If your classes and third-party libraries follow the `PSR-0`_ standard, you can use the :class:`Symfony\\Component\\ClassLoader\\ClassLoader` class to load all of your project's classes. diff --git a/components/class_loader/debug_class_loader.rst b/components/class_loader/debug_class_loader.rst index 2af2e158401..7533f715b07 100644 --- a/components/class_loader/debug_class_loader.rst +++ b/components/class_loader/debug_class_loader.rst @@ -4,9 +4,6 @@ Debugging a Class Loader ======================== -.. versionadded:: 2.1 - The ``DebugClassLoader`` class was added in Symfony 2.1. - The :class:`Symfony\\Component\\ClassLoader\\DebugClassLoader` attempts to throw more helpful exceptions when a class isn't found by the registered autoloaders. All autoloaders that implement a ``findFile()`` method are replaced From a8666062621a3638abf156e17f86420a1fc7ca4e Mon Sep 17 00:00:00 2001 From: Adrien Brault Date: Fri, 27 Sep 2013 15:53:12 -0700 Subject: [PATCH 035/146] Add a cookbook entry on how to limit session metadata writes --- cookbook/map.rst.inc | 1 + cookbook/session/index.rst | 3 +- cookbook/session/limit_metadata_writes.rst | 68 ++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 cookbook/session/limit_metadata_writes.rst diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index c4196b0b035..d98207e594d 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -148,6 +148,7 @@ * :doc:`/cookbook/session/locale_sticky_session` * :doc:`/cookbook/session/sessions_directory` * :doc:`/cookbook/session/php_bridge` + * :doc:`/cookbook/session/limit_metadata_writes` * **symfony1** diff --git a/cookbook/session/index.rst b/cookbook/session/index.rst index 536ad02c3d8..dede3362434 100644 --- a/cookbook/session/index.rst +++ b/cookbook/session/index.rst @@ -7,4 +7,5 @@ Sessions proxy_examples locale_sticky_session sessions_directory - php_bridge \ No newline at end of file + php_bridge + limit_metadata_writes diff --git a/cookbook/session/limit_metadata_writes.rst b/cookbook/session/limit_metadata_writes.rst new file mode 100644 index 00000000000..b2d0208d21c --- /dev/null +++ b/cookbook/session/limit_metadata_writes.rst @@ -0,0 +1,68 @@ +.. index:: + single: Limit Metadata Writes; Session + +Limit session metadata writes +============================= + +.. versionadded:: 2.4 + The ability to limit session metadata writes was added in Symfony 2.4. + +The default behaviour of PHP session is to persist the session regardless of +whether the session data has changed or not. In Symfony, each time the session +is accessed metadata is recorded (session created/last used) which can be used +to determine session age and idle time. + +If for performance reasons you wish to limit the frequency at which the session +persists, this feature can adjust the granularity of the metadata updates and +persist the session less often while still maintaining relatively accurate +metadata. If other session data is changed, the session will always persist. + +You can tell Symfony not to update the metadata "session last updated" time +until a certain amount of time has passed, by setting +``framework.session.metadata_update_threshold`` to a value in seconds greater +than zero: + +.. configuration-block:: + + .. code-block:: yaml + + framework: + session: + metadata_update_threshold: 120 + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + $container->loadFromExtension('framework', array( + 'session' => array( + 'metadata_update_threshold' => 120, + ), + )); + +.. info:: + + PHP default's behavior is to save the session whether it has been changed or + not. When using ``framework.session.metadata_update_threshold`` Symfony + will wrap the session handler (configured at + ``framework.session.handler_id``) into the WriteCheckSessionHandler, that + will prevent any session write if the session was not modified. + +.. caution:: + + Be aware that if the session is not written at every request, it may be + garbage collected sooner than usual. This means that your users may be + logged out sooner than expected. From 0e9f02a96b5955cc477a101aa595686390800290 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Mon, 30 Sep 2013 22:45:55 +0200 Subject: [PATCH 036/146] added documentation about Request::setFactory() --- components/http_foundation/introduction.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/components/http_foundation/introduction.rst b/components/http_foundation/introduction.rst index f15372da975..ba37c78aa25 100644 --- a/components/http_foundation/introduction.rst +++ b/components/http_foundation/introduction.rst @@ -269,6 +269,26 @@ request information. Have a look at :class:`the Request API` for more information about them. +Overriding the Request +~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 2.4 + The :method:`Symfony\\Component\\HttpFoundation\\Request::setFactory` + class was added in Symfony 2.4. + +The Request class should not be overridden as it is a data object that +represents an HTTP message. But when moving from a legacy system, adding +methods or changing some default behavior might help. In that case, register a +PHP callable that is able to create an instance of your Request class:: + + use Symfony\Component\HttpFoundation\Request; + + Request::setFactory(function (array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) { + return SpecialRequest::create($query, $request, $attributes, $cookies, $files, $server, $content); + }); + + $request = Request::createFromGlobals(); + .. _component-http-foundation-response: Response From 16799b4db8717fcccfbb3ad0ec83085a57d4946d Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 2 Oct 2013 09:37:56 +0200 Subject: [PATCH 037/146] added the compact layout information --- components/console/helpers/tablehelper.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/components/console/helpers/tablehelper.rst b/components/console/helpers/tablehelper.rst index 1145dd7b603..4bc3323ebe6 100644 --- a/components/console/helpers/tablehelper.rst +++ b/components/console/helpers/tablehelper.rst @@ -32,12 +32,17 @@ table rendering: using named layouts or by customizing rendering options. Customize Table Layout using Named Layouts ------------------------------------------ -The Table helper ships with two preconfigured table layouts: +.. versionadded:: 2.4 + The ``TableHelper::LAYOUT_COMPACT`` layout was added in Symfony 2.4. + +The Table helper ships with three preconfigured table layouts: * ``TableHelper::LAYOUT_DEFAULT`` * ``TableHelper::LAYOUT_BORDERLESS`` +* ``TableHelper::LAYOUT_COMPACT`` + Layout can be set using :method:`Symfony\\Component\\Console\\Helper\\TableHelper::setLayout` method. Customize Table Layout using Rendering Options From 7e0cb8bb05e993b4b983bd82bbebef56261e7479 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 2 Oct 2013 17:27:58 -0400 Subject: [PATCH 038/146] [#2947] Adding versionadded details --- components/filesystem.rst | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/components/filesystem.rst b/components/filesystem.rst index 21c1afc1291..d59827885bc 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -21,16 +21,21 @@ The :class:`Symfony\\Component\\Filesystem\\Filesystem` class is the unique endpoint for filesystem operations:: use Symfony\Component\Filesystem\Filesystem; - use Symfony\Component\Filesystem\Exception\IOException; + use Symfony\Component\Filesystem\Exception\IOExceptionInterface; $fs = new Filesystem(); try { $fs->mkdir('/tmp/random/dir/' . mt_rand()); - } catch (IOException $e) { + } catch (IOExceptionInterface $e) { echo "An error occurred while creating your directory at ".$e->getPath(); } +.. versionadded:: + + The ``IOExceptionInterface`` and its ``getPath`` method are new in Symfony + 2.4. Prior to 2.4, you would catch the ``IOException`` class. + .. note:: Methods :method:`Symfony\\Component\\Filesystem\\Filesystem::mkdir`, @@ -251,7 +256,7 @@ Error Handling -------------- Whenever something wrong happens, an exception implementing -:class:`Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface` and +:class:`Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface` or :class:`Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface` is thrown. .. note:: From 2be6510ec8af216976901e0f05ab3bfef4e10963 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 2 Oct 2013 17:31:28 -0400 Subject: [PATCH 039/146] [#2960] Minor changes thanks to @xabbuh --- cookbook/templating/PHP.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cookbook/templating/PHP.rst b/cookbook/templating/PHP.rst index 759e124e0d2..3db2f9b23fb 100644 --- a/cookbook/templating/PHP.rst +++ b/cookbook/templating/PHP.rst @@ -313,11 +313,11 @@ template's code. Profiling Templates ~~~~~~~~~~~~~~~~~~~ -Using the ``stopwatch`` helper, you are able to time parts of your template +By using the ``stopwatch`` helper, you are able to time parts of your template and display it on the timeline of the WebProfilerBundle:: start('foo') ?> - ... things that gets timed + ... things that get timed stop('foo') ?> .. tip:: From 88f051a137b18292eb1797ff5345fd5e0ed2c9db Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 2 Oct 2013 17:43:47 -0400 Subject: [PATCH 040/146] [#2728] Minor tweaks to docs on Process flush methods --- components/process.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/components/process.rst b/components/process.rst index 0add196b0ca..87c6942eb1c 100644 --- a/components/process.rst +++ b/components/process.rst @@ -48,8 +48,10 @@ methods returns the new outputs since the last call. .. versionadded:: 2.4 The ``flushOutput()`` and ``flushErrorOutput()`` methods were added in Symfony 2.4. -The :method:`Symfony\\Component\\Process\\Process::flushOutput()` method flushes the contents of the output and -and :method:`Symfony\\Component\\Process\\Process::flushErrorOutput()` the content of the error output. +The :method:`Symfony\\Component\\Process\\Process::flushOutput` method flushes +the contents of the output and +:method:`Symfony\\Component\\Process\\Process::flushErrorOutput` flushes +the content of the error output. Getting real-time Process Output -------------------------------- From 66f16729cd2e7e60c9ec2a593b956182ead3bab7 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 2 Oct 2013 17:53:55 -0400 Subject: [PATCH 041/146] [#2971] Minor language tweak to be consistent with the other areas The language used by @xabbuh is actually straight from the PHPDoc, which is cool, but I don't love the wording there, and having some variety in wording might help clarification. --- components/http_foundation/introduction.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/http_foundation/introduction.rst b/components/http_foundation/introduction.rst index 0f64bc3f59f..f1d3b1df79a 100644 --- a/components/http_foundation/introduction.rst +++ b/components/http_foundation/introduction.rst @@ -243,7 +243,7 @@ by using the following methods: returns the list of accepted charsets ordered by descending quality; * :method:`Symfony\\Component\\HttpFoundation\\Request::getEncodings`: - returns the list of accepted encodings in preferable order. + returns the list of accepted charsets ordered by descending quality; .. versionadded:: 2.4 The ``getEncodings()`` method was added in Symfony 2.4. From e52ac5cb02d2af23c2dc483fdb2e11ba2f9ecc88 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Fri, 4 Oct 2013 19:32:16 +0200 Subject: [PATCH 042/146] fix versionadded directive --- components/filesystem.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/components/filesystem.rst b/components/filesystem.rst index d59827885bc..9a50e256e2b 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -31,8 +31,7 @@ endpoint for filesystem operations:: echo "An error occurred while creating your directory at ".$e->getPath(); } -.. versionadded:: - +.. versionadded:: 2.4 The ``IOExceptionInterface`` and its ``getPath`` method are new in Symfony 2.4. Prior to 2.4, you would catch the ``IOException`` class. From 4732a76f571f1dd3903b4e825843a21bf22fe87b Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 5 Oct 2013 13:04:55 -0400 Subject: [PATCH 043/146] [#2728] Fixing typo thanks to @xabbuh --- components/process.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/process.rst b/components/process.rst index 87c6942eb1c..981ec69e493 100644 --- a/components/process.rst +++ b/components/process.rst @@ -51,7 +51,7 @@ methods returns the new outputs since the last call. The :method:`Symfony\\Component\\Process\\Process::flushOutput` method flushes the contents of the output and :method:`Symfony\\Component\\Process\\Process::flushErrorOutput` flushes -the content of the error output. +the contents of the error output. Getting real-time Process Output -------------------------------- From 1d94f348c5fcb333dc2c4588e29e6d5a284e4a9e Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 6 Oct 2013 11:23:11 -0400 Subject: [PATCH 044/146] [#3021] Minor tweaks thanks to @WouterJ and @GromNaN --- components/http_foundation/introduction.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/http_foundation/introduction.rst b/components/http_foundation/introduction.rst index 8079be2a954..09c9f2ccc76 100644 --- a/components/http_foundation/introduction.rst +++ b/components/http_foundation/introduction.rst @@ -280,12 +280,12 @@ Overriding the Request .. versionadded:: 2.4 The :method:`Symfony\\Component\\HttpFoundation\\Request::setFactory` - class was added in Symfony 2.4. + method was added in Symfony 2.4. The Request class should not be overridden as it is a data object that represents an HTTP message. But when moving from a legacy system, adding methods or changing some default behavior might help. In that case, register a -PHP callable that is able to create an instance of your Request class:: +PHP callable that is able to create an instance of your ``Request`` class:: use Symfony\Component\HttpFoundation\Request; From cab5c89e5c608cd239a382b57c063f998da209ec Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sun, 6 Oct 2013 20:04:50 +0200 Subject: [PATCH 045/146] Creates Expression Language chapter --- components/expression_language/index.rst | 7 +++++++ components/index.rst | 1 + components/map.rst.inc | 2 ++ 3 files changed, 10 insertions(+) create mode 100644 components/expression_language/index.rst diff --git a/components/expression_language/index.rst b/components/expression_language/index.rst new file mode 100644 index 00000000000..adddcd4fc6d --- /dev/null +++ b/components/expression_language/index.rst @@ -0,0 +1,7 @@ +Expression Language +=================== + +.. toctree:: + :maxdepth: 2 + + introduction diff --git a/components/index.rst b/components/index.rst index e5dffc58cd6..3cf769b6282 100644 --- a/components/index.rst +++ b/components/index.rst @@ -13,6 +13,7 @@ The Components dom_crawler dependency_injection/index event_dispatcher/index + expression_language/index filesystem finder form/index diff --git a/components/map.rst.inc b/components/map.rst.inc index a915310cde1..e1512b04ec2 100644 --- a/components/map.rst.inc +++ b/components/map.rst.inc @@ -57,6 +57,8 @@ * :doc:`/components/event_dispatcher/generic_event` * :doc:`/components/event_dispatcher/immutable_dispatcher` +* :doc:`/components/expression_language/index` + * **Filesystem** * :doc:`/components/filesystem` From 27822ffabb5eb94b9b8673a4064365b32003a1d8 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sun, 6 Oct 2013 20:08:43 +0200 Subject: [PATCH 046/146] Bootstraps intro --- .../expression_language/introduction.rst | 23 +++++++++++++++++++ components/map.rst.inc | 2 ++ 2 files changed, 25 insertions(+) create mode 100644 components/expression_language/introduction.rst diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst new file mode 100644 index 00000000000..230a82ba1c0 --- /dev/null +++ b/components/expression_language/introduction.rst @@ -0,0 +1,23 @@ +.. index:: + single: Expressions + Single: Components; Expression Language + +The ExpressionLanguage Component +================================= + + The ExpressionLanguage component provides an engine that can compile and + evaluate expressions. An expression is a one-liner that returns a value + (mostly, but not limited to, Booleans). + +.. versionadded:: 2.4 + The ExpressionLanguage Component was new in Symfony 2.4. + +Installation +------------ + +You can install the component in 2 different ways: + +* Use the official Git repository (https://github.com/symfony/ExpressionLanguage); +* :doc:`Install it via Composer ` (``symfony/expression-language`` on `Packagist`_). + +.. _Packagist: https://packagist.org/packages/symfony/expression-language diff --git a/components/map.rst.inc b/components/map.rst.inc index e1512b04ec2..d55e3c4e721 100644 --- a/components/map.rst.inc +++ b/components/map.rst.inc @@ -59,6 +59,8 @@ * :doc:`/components/expression_language/index` + * :doc:`/components/expression_language/introduction` + * **Filesystem** * :doc:`/components/filesystem` From efe349e3ae0e9a285ba50384da4ac1a427f9e79c Mon Sep 17 00:00:00 2001 From: xabbuh Date: Sun, 6 Oct 2013 20:40:54 +0200 Subject: [PATCH 047/146] use literal for class name --- components/http_foundation/introduction.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/http_foundation/introduction.rst b/components/http_foundation/introduction.rst index 09c9f2ccc76..f7cb342037e 100644 --- a/components/http_foundation/introduction.rst +++ b/components/http_foundation/introduction.rst @@ -282,7 +282,7 @@ Overriding the Request The :method:`Symfony\\Component\\HttpFoundation\\Request::setFactory` method was added in Symfony 2.4. -The Request class should not be overridden as it is a data object that +The ``Request`` class should not be overridden as it is a data object that represents an HTTP message. But when moving from a legacy system, adding methods or changing some default behavior might help. In that case, register a PHP callable that is able to create an instance of your ``Request`` class:: From 6631f70836fbffdad407eef9e3e5289761756ed7 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sun, 6 Oct 2013 21:58:04 +0200 Subject: [PATCH 048/146] Added operators --- .../expression_language/introduction.rst | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index 230a82ba1c0..3c3039cccaa 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -20,4 +20,115 @@ You can install the component in 2 different ways: * Use the official Git repository (https://github.com/symfony/ExpressionLanguage); * :doc:`Install it via Composer ` (``symfony/expression-language`` on `Packagist`_). +Usage +----- + +The ExpressionLanguage component can compile and evaluate expressions. +Expressions are one-liners which most of the time return a boolean, you can +compare them to the expression in an ``if`` statement. A simple example of an +expression is ``1 + 2``. You can also use more complicated expressions, such +as ``someArray[3].someMethod('bar')``. + +The component provide 2 ways to work with expressions: + +* **compile**: the expression is compiled to PHP, so it can be cached and + evaluated; +* **evaluation**: the expression is evaluated without being compiled to PHP. + +The main class of the component is +:class:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage`:: + + use Symfony\Component\ExpressionLanguage\ExpressionLanguage; + + $language = new ExpressionLanguage(); + + echo $language->evaluate('1 + 2'); // displays 3 + + echo $language->compile('1 + 2'); // displays (1 + 2) + +Supported Literals +~~~~~~~~~~~~~~~~~~ + +The component supports: + +* **strings** - single and double quotes (e.g. ``'hello'``) +* **numbers** - e.g. ``103`` +* **arrays** - using twig notation (e.g. ``[1, 2]``) +* **hashes** - using twig notation (e.g. ``{ foo: 'bar' }``) +* **booleans** - ``true`` and ``false`` +* **null** - ``null`` + +Supported Operators +~~~~~~~~~~~~~~~~~~~ + +The component comes with a lot of operators: + +Arithmetic Operators +.................... + +* ``+`` (addition) +* ``-`` (subtraction) +* ``*`` (multiplication) +* ``/`` (division) +* ``%`` (modulus) +* ``**`` (pow) + +Assignment Operators +.................... + +* ``=`` + +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) +* ``=~`` (regex match) +* ``!~`` (regex does not match) + +.. sidebar:: Regex Operator + + The Regex Operators (``=~`` and ``!~``) are coming from Perl. This + operator matches if the regular expression on the right side of the + operator matches the string on the left. For instance, + ``'foobar' =~ '/foo/'`` evaluates to true. + ``!~`` is the opposite and matches if the regular expression does *not* + match the string. + +Logical Operators +................. + +* ``not`` or ``!`` +* ``and`` or ``&&`` +* ``or`` or ``||`` + +String Operators +................ + +* ``~`` (concatenation) + +Array Operators +............... + +* ``in`` (contain) +* ``not in`` (does not contain) + +Numeric Operators +................. + +* ``..`` (range) + .. _Packagist: https://packagist.org/packages/symfony/expression-language From 4ff9faeab25fa64ae540181b8b24df450a903f7d Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sun, 6 Oct 2013 22:01:38 +0200 Subject: [PATCH 049/146] Added another operator --- components/expression_language/introduction.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index 3c3039cccaa..475b15cb42f 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -131,4 +131,11 @@ Numeric Operators * ``..`` (range) +Ternary Operators +................. + +* ``foo ? 'yes' : 'no'`` +* ``foo ?: 'no'`` (equal to ``foo ? foo : 'no'``) +* ``foo ? 'yes'`` (equal to ``foo ? 'yes' : ''``) + .. _Packagist: https://packagist.org/packages/symfony/expression-language From f98fa24c22e1abf385b09bad7fd6eb6c43fcf4dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Pineau?= Date: Fri, 4 Oct 2013 15:04:11 +0200 Subject: [PATCH 050/146] Register Commands in the Service Container --- cookbook/console/console_command.rst | 46 ++++++++++++++++++++++++++++ reference/dic_tags.rst | 14 +++++++++ 2 files changed, 60 insertions(+) diff --git a/cookbook/console/console_command.rst b/cookbook/console/console_command.rst index 83033761feb..da6ff969200 100644 --- a/cookbook/console/console_command.rst +++ b/cookbook/console/console_command.rst @@ -62,6 +62,52 @@ This command will now automatically be available to run: $ app/console demo:greet Fabien +.. _cookbook-console-dic: + +Register Commands in the Service Container +------------------------------------------ + +.. versionadded:: 2.4 + Support for registering commands in the service container was added in + version 2.4. + +You can register commands in the service container using the ``console.command`` +tag: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + services: + acme_hello.command.my_command: + class: Acme\HelloBundle\Command\MyCommand + tags: + - { name: console.command } + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // app/config/config.php + + $container + ->register('acme_hello.command.my_command', 'Acme\HelloBundle\Command\MyCommand') + ->addTag('console.command') + ; + Getting Services from the Service Container ------------------------------------------- diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 727ef309f2d..731cfd84454 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -29,6 +29,8 @@ may also be tags in other bundles you use that aren't listed here. +-----------------------------------+---------------------------------------------------------------------------+ | `assetic.templating.twig`_ | Remove this service if twig templating is disabled | +-----------------------------------+---------------------------------------------------------------------------+ +| `console.command`_ | Add a command | ++-----------------------------------+---------------------------------------------------------------------------+ | `data_collector`_ | Create a class that collects custom data for the profiler | +-----------------------------------+---------------------------------------------------------------------------+ | `doctrine.event_listener`_ | Add a Doctrine event listener | @@ -241,6 +243,18 @@ assetic.templating.twig The tagged service will be removed from the container if ``framework.templating.engines`` config section does not contain twig. +console.command +--------------- + +.. versionadded:: 2.4 + Support for registering commands in the service container was added in + version 2.4. + +**Purpose**: Add a command to the application + +For details on registering your own commands in the service container, read +:ref:`the cookbook article`. + data_collector -------------- From b94e3f7f5d522d4a20ea5e5e2b0911a8fa45c4d5 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 8 Oct 2013 08:45:49 -0400 Subject: [PATCH 051/146] [#3012] Tweaks to Callback changes - most thanks to the careful eye of @xabbuh --- reference/constraints/Callback.rst | 41 ++++++++++++++++++------------ 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index f9024f37ef9..83b68d69401 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -114,7 +114,12 @@ those errors should be attributed:: // check if the name is actually a fake name if (in_array($this->getFirstName(), $fakeNames)) { - $context->addViolationAt('firstName', 'This name sounds totally fake!', array(), null); + $context->addViolationAt( + 'firstName', + 'This name sounds totally fake!', + array(), + null + ); } } } @@ -123,7 +128,7 @@ Static Callbacks ---------------- You can also use the constraint with static methods. Since static methods don't -have access to the object instance, they receive the object as first argument:: +have access to the object instance, they receive the object as the first argument:: public static function validate($object, ExecutionContextInterface $context) { @@ -132,7 +137,12 @@ have access to the object instance, they receive the object as first argument:: // check if the name is actually a fake name if (in_array($object->getFirstName(), $fakeNames)) { - $context->addViolationAt('firstName', 'This name sounds totally fake!', array(), null); + $context->addViolationAt( + 'firstName', + 'This name sounds totally fake!', + array(), + null + ); } } @@ -142,7 +152,7 @@ External Callbacks and Closures If you want to execute a static callback method that is not located in the class of the validated object, you can configure the constraint to invoke an array callable as supported by PHP's :phpfunction:`call_user_func` function. Suppose -your validation function is `Vendor\Package\Validator::validate()`:: +your validation function is ``Vendor\Package\Validator::validate()``:: namespace Vendor\Package; @@ -156,7 +166,7 @@ your validation function is `Vendor\Package\Validator::validate()`:: } } -You can then use the following configuration to invoke this validator:: +You can then use the following configuration to invoke this validator: .. configuration-block:: @@ -173,7 +183,6 @@ You can then use the following configuration to invoke this validator:: namespace Acme\BlogBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; - use Symfony\Component\Validator\ExecutionContextInterface; /** * @Assert\Callback({"Vendor\Package\Validator", "validate"}) @@ -212,17 +221,17 @@ You can then use the following configuration to invoke this validator:: { $metadata->addConstraint(new Assert\Callback(array( 'Vendor\Package\Validator', - 'validate' + 'validate', ))); } } .. note:: - The Callback constraint does *not* support global callback functions or - It is *not* possible to specify a global function or a :term:`service` - method as callback. To validate using a service, you should - :doc:`create a custom validation constraint` + The Callback constraint does *not* support global callback functions nor + is it possible to specify a global function or a :term:`service` method + as callback. To validate using a service, you should + :doc:`create a custom validation constraint ` and add that new constraint to your class. When configuring the constraint via PHP, you can also pass a closure to the @@ -252,20 +261,20 @@ Options callback ~~~~~~~~ -**type**: ``string``, ``array`` or ``Closure`` [:ref:`default option`] +**type**: ``string``, ``array`` or ``Closure`` [:ref:`default option `] The callback option accepts three different formats for specifying the callback method: -* A **string** containing the name of a concrete or static method. +* A **string** containing the name of a concrete or static method; -* An array callable with the format ``array('', '')``. +* An array callable with the format ``array('', '')``; * A closure. Concrete callbacks receive an :class:`Symfony\\Component\\Validator\\ExecutionContextInterface` instance as only argument. -Static or closure callbacks receive the validated object as first argument +Static or closure callbacks receive the validated object as the first argument and the :class:`Symfony\\Component\\Validator\\ExecutionContextInterface` -instance as second argument. +instance as the second argument. From 3efd179c43b47e5ee5d15cabf222c850b620c565 Mon Sep 17 00:00:00 2001 From: Eric GELOEN Date: Fri, 4 Oct 2013 00:26:21 +0200 Subject: [PATCH 052/146] [Form] Add a 'submitted' attribute to the form view --- reference/forms/twig_reference.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/reference/forms/twig_reference.rst b/reference/forms/twig_reference.rst index 20156e5a8f8..42d2150bcc1 100644 --- a/reference/forms/twig_reference.rst +++ b/reference/forms/twig_reference.rst @@ -295,6 +295,9 @@ object: get('name')->vars['label'] ?> +.. versionadded:: 2.4 + The ``submitted`` variable was added in Symfony 2.4. + +-----------------+-----------------------------------------------------------------------------------------+ | Variable | Usage | +=================+=========================================================================================+ @@ -310,6 +313,8 @@ object: | | since this only returns "global" errors: some individual fields may have errors | | | Instead, use the ``valid`` option | +-----------------+-----------------------------------------------------------------------------------------+ +| ``submitted`` | Returns ``true`` or ``false`` depending on whether the whole form is submitted | ++-----------------+-----------------------------------------------------------------------------------------+ | ``valid`` | Returns ``true`` or ``false`` depending on whether the whole form is valid | +-----------------+-----------------------------------------------------------------------------------------+ | ``value`` | The value that will be used when rendering (commonly the ``value`` HTML attribute) | From ca83f6a50cd9aac697184b07b98a64e2faf3785b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Pineau?= Date: Tue, 8 Oct 2013 16:30:03 +0200 Subject: [PATCH 053/146] Documents Output::*Verbose methods --- components/console/introduction.rst | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/components/console/introduction.rst b/components/console/introduction.rst index 451b6f18722..7d579576fd3 100755 --- a/components/console/introduction.rst +++ b/components/console/introduction.rst @@ -196,6 +196,31 @@ level. For example:: $output->writeln(...); } +.. versionadded:: 2.4 + The :method:`Symfony\\Component\Console\\Output\\Output::isQuiet`, + :method:`Symfony\\Component\Console\\Output\\Output::isVerbose`, + :method:`Symfony\\Component\Console\\Output\\Output::isVeryVerbose` and + :method:`Symfony\\Component\Console\\Output\\Output::isDebug` + methods were introduced in version 2.4 + +.. code-block:: php + + if ($output->isQuiet()) { + // ... + } + + if ($output->isVerbose()) { + // ... + } + + if ($output->isVeryVerbose()) { + // ... + } + + if ($output->isDebug()) { + // ... + } + When the quiet level is used, all output is suppressed as the default :method:`Symfony\Component\Console\Output::write ` method returns without actually printing. From bdd37ba279c930d6d8e0720eb738a91b45185d00 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 10 Oct 2013 10:30:00 -0400 Subject: [PATCH 054/146] [#3017] Very minor tweaks --- cookbook/session/limit_metadata_writes.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cookbook/session/limit_metadata_writes.rst b/cookbook/session/limit_metadata_writes.rst index b2d0208d21c..78d3923c69b 100644 --- a/cookbook/session/limit_metadata_writes.rst +++ b/cookbook/session/limit_metadata_writes.rst @@ -1,15 +1,15 @@ .. index:: single: Limit Metadata Writes; Session -Limit session metadata writes +Limit Session Metadata Writes ============================= .. versionadded:: 2.4 The ability to limit session metadata writes was added in Symfony 2.4. -The default behaviour of PHP session is to persist the session regardless of +The default behavior of PHP session is to persist the session regardless of whether the session data has changed or not. In Symfony, each time the session -is accessed metadata is recorded (session created/last used) which can be used +is accessed, metadata is recorded (session created/last used) which can be used to determine session age and idle time. If for performance reasons you wish to limit the frequency at which the session @@ -53,12 +53,12 @@ than zero: ), )); -.. info:: +.. note:: PHP default's behavior is to save the session whether it has been changed or not. When using ``framework.session.metadata_update_threshold`` Symfony will wrap the session handler (configured at - ``framework.session.handler_id``) into the WriteCheckSessionHandler, that + ``framework.session.handler_id``) into the WriteCheckSessionHandler. This will prevent any session write if the session was not modified. .. caution:: From ce45928a592268e2cb9e89bf0e782b4962ed3d4d Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Thu, 10 Oct 2013 18:04:21 +0200 Subject: [PATCH 055/146] make target name unique that is used as a reference --- reference/constraints/Callback.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index 83b68d69401..e59754f450a 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -25,7 +25,7 @@ can do anything, including creating and assigning validation errors. +----------------+------------------------------------------------------------------------+ | Applies to | :ref:`class ` | +----------------+------------------------------------------------------------------------+ -| Options | - `callback`_ | +| Options | - :ref:`callback ` | +----------------+------------------------------------------------------------------------+ | Class | :class:`Symfony\\Component\\Validator\\Constraints\\Callback` | +----------------+------------------------------------------------------------------------+ @@ -258,6 +258,8 @@ constructor of the Callback constraint:: Options ------- +.. _callback-option: + callback ~~~~~~~~ From 0925090d11de169e05d4d22a6da6e061d7a01226 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 14 Oct 2013 17:22:50 -0500 Subject: [PATCH 056/146] [#3031] Adding some details as to why you may or may not want to register a command a service --- cookbook/console/console_command.rst | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/cookbook/console/console_command.rst b/cookbook/console/console_command.rst index da6ff969200..3ff3759d4eb 100644 --- a/cookbook/console/console_command.rst +++ b/cookbook/console/console_command.rst @@ -71,8 +71,9 @@ Register Commands in the Service Container Support for registering commands in the service container was added in version 2.4. -You can register commands in the service container using the ``console.command`` -tag: +Instead of putting your command in the ``Command`` directory and having Symfony +auto-discover it for you, you can register commands in the service container +using the ``console.command`` tag: .. configuration-block:: @@ -108,6 +109,12 @@ tag: ->addTag('console.command') ; +.. tip:: + + Registering your command as a service gives you more control over its + location and the services that are injected into it. But, there are no + functional advantages, so you don't need register your command as a service. + Getting Services from the Service Container ------------------------------------------- From a53c8ad93e80740df3d380b3344e062a33cdae1a Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 15 Oct 2013 09:50:26 -0500 Subject: [PATCH 057/146] [#3048] Adding intro paragraph about the semantic verbosity methods --- components/console/introduction.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/components/console/introduction.rst b/components/console/introduction.rst index 7d579576fd3..12fcbe525ab 100755 --- a/components/console/introduction.rst +++ b/components/console/introduction.rst @@ -203,7 +203,8 @@ level. For example:: :method:`Symfony\\Component\Console\\Output\\Output::isDebug` methods were introduced in version 2.4 -.. code-block:: php +There are also more semantic methods you can use to test for each of the +verbosity levels:: if ($output->isQuiet()) { // ... From 72b690fe39cb06aeba4f383461cd8003591c6d1a Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 15 Oct 2013 10:04:53 -0500 Subject: [PATCH 058/146] [#3031] Fixing typo thanks to @xabbuh --- cookbook/console/console_command.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cookbook/console/console_command.rst b/cookbook/console/console_command.rst index c30d9edeb49..303a9ee45ed 100644 --- a/cookbook/console/console_command.rst +++ b/cookbook/console/console_command.rst @@ -113,7 +113,7 @@ using the ``console.command`` tag: Registering your command as a service gives you more control over its location and the services that are injected into it. But, there are no - functional advantages, so you don't need register your command as a service. + functional advantages, so you don't need to register your command as a service. Getting Services from the Service Container ------------------------------------------- From b944124de02eaa2650804d64eb83cbcd1ab59c2e Mon Sep 17 00:00:00 2001 From: Pierre-Yves LEBECQ Date: Sun, 20 Oct 2013 13:11:59 +0200 Subject: [PATCH 059/146] Added documentation about disabling internal validation of DomCrawler forms. --- book/testing.rst | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/book/testing.rst b/book/testing.rst index 3de9cba48d6..729bb51804b 100644 --- a/book/testing.rst +++ b/book/testing.rst @@ -671,6 +671,22 @@ their type:: // Upload a file $form['photo']->upload('/path/to/lucas.jpg'); +.. versionadded:: 2.4 + The :method:`Symfony\\Component\\DomCrawler\\Form::disableValidation` + method was added in Symfony 2.4. + +By default, choice fields (select, radio) have internal validation activated +to prevent you from setting invalid values. If you want to be able to set +invalid values, you can use the ``disableValidation()`` method on either +the whole form or specific field(s):: + + // Disable validation for a specific field + $form['country']->disableValidation()->select('Invalid value'); + + // Disable validation for the whole form + $form->disableValidation(); + $form['country']->select('Invalid value'); + .. tip:: You can get the values that will be submitted by calling the ``getValues()`` From b02bc8cd003211a25cbfdaa6bc3947399c5ce71d Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 22 Oct 2013 17:34:33 +0200 Subject: [PATCH 060/146] add note about not passing the command argument with Symfony 2.4 --- cookbook/console/console_command.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cookbook/console/console_command.rst b/cookbook/console/console_command.rst index 303a9ee45ed..fa7db6f1673 100644 --- a/cookbook/console/console_command.rst +++ b/cookbook/console/console_command.rst @@ -159,7 +159,6 @@ instead of $commandTester = new CommandTester($command); $commandTester->execute( array( - 'command' => $command->getName(), 'name' => 'Fabien', '--yell' => true, ) @@ -171,6 +170,11 @@ instead of } } +.. versionadded:: 2.4 + Since Symfony 2.4, the ``CommandTester`` automatically detects the name of + the command to execute. Thus, you don't need to pass it via the ``command`` + argument anymore. + .. note:: In the specific case above, the ``name`` parameter and the ``--yell`` option @@ -200,7 +204,6 @@ you can extend your test from $commandTester = new CommandTester($command); $commandTester->execute( array( - 'command' => $command->getName(), 'name' => 'Fabien', '--yell' => true, ) From 8fe9fd606fdf4b0b20bf55606b9b7472b3965c83 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sat, 26 Oct 2013 12:32:53 +0200 Subject: [PATCH 061/146] Fixed comments and splitted in intro and syntax --- components/expression_language/index.rst | 1 + .../expression_language/introduction.rst | 100 ++---------------- components/expression_language/syntax.rst | 98 +++++++++++++++++ components/map.rst.inc | 1 + 4 files changed, 107 insertions(+), 93 deletions(-) create mode 100644 components/expression_language/syntax.rst diff --git a/components/expression_language/index.rst b/components/expression_language/index.rst index adddcd4fc6d..e6eb657b4be 100644 --- a/components/expression_language/index.rst +++ b/components/expression_language/index.rst @@ -5,3 +5,4 @@ Expression Language :maxdepth: 2 introduction + syntax diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index 475b15cb42f..a7f474c732a 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -10,14 +10,14 @@ The ExpressionLanguage Component (mostly, but not limited to, Booleans). .. versionadded:: 2.4 - The ExpressionLanguage Component was new in Symfony 2.4. + The ExpressionLanguage component was new in Symfony 2.4. Installation ------------ You can install the component in 2 different ways: -* Use the official Git repository (https://github.com/symfony/ExpressionLanguage); +* Use the official Git repository (https://github.com/symfony/expression-language); * :doc:`Install it via Composer ` (``symfony/expression-language`` on `Packagist`_). Usage @@ -29,7 +29,7 @@ compare them to the expression in an ``if`` statement. A simple example of an expression is ``1 + 2``. You can also use more complicated expressions, such as ``someArray[3].someMethod('bar')``. -The component provide 2 ways to work with expressions: +The component provides 2 ways to work with expressions: * **compile**: the expression is compiled to PHP, so it can be cached and evaluated; @@ -46,96 +46,10 @@ The main class of the component is echo $language->compile('1 + 2'); // displays (1 + 2) -Supported Literals -~~~~~~~~~~~~~~~~~~ +Expression Syntax +----------------- -The component supports: - -* **strings** - single and double quotes (e.g. ``'hello'``) -* **numbers** - e.g. ``103`` -* **arrays** - using twig notation (e.g. ``[1, 2]``) -* **hashes** - using twig notation (e.g. ``{ foo: 'bar' }``) -* **booleans** - ``true`` and ``false`` -* **null** - ``null`` - -Supported Operators -~~~~~~~~~~~~~~~~~~~ - -The component comes with a lot of operators: - -Arithmetic Operators -.................... - -* ``+`` (addition) -* ``-`` (subtraction) -* ``*`` (multiplication) -* ``/`` (division) -* ``%`` (modulus) -* ``**`` (pow) - -Assignment Operators -.................... - -* ``=`` - -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) -* ``=~`` (regex match) -* ``!~`` (regex does not match) - -.. sidebar:: Regex Operator - - The Regex Operators (``=~`` and ``!~``) are coming from Perl. This - operator matches if the regular expression on the right side of the - operator matches the string on the left. For instance, - ``'foobar' =~ '/foo/'`` evaluates to true. - ``!~`` is the opposite and matches if the regular expression does *not* - match the string. - -Logical Operators -................. - -* ``not`` or ``!`` -* ``and`` or ``&&`` -* ``or`` or ``||`` - -String Operators -................ - -* ``~`` (concatenation) - -Array Operators -............... - -* ``in`` (contain) -* ``not in`` (does not contain) - -Numeric Operators -................. - -* ``..`` (range) - -Ternary Operators -................. - -* ``foo ? 'yes' : 'no'`` -* ``foo ?: 'no'`` (equal to ``foo ? foo : 'no'``) -* ``foo ? 'yes'`` (equal to ``foo ? 'yes' : ''``) +See ":doc:`/components/expression_language/syntax`" to learn the syntax of the +ExpressionLanguage component. .. _Packagist: https://packagist.org/packages/symfony/expression-language diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst new file mode 100644 index 00000000000..7c3a59fccb9 --- /dev/null +++ b/components/expression_language/syntax.rst @@ -0,0 +1,98 @@ +.. 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 twig notation (e.g. ``[1, 2]``) +* **hashes** - using twig notation (e.g. ``{ foo: 'bar' }``) +* **booleans** - ``true`` and ``false`` +* **null** - ``null`` + +Supported Operators +~~~~~~~~~~~~~~~~~~~ + +The component comes with a lot of operators: + +Arithmetic Operators +.................... + +* ``+`` (addition) +* ``-`` (subtraction) +* ``*`` (multiplication) +* ``/`` (division) +* ``%`` (modulus) +* ``**`` (pow) + +Assignment Operators +.................... + +* ``=`` + +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:: + + $language->evaluate('not "foo" matches "/bar/"'); // returns true + +Logical Operators +................. + +* ``not`` or ``!`` +* ``and`` or ``&&`` +* ``or`` or ``||`` + +String Operators +................ + +* ``~`` (concatenation) + +Array Operators +............... + +* ``in`` (contain) +* ``not in`` (does not contain) + +Numeric Operators +................. + +* ``..`` (range) + +Ternary Operators +................. + +* ``foo ? 'yes' : 'no'`` +* ``foo ?: 'no'`` (equal to ``foo ? foo : 'no'``) +* ``foo ? 'yes'`` (equal to ``foo ? 'yes' : ''``) diff --git a/components/map.rst.inc b/components/map.rst.inc index d55e3c4e721..fb1055a6555 100644 --- a/components/map.rst.inc +++ b/components/map.rst.inc @@ -60,6 +60,7 @@ * :doc:`/components/expression_language/index` * :doc:`/components/expression_language/introduction` + * :doc:`/components/expression_language/syntax` * **Filesystem** From 31fb5b84c75b8178cbf6f9b8a9de9985fe4f78f1 Mon Sep 17 00:00:00 2001 From: Tobias Schultze Date: Mon, 28 Oct 2013 10:38:19 +0100 Subject: [PATCH 062/146] update framework csrf configuration https://github.com/symfony/symfony/pull/9252 --- reference/configuration/framework.rst | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 05d707e370d..01752fbe950 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -20,11 +20,14 @@ Configuration * `ide`_ * `test`_ * `trusted_proxies`_ -* `form`_ - * enabled * `csrf_protection`_ * enabled - * field_name + * field_name (deprecated) +* `form`_ + * enabled + * csrf_protection + * enabled + * field_name * `session`_ * `name`_ * `cookie_lifetime`_ @@ -452,12 +455,16 @@ Full Default Configuration test: ~ default_locale: en + csrf_protection: + enabled: false + field_name: _token # Deprecated since 2.4, to be removed in 3.0. Use form.csrf_protection.field_name instead + # form configuration form: enabled: false - csrf_protection: - enabled: false - field_name: _token + csrf_protection: + enabled: true + field_name: ~ # esi configuration esi: From 2a5049340ab0524edaf5e50b9e70eb8f56346e8c Mon Sep 17 00:00:00 2001 From: Luis Cordova Date: Mon, 28 Oct 2013 16:50:34 -0500 Subject: [PATCH 063/146] switch argument to key to be more precise --- cookbook/console/console_command.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cookbook/console/console_command.rst b/cookbook/console/console_command.rst index fa7db6f1673..18efda43a3e 100644 --- a/cookbook/console/console_command.rst +++ b/cookbook/console/console_command.rst @@ -4,7 +4,7 @@ How to create a Console Command =============================== -The Console page of the Components section (:doc:`/components/console/introduction`) covers +The Console page of the Components section (:doc:`/components/console/introductcion`) covers how to create a Console command. This cookbook article covers the differences when creating Console commands within the Symfony2 framework. @@ -173,7 +173,7 @@ instead of .. versionadded:: 2.4 Since Symfony 2.4, the ``CommandTester`` automatically detects the name of the command to execute. Thus, you don't need to pass it via the ``command`` - argument anymore. + key anymore. .. note:: From fda51eee9a34107eba3eee45d4a922803e0df5b8 Mon Sep 17 00:00:00 2001 From: Luis Cordova Date: Mon, 28 Oct 2013 16:51:58 -0500 Subject: [PATCH 064/146] fix introducing typo --- cookbook/console/console_command.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cookbook/console/console_command.rst b/cookbook/console/console_command.rst index 18efda43a3e..7571b49543b 100644 --- a/cookbook/console/console_command.rst +++ b/cookbook/console/console_command.rst @@ -4,7 +4,7 @@ How to create a Console Command =============================== -The Console page of the Components section (:doc:`/components/console/introductcion`) covers +The Console page of the Components section (:doc:`/components/console/introduction`) covers how to create a Console command. This cookbook article covers the differences when creating Console commands within the Symfony2 framework. From ae03fdb5cc28e9ffe9a089fe539d1354ae977b00 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Fri, 1 Nov 2013 22:15:08 -0500 Subject: [PATCH 065/146] [#3075] Moving new Form::disableValidation DomCrawler details into the component The idea is to keep the book chapter to more main-stream details and put longer details into the component docs --- book/testing.rst | 17 +++-------------- components/dom_crawler.rst | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/book/testing.rst b/book/testing.rst index 729bb51804b..4deb4229075 100644 --- a/book/testing.rst +++ b/book/testing.rst @@ -671,21 +671,10 @@ their type:: // Upload a file $form['photo']->upload('/path/to/lucas.jpg'); -.. versionadded:: 2.4 - The :method:`Symfony\\Component\\DomCrawler\\Form::disableValidation` - method was added in Symfony 2.4. - -By default, choice fields (select, radio) have internal validation activated -to prevent you from setting invalid values. If you want to be able to set -invalid values, you can use the ``disableValidation()`` method on either -the whole form or specific field(s):: - - // Disable validation for a specific field - $form['country']->disableValidation()->select('Invalid value'); +.. tip:: - // Disable validation for the whole form - $form->disableValidation(); - $form['country']->select('Invalid value'); + If you purposefully want to select "invalid" select/radio values, see + :ref:`components-dom-crawler-invalid`. .. tip:: diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index d1ae7a66e3f..ba9b9a09ade 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -340,6 +340,9 @@ and uploading files:: // even fake a file upload $form['registration[photo]']->upload('/path/to/lucas.jpg'); +Using the Form Data +................... + What's the point of doing all of this? If you're testing internally, you can grab the information off of your form as if it had just been submitted by using the PHP values:: @@ -375,5 +378,26 @@ directly:: // submit that form $crawler = $client->submit($form); +.. _components-dom-crawler-invalid: + +Selecting Invalid Choice Values +............................... + +.. versionadded:: 2.4 + The :method:`Symfony\\Component\\DomCrawler\\Form::disableValidation` + method was added in Symfony 2.4. + +By default, choice fields (select, radio) have internal validation activated +to prevent you from setting invalid values. If you want to be able to set +invalid values, you can use the ``disableValidation()`` method on either +the whole form or specific field(s):: + + // Disable validation for a specific field + $form['country']->disableValidation()->select('Invalid value'); + + // Disable validation for the whole form + $form->disableValidation(); + $form['country']->select('Invalid value'); + .. _`Goutte`: https://github.com/fabpot/goutte .. _Packagist: https://packagist.org/packages/symfony/dom-crawler From 10fe8a4d16be777c12ad84eaaa7429011d60dbdc Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sat, 2 Nov 2013 11:35:59 +0100 Subject: [PATCH 066/146] Removed 2.2 references as it reached eom --- book/forms.rst | 6 +++--- book/routing.rst | 14 -------------- book/security.rst | 7 ------- book/templating.rst | 12 ------------ components/config/definition.rst | 8 +------- components/console/helpers/dialoghelper.rst | 13 ------------- components/console/helpers/progresshelper.rst | 3 --- components/dependency_injection/compilation.rst | 3 --- components/finder.rst | 6 ------ components/http_foundation/introduction.rst | 7 ------- components/process.rst | 3 --- components/property_access/introduction.rst | 4 ---- components/routing/hostname_pattern.rst | 3 --- components/routing/introduction.rst | 7 ------- components/stopwatch.rst | 4 ---- cookbook/console/sending_emails.rst | 9 +++------ cookbook/form/dynamic_form_modification.rst | 8 -------- cookbook/templating/namespaced_paths.rst | 5 +---- cookbook/templating/render_without_controller.rst | 6 +----- reference/configuration/framework.rst | 5 ----- reference/configuration/security.rst | 6 ------ reference/constraints/CardScheme.rst | 3 --- reference/constraints/Luhn.rst | 3 --- reference/constraints/UserPassword.rst | 8 -------- reference/dic_tags.rst | 2 +- reference/twig_reference.rst | 4 ---- 26 files changed, 10 insertions(+), 149 deletions(-) diff --git a/book/forms.rst b/book/forms.rst index f5621c51a5b..a835cd2cb16 100644 --- a/book/forms.rst +++ b/book/forms.rst @@ -1873,7 +1873,7 @@ Learn more from the Cookbook .. _`Symfony2 Form Component`: https://github.com/symfony/Form .. _`DateTime`: http://php.net/manual/en/class.datetime.php -.. _`Twig Bridge`: https://github.com/symfony/symfony/tree/2.2/src/Symfony/Bridge/Twig -.. _`form_div_layout.html.twig`: https://github.com/symfony/symfony/blob/2.2/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig +.. _`Twig Bridge`: https://github.com/symfony/symfony/tree/master/src/Symfony/Bridge/Twig +.. _`form_div_layout.html.twig`: https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig .. _`Cross-site request forgery`: http://en.wikipedia.org/wiki/Cross-site_request_forgery -.. _`view on GitHub`: https://github.com/symfony/symfony/tree/2.2/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form +.. _`view on GitHub`: https://github.com/symfony/symfony/tree/master/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form diff --git a/book/routing.rst b/book/routing.rst index 68a9e4c7ce6..fc594aaeaff 100644 --- a/book/routing.rst +++ b/book/routing.rst @@ -68,10 +68,6 @@ The route is simple: return $collection; -.. versionadded:: 2.2 - The ``path`` option is new in Symfony2.2, ``pattern`` is used in older - versions. - The path defined by the ``blog_show`` route acts like ``/blog/*`` where the wildcard is given the name ``slug``. For the URL ``/blog/my-blog-post``, the ``slug`` variable gets a value of ``my-blog-post``, which is available @@ -694,10 +690,6 @@ be accomplished with the following route configuration: return $collection; -.. versionadded:: 2.2 - The ``methods`` option is added in Symfony2.2. Use the ``_method`` - requirement in older versions. - Despite the fact that these two routes have identical paths (``/contact``), the first route will match only GET requests and the second route will match only POST requests. This means that you can display the form and submit the @@ -710,9 +702,6 @@ form via the same URL, while using distinct controllers for the two actions. Adding a Host ~~~~~~~~~~~~~ -.. versionadded:: 2.2 - Host matching support was added in Symfony 2.2 - You can also match on the HTTP *host* of the incoming request. For more information, see :doc:`/components/routing/hostname_pattern` in the Routing component documentation. @@ -1070,9 +1059,6 @@ from the new routing resource. Adding a Host regex to Imported Routes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 2.2 - Host matching support was added in Symfony 2.2 - You can set the host regex on imported routes. For more information, see :ref:`component-routing-host-imported`. diff --git a/book/security.rst b/book/security.rst index e21e32cc438..6a82b4ecfd1 100644 --- a/book/security.rst +++ b/book/security.rst @@ -1385,10 +1385,6 @@ it as base64. In other words, the password has been greatly obfuscated so that the hashed password can't be decoded (i.e. you can't determine the password from the hashed password). -.. versionadded:: 2.2 - As of Symfony 2.2 you can also use the :ref:`PBKDF2 ` - and :ref:`BCrypt ` password encoders. - Determining the Hashed Password ............................... @@ -2023,9 +2019,6 @@ cookie will be ever created by Symfony2): Utilities --------- -.. versionadded:: 2.2 - The ``StringUtils`` and ``SecureRandom`` classes were added in Symfony 2.2 - 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. diff --git a/book/templating.rst b/book/templating.rst index 2e01d869196..d6e75fa0f75 100644 --- a/book/templating.rst +++ b/book/templating.rst @@ -375,11 +375,6 @@ When working with template inheritance, here are some tips to keep in mind: Template Naming and Locations ----------------------------- -.. versionadded:: 2.2 - Namespaced path support was added in 2.2, allowing for template names - like ``@AcmeDemo/layout.html.twig``. See :doc:`/cookbook/templating/namespaced_paths` - for more details. - By default, templates can live in two different locations: * ``app/Resources/views/``: The applications ``views`` directory can contain @@ -572,10 +567,6 @@ you set `with_context`_ to false). maps (i.e. an array with named keys). If you needed to pass in multiple elements, it would look like this: ``{'foo': foo, 'bar': bar}``. -.. versionadded:: 2.2 - The `include() function`_ is a new Twig feature that's available in Symfony - 2.2. Prior, the `{% include %} tag`_ tag was used. - .. index:: single: Templating; Embedding action @@ -782,9 +773,6 @@ in your application configuration: ), )); -.. versionadded:: 2.2 - Default templates per render function was added in Symfony 2.2 - You can define default templates per ``render`` function (which will override any global default template that is defined): diff --git a/components/config/definition.rst b/components/config/definition.rst index 0bd25d19a03..9a5f22d7125 100644 --- a/components/config/definition.rst +++ b/components/config/definition.rst @@ -99,7 +99,7 @@ node definition. Node type are available for: * scalar * boolean -* integer (new in 2.2) +* integer * float * enum * array @@ -111,9 +111,6 @@ and are created with ``node($name, $type)`` or their associated shortcut Numeric node constraints ~~~~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 2.2 - The numeric (float and integer) nodes are new in 2.2 - Numeric nodes (float and integer) provide two extra constraints - :method:`Symfony\\Component\\Config\\Definition\\Builder::min` and :method:`Symfony\\Component\\Config\\Definition\\Builder::max` - @@ -287,9 +284,6 @@ has a certain value: Optional Sections ----------------- -.. versionadded:: 2.2 - The ``canBeEnabled`` and ``canBeDisabled`` methods are new in Symfony 2.2 - If you have entire sections which are optional and can be enabled/disabled, you can take advantage of the shortcut :method:`Symfony\\Component\\Config\\Definition\\Builder\\ArrayNodeDefinition::canBeEnabled` and diff --git a/components/console/helpers/dialoghelper.rst b/components/console/helpers/dialoghelper.rst index 1d1215236f1..584a080164d 100644 --- a/components/console/helpers/dialoghelper.rst +++ b/components/console/helpers/dialoghelper.rst @@ -56,9 +56,6 @@ the default value (``AcmeDemoBundle`` here) is returned. Autocompletion ~~~~~~~~~~~~~~ -.. versionadded:: 2.2 - Autocompletion for questions was added in Symfony 2.2. - You can also specify an array of potential answers for a given question. These will be autocompleted as the user types:: @@ -74,9 +71,6 @@ will be autocompleted as the user types:: Hiding the User's Response ~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 2.2 - The ``askHiddenResponse`` method was added in Symfony 2.2. - You can also ask a question and hide the response. This is particularly convenient for passwords:: @@ -144,9 +138,6 @@ be able to proceed if her input is valid. Hiding the User's Response ~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 2.2 - The ``askHiddenResponseAndValidate`` method was added in Symfony 2.2. - You can also ask and validate a hidden response:: $dialog = $this->getHelperSet()->get('dialog'); @@ -171,10 +162,6 @@ some reason, pass true as the fifth argument. Let the user choose from a list of Answers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 2.2 - The :method:`Symfony\\Component\\Console\\Helper\\DialogHelper::select` method - was added in Symfony 2.2. - If you have a predefined set of answers the user can choose from, you could use the ``ask`` method described above or, to make sure the user provided a correct answer, the ``askAndValidate`` method. Both have diff --git a/components/console/helpers/progresshelper.rst b/components/console/helpers/progresshelper.rst index ccd5d381afd..9ee76b694cb 100644 --- a/components/console/helpers/progresshelper.rst +++ b/components/console/helpers/progresshelper.rst @@ -4,9 +4,6 @@ Progress Helper =============== -.. versionadded:: 2.2 - The ``progress`` helper was added in Symfony 2.2. - .. versionadded:: 2.3 The ``setCurrent`` method was added in Symfony 2.3. diff --git a/components/dependency_injection/compilation.rst b/components/dependency_injection/compilation.rst index af1fd1444f5..07c8a737c6a 100644 --- a/components/dependency_injection/compilation.rst +++ b/components/dependency_injection/compilation.rst @@ -276,9 +276,6 @@ but also load a secondary one only if a certain parameter is set:: Prepending Configuration passed to the Extension ------------------------------------------------ -.. versionadded:: 2.2 - The ability to prepend the configuration of a bundle is new in Symfony 2.2. - An Extension can prepend the configuration of any Bundle before the ``load()`` method is called by implementing :class:`Symfony\\Component\\DependencyInjection\\Extension\\PrependExtensionInterface`:: diff --git a/components/finder.rst b/components/finder.rst index c63d624e6c6..2f985ba0af9 100644 --- a/components/finder.rst +++ b/components/finder.rst @@ -82,9 +82,6 @@ Search in several locations by chaining calls to $finder->files()->in(__DIR__)->in('/elsewhere'); -.. versionadded:: 2.2 - Wildcard support was added in version 2.2. - Use wildcard characters to search in the directories matching a pattern:: $finder->in('src/Symfony/*/*/Resources'); @@ -206,9 +203,6 @@ The ``notContains()`` method excludes files containing given pattern:: Path ~~~~ -.. versionadded:: 2.2 - The ``path()`` and ``notPath()`` methods were added in version 2.2. - Restrict files and directories by path with the :method:`Symfony\\Component\\Finder\\Finder::path` method:: diff --git a/components/http_foundation/introduction.rst b/components/http_foundation/introduction.rst index f7cb342037e..f7880d15e5f 100644 --- a/components/http_foundation/introduction.rst +++ b/components/http_foundation/introduction.rst @@ -248,9 +248,6 @@ by using the following methods: .. versionadded:: 2.4 The ``getEncodings()`` method was added in Symfony 2.4. -.. versionadded:: 2.2 - The :class:`Symfony\\Component\\HttpFoundation\\AcceptHeader` class is new in Symfony 2.2. - If you need to get full access to parsed data from ``Accept``, ``Accept-Language``, ``Accept-Charset`` or ``Accept-Encoding``, you can use :class:`Symfony\\Component\\HttpFoundation\\AcceptHeader` utility class:: @@ -462,10 +459,6 @@ abstracts the hard work behind a simple API:: $response->headers->set('Content-Disposition', $d); -.. versionadded:: 2.2 - The :class:`Symfony\\Component\\HttpFoundation\\BinaryFileResponse` - class was added in Symfony 2.2. - Alternatively, if you are serving a static file, you can use a :class:`Symfony\\Component\\HttpFoundation\\BinaryFileResponse`:: diff --git a/components/process.rst b/components/process.rst index 981ec69e493..a9d21d1187f 100644 --- a/components/process.rst +++ b/components/process.rst @@ -36,9 +36,6 @@ a command in a sub-process:: The component takes care of the subtle differences between the different platforms when executing the command. -.. versionadded:: 2.2 - The ``getIncrementalOutput()`` and ``getIncrementalErrorOutput()`` methods were added in Symfony 2.2. - The ``getOutput()`` method always return the whole content of the standard output of the command and ``getErrorOutput()`` the content of the error output. Alternatively, the :method:`Symfony\\Component\\Process\\Process::getIncrementalOutput` diff --git a/components/property_access/introduction.rst b/components/property_access/introduction.rst index 767097f8dfd..3c316726142 100644 --- a/components/property_access/introduction.rst +++ b/components/property_access/introduction.rst @@ -8,10 +8,6 @@ The PropertyAccess Component The PropertyAccess component provides function to read and write from/to an object or array using a simple string notation. -.. versionadded:: 2.2 - The PropertyAccess Component is new to Symfony 2.2. Previously, the - ``PropertyPath`` class was located in the ``Form`` component. - Installation ------------ diff --git a/components/routing/hostname_pattern.rst b/components/routing/hostname_pattern.rst index dfe5df8a445..fd872bb65a8 100644 --- a/components/routing/hostname_pattern.rst +++ b/components/routing/hostname_pattern.rst @@ -4,9 +4,6 @@ How to match a route based on the Host ====================================== -.. versionadded:: 2.2 - Host matching support was added in Symfony 2.2 - You can also match on the HTTP *host* of the incoming request. .. configuration-block:: diff --git a/components/routing/introduction.rst b/components/routing/introduction.rst index 12a032eb9d4..dc4ddcdd85d 100644 --- a/components/routing/introduction.rst +++ b/components/routing/introduction.rst @@ -93,9 +93,6 @@ are the least commonly needed. 7. An array of methods. These enforce a certain HTTP request method (``HEAD``, ``GET``, ``POST``, ...). -.. versionadded:: 2.2 - Host matching support was added in Symfony 2.2 - Take the following route, which combines several of these ideas:: $route = new Route( @@ -160,10 +157,6 @@ the :method:`Symfony\\Component\\Routing\\RouteCollection::addPrefix` method:: $rootCollection->addCollection($subCollection); -.. versionadded:: 2.2 - The ``addPrefix`` method is added in Symfony2.2. This was part of the - ``addCollection`` method in older versions. - Set the Request Parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/components/stopwatch.rst b/components/stopwatch.rst index c7347a4ad5c..6b0004441c0 100644 --- a/components/stopwatch.rst +++ b/components/stopwatch.rst @@ -7,10 +7,6 @@ The Stopwatch Component Stopwatch component provides a way to profile code. -.. versionadded:: 2.2 - The Stopwatch Component is new to Symfony 2.2. Previously, the ``Stopwatch`` - class was located in the ``HttpKernel`` component. - Installation ------------ diff --git a/cookbook/console/sending_emails.rst b/cookbook/console/sending_emails.rst index 2d72da3cfd4..e7dbcbca03d 100644 --- a/cookbook/console/sending_emails.rst +++ b/cookbook/console/sending_emails.rst @@ -17,16 +17,13 @@ what URL it should use when generating URLs. There are two ways of configuring the request context: at the application level and per Command. -Configuring the Request Context globally +Configuring the Request Context Globally ---------------------------------------- -.. versionadded: 2.2 - The ``base_url`` parameter is available since Symfony 2.2 - To configure the Request Context - which is used by the URL Generator - you can redefine the parameters it uses as default values to change the default host -(localhost) and scheme (http). Starting with Symfony 2.2 you can also configure -the base path if Symfony is not running in the root directory. +(localhost) and scheme (http). You can also configure the base path if Symfony +is not running in the root directory. Note that this does not impact URLs generated via normal web requests, since those will override the defaults. diff --git a/cookbook/form/dynamic_form_modification.rst b/cookbook/form/dynamic_form_modification.rst index e358d39bb96..a53998ef168 100644 --- a/cookbook/form/dynamic_form_modification.rst +++ b/cookbook/form/dynamic_form_modification.rst @@ -114,10 +114,6 @@ The goal is to create a "name" field *only* if the underlying Product object is new (e.g. hasn't been persisted to the database). Based on that, the subscriber might look like the following: -.. versionadded:: 2.2 - The ability to pass a string into :method:`FormInterface::add ` - was added in Symfony 2.2. - .. code-block:: php // src/Acme/DemoBundle/Form/EventListener/AddNameFieldSubscriber.php @@ -469,10 +465,6 @@ On a form, we can usually listen to the following events: The events ``PRE_SUBMIT``, ``SUBMIT`` and ``POST_SUBMIT`` were added in Symfony 2.3. Before, they were named ``PRE_BIND``, ``BIND`` and ``POST_BIND``. -.. versionadded:: 2.2.6 - The behavior of the ``POST_SUBMIT`` event changed slightly in 2.2.6, which the - below example uses. - The key is to add a ``POST_SUBMIT`` listener to the field that your new field depends on. If you add a ``POST_SUBMIT`` listener to a form child (e.g. ``sport``), and add new children to the parent form, the Form component will detect the diff --git a/cookbook/templating/namespaced_paths.rst b/cookbook/templating/namespaced_paths.rst index 8e33b38ef66..ff41d10e7c0 100644 --- a/cookbook/templating/namespaced_paths.rst +++ b/cookbook/templating/namespaced_paths.rst @@ -4,9 +4,6 @@ How to use and Register namespaced Twig Paths ============================================= -.. versionadded:: 2.2 - Namespaced path support was added in 2.2. - Usually, when you refer to a template, you'll use the ``MyBundle:Subdir:filename.html.twig`` format (see :ref:`template-naming-locations`). @@ -80,4 +77,4 @@ called ``sidebar.twig`` in that directory, you can use it easily: .. code-block:: jinja - {% include '@foo_bar/side.bar.twig` %} \ No newline at end of file + {% include '@foo_bar/side.bar.twig` %} diff --git a/cookbook/templating/render_without_controller.rst b/cookbook/templating/render_without_controller.rst index f2a44f7e4e1..a00c9089f1a 100644 --- a/cookbook/templating/render_without_controller.rst +++ b/cookbook/templating/render_without_controller.rst @@ -77,10 +77,6 @@ this is probably only useful if you'd like to cache this page partial (see Caching the static Template --------------------------- -.. versionadded:: 2.2 - The ability to cache templates rendered via ``FrameworkBundle:Template:template`` - is new in Symfony 2.2. - Since templates that are rendered in this way are typically static, it might make sense to cache them. Fortunately, this is easy! By configuring a few other variables in your route, you can control exactly how your page is cached: @@ -134,4 +130,4 @@ object created in the controller. For more information on caching, see There is also a ``private`` variable (not shown here). By default, the Response will be made public, as long as ``maxAge`` or ``sharedMaxAge`` are passed. -If set to ``true``, the Response will be marked as private. \ No newline at end of file +If set to ``true``, the Response will be marked as private. diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 05d707e370d..2e91dd07e2c 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -405,11 +405,6 @@ would be ``/images/logo.png?version=5``. profiler ~~~~~~~~ -.. versionadded:: 2.2 - The ``enabled`` option was added in Symfony 2.2. Previously, the profiler - could only be disabled by omitting the ``framework.profiler`` configuration - entirely. - .. _profiler.enabled: enabled diff --git a/reference/configuration/security.rst b/reference/configuration/security.rst index dce75e06451..fd33ffc94aa 100644 --- a/reference/configuration/security.rst +++ b/reference/configuration/security.rst @@ -284,9 +284,6 @@ Redirecting after Login Using the PBKDF2 encoder: Security and Speed -------------------------------------------- -.. versionadded:: 2.2 - The PBKDF2 password encoder was added in Symfony 2.2. - The `PBKDF2`_ encoder provides a high level of Cryptographic security, as recommended by the National Institute of Standards and Technology (NIST). @@ -309,9 +306,6 @@ Using the BCrypt Password Encoder To use this encoder, you either need to use PHP Version 5.5 or install the `ircmaxell/password-compat`_ library via Composer. -.. versionadded:: 2.2 - The BCrypt password encoder was added in Symfony 2.2. - .. configuration-block:: .. code-block:: yaml diff --git a/reference/constraints/CardScheme.rst b/reference/constraints/CardScheme.rst index 172ddbfdf70..7e9309c1ea7 100644 --- a/reference/constraints/CardScheme.rst +++ b/reference/constraints/CardScheme.rst @@ -1,9 +1,6 @@ CardScheme ========== -.. versionadded:: 2.2 - The CardScheme validation is new in Symfony 2.2. - This constraint ensures that a credit card number is valid for a given credit card company. It can be used to validate the number before trying to initiate a payment through a payment gateway. diff --git a/reference/constraints/Luhn.rst b/reference/constraints/Luhn.rst index 58697e94184..0907456266b 100644 --- a/reference/constraints/Luhn.rst +++ b/reference/constraints/Luhn.rst @@ -1,9 +1,6 @@ Luhn ==== -.. versionadded:: 2.2 - The Luhn validation is new in Symfony 2.2. - This constraint is used to ensure that a credit card number passes the `Luhn algorithm`_. It is useful as a first step to validating a credit card: before communicating with a payment gateway. diff --git a/reference/constraints/UserPassword.rst b/reference/constraints/UserPassword.rst index e5e1baea42d..fdd9371b40c 100644 --- a/reference/constraints/UserPassword.rst +++ b/reference/constraints/UserPassword.rst @@ -1,14 +1,6 @@ UserPassword ============ -.. note:: - - Since Symfony 2.2, the ``UserPassword*`` classes in the - ``Symfony\\Component\\Security\\Core\\Validator\\Constraint`` namespace are - deprecated and will be removed in Symfony 2.3. Please use the - ``UserPassword*`` classes in the - ``Symfony\\Component\\Security\\Core\\Validator\\Constraints`` namespace instead. - This validates that an input value is equal to the current authenticated user's password. This is useful in a form where a user can change his password, but needs to enter his old password for security. diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index f81362c8dbc..35ed24521e6 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -1216,6 +1216,6 @@ For an example, see the ``EntityInitializer`` class inside the Doctrine Bridge. .. _`Twig's documentation`: http://twig.sensiolabs.org/doc/advanced.html#creating-an-extension .. _`Twig official extension repository`: https://github.com/fabpot/Twig-extensions -.. _`KernelEvents`: https://github.com/symfony/symfony/blob/2.2/src/Symfony/Component/HttpKernel/KernelEvents.php +.. _`KernelEvents`: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/KernelEvents.php .. _`SwiftMailer's Plugin Documentation`: http://swiftmailer.org/docs/plugins.html .. _`Twig Loader`: http://twig.sensiolabs.org/doc/api.html#loaders diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index af020967192..568e21ac668 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -17,10 +17,6 @@ There may also be tags in bundles you use that aren't listed here. Functions --------- -.. versionadded:: 2.2 - The ``render`` and ``controller`` functions are new in Symfony 2.2. Prior, - the ``{% render %}`` tag was used and had a different signature. - +----------------------------------------------------+--------------------------------------------------------------------------------------------+ | Function Syntax | Usage | +====================================================+============================================================================================+ From 3943d8f521a83972b5f373ca8e4f7635cd7113d5 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 3 Nov 2013 10:59:12 -0600 Subject: [PATCH 067/146] [#3084] Putting back message that was incorrect in 2.3, but correct in 2.4/master --- cookbook/logging/monolog_email.rst | 8 -------- 1 file changed, 8 deletions(-) diff --git a/cookbook/logging/monolog_email.rst b/cookbook/logging/monolog_email.rst index e6adcc1553b..b429bc8c588 100644 --- a/cookbook/logging/monolog_email.rst +++ b/cookbook/logging/monolog_email.rst @@ -107,14 +107,6 @@ to and from addresses and the subject. You can combine these handlers with other handlers so that the errors still get logged on the server as well as the emails being sent: -.. caution:: - - The default spool setting for swiftmailer is set to ``memory``, which - means that emails are sent at the very end of the request. However, this - does not work with buffered logs at the moment. In order to enable emailing - logs per the example below, you must comment out the ``spool: { type: memory }`` - line in the ``config.yml`` file. - .. configuration-block:: .. code-block:: yaml From 6829df39bc0236b1b67c49b9b007958907b274e8 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 3 Nov 2013 11:37:08 -0600 Subject: [PATCH 068/146] Removing versionadded 2.1 that leaked in from a merge up --- book/templating.rst | 3 --- 1 file changed, 3 deletions(-) diff --git a/book/templating.rst b/book/templating.rst index 66462490811..f037cb4ac82 100644 --- a/book/templating.rst +++ b/book/templating.rst @@ -676,9 +676,6 @@ that as much code as possible lives in reusable :doc:`services Date: Sun, 3 Nov 2013 12:29:24 -0600 Subject: [PATCH 069/146] [#3114] Lining up spaces --- reference/configuration/framework.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index 01752fbe950..b65c5fda0de 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -463,8 +463,8 @@ Full Default Configuration form: enabled: false csrf_protection: - enabled: true - field_name: ~ + enabled: true + field_name: ~ # esi configuration esi: From 966045557ed7bc3517aa0f55efd0e152c04d20d7 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sun, 3 Nov 2013 15:07:33 +0100 Subject: [PATCH 070/146] use verbose HTTP status code constants --- book/controller.rst | 9 ++++++--- book/from_flat_php_to_symfony2.rst | 5 ++++- book/http_cache.rst | 7 +++++-- book/http_fundamentals.rst | 8 ++++++-- book/internals.rst | 7 +++++-- book/testing.rst | 9 ++++++++- components/http_foundation/introduction.rst | 7 +++++-- cookbook/security/custom_authentication_provider.rst | 7 +++++-- cookbook/service_container/event_listener.rst | 5 ++++- cookbook/testing/insulating_clients.rst | 11 +++++++++-- quick_tour/the_big_picture.rst | 7 +++++-- 11 files changed, 62 insertions(+), 20 deletions(-) diff --git a/book/controller.rst b/book/controller.rst index 7907b70b919..a3ca2610273 100755 --- a/book/controller.rst +++ b/book/controller.rst @@ -501,9 +501,9 @@ value to each variable. directly by duplicating the current request. When this :ref:`sub request ` is executed via the ``http_kernel`` service the ``HttpKernel`` returns a ``Response`` object:: - + use Symfony\Component\HttpKernel\HttpKernelInterface; - + $path = array( '_controller' => 'AcmeHelloBundle:Hello:fancy', 'name' => $name, @@ -750,12 +750,15 @@ headers and content that's sent back to the client:: use Symfony\Component\HttpFoundation\Response; // create a simple Response with a 200 status code (the default) - $response = new Response('Hello '.$name, 200); + $response = new Response('Hello '.$name, Response::HTTP_OK); // create a JSON-response with a 200 status code $response = new Response(json_encode(array('name' => $name))); $response->headers->set('Content-Type', 'application/json'); +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + .. tip:: The ``headers`` property is a diff --git a/book/from_flat_php_to_symfony2.rst b/book/from_flat_php_to_symfony2.rst index 3590fe44353..76b5076f3cb 100644 --- a/book/from_flat_php_to_symfony2.rst +++ b/book/from_flat_php_to_symfony2.rst @@ -476,12 +476,15 @@ the HTTP response being returned. Use them to improve the blog: $response = show_action($request->query->get('id')); } else { $html = '

Page Not Found

'; - $response = new Response($html, 404); + $response = new Response($html, Response::HTTP_NOT_FOUND); } // echo the headers and send the response $response->send(); +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + The controllers are now responsible for returning a ``Response`` object. To make this easier, you can add a new ``render_template()`` function, which, incidentally, acts quite a bit like the Symfony2 templating engine: diff --git a/book/http_cache.rst b/book/http_cache.rst index c1c0b737bea..ab845d1bd85 100644 --- a/book/http_cache.rst +++ b/book/http_cache.rst @@ -1059,15 +1059,18 @@ Here is how you can configure the Symfony2 reverse proxy to support the $response = new Response(); if (!$this->getStore()->purge($request->getUri())) { - $response->setStatusCode(404, 'Not purged'); + $response->setStatusCode(Response::HTTP_NOT_FOUND, 'Not purged'); } else { - $response->setStatusCode(200, 'Purged'); + $response->setStatusCode(Response::HTTP_OK, 'Purged'); } return $response; } } +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + .. caution:: You must protect the ``PURGE`` HTTP method somehow to avoid random people diff --git a/book/http_fundamentals.rst b/book/http_fundamentals.rst index 902a5065b9e..391f549a7d7 100644 --- a/book/http_fundamentals.rst +++ b/book/http_fundamentals.rst @@ -278,12 +278,15 @@ interface to construct the response that needs to be returned to the client:: $response = new Response(); $response->setContent('

Hello world!

'); - $response->setStatusCode(200); + $response->setStatusCode(Response::HTTP_OK); $response->headers->set('Content-Type', 'text/html'); // prints the HTTP headers followed by the content $response->send(); +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + If Symfony offered nothing else, you would already have a toolkit for easily accessing request information and an object-oriented interface for creating the response. Even as you learn the many powerful features in Symfony, keep @@ -364,6 +367,7 @@ on that value. This can get ugly quickly:: // index.php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; + $request = Request::createFromGlobals(); $path = $request->getPathInfo(); // the URI path being requested @@ -372,7 +376,7 @@ on that value. This can get ugly quickly:: } elseif ($path == '/contact') { $response = new Response('Contact us'); } else { - $response = new Response('Page not found.', 404); + $response = new Response('Page not found.', Response::HTTP_NOT_FOUND); } $response->send(); diff --git a/book/internals.rst b/book/internals.rst index 69078e403e1..33a14abb2c9 100644 --- a/book/internals.rst +++ b/book/internals.rst @@ -417,10 +417,13 @@ and set a new ``Exception`` object, or do nothing:: return new Response( 'Error', - 404 // ignored, - array('X-Status-Code' => 200) + Response::HTTP_NOT_FOUND, // ignored + array('X-Status-Code' => Response::HTTP_OK) ); + .. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + .. index:: single: Event Dispatcher diff --git a/book/testing.rst b/book/testing.rst index 4deb4229075..34e206f87b0 100644 --- a/book/testing.rst +++ b/book/testing.rst @@ -268,6 +268,10 @@ document:: To get you started faster, here is a list of the most common and useful test assertions:: + use Symfony\Component\HttpFoundation\Response; + + // ... + // Assert that there is at least one h2 tag // with the class "subtitle" $this->assertGreaterThan( @@ -295,7 +299,7 @@ document:: $this->assertTrue($client->getResponse()->isNotFound()); // Assert a specific 200 status code $this->assertEquals( - 200, + Response::HTTP_OK, $client->getResponse()->getStatusCode() ); @@ -306,6 +310,9 @@ document:: // or simply check that the response is a redirect to any URL $this->assertTrue($client->getResponse()->isRedirect()); + .. versionadded:: 2.4 + Support for HTTP status code constants was added with Symfony 2.4. + .. index:: single: Tests; Client diff --git a/components/http_foundation/introduction.rst b/components/http_foundation/introduction.rst index f7cb342037e..185b5366fbb 100644 --- a/components/http_foundation/introduction.rst +++ b/components/http_foundation/introduction.rst @@ -309,10 +309,13 @@ code, and an array of HTTP headers:: $response = new Response( 'Content', - 200, + Response::HTTP_OK, array('content-type' => 'text/html') ); +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + These information can also be manipulated after the Response object creation:: $response->setContent('Hello World'); @@ -320,7 +323,7 @@ These information can also be manipulated after the Response object creation:: // the headers public attribute is a ResponseHeaderBag $response->headers->set('Content-Type', 'text/plain'); - $response->setStatusCode(404); + $response->setStatusCode(Response::HTTP_NOT_FOUND); When setting the ``Content-Type`` of the Response, you can set the charset, but it is better to set it via the diff --git a/cookbook/security/custom_authentication_provider.rst b/cookbook/security/custom_authentication_provider.rst index 26e3219c062..729c03b5165 100644 --- a/cookbook/security/custom_authentication_provider.rst +++ b/cookbook/security/custom_authentication_provider.rst @@ -153,18 +153,21 @@ set an authenticated token in the security context if successful. // Deny authentication with a '403 Forbidden' HTTP response $response = new Response(); - $response->setStatusCode(403); + $response->setStatusCode(Response::HTTP_FORBIDDEN); $event->setResponse($response); } // By default deny authorization $response = new Response(); - $response->setStatusCode(403); + $response->setStatusCode(Response::HTTP_FORBIDDEN); $event->setResponse($response); } } +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + This listener checks the request for the expected `X-WSSE` header, matches the value returned for the expected WSSE information, creates a token using that information, and passes the token on to the authentication manager. If diff --git a/cookbook/service_container/event_listener.rst b/cookbook/service_container/event_listener.rst index 7e0b5410f79..91f20364bee 100644 --- a/cookbook/service_container/event_listener.rst +++ b/cookbook/service_container/event_listener.rst @@ -43,7 +43,7 @@ event is just one of the core kernel events:: $response->setStatusCode($exception->getStatusCode()); $response->headers->replace($exception->getHeaders()); } else { - $response->setStatusCode(500); + $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); } // Send the modified response object to the event @@ -51,6 +51,9 @@ event is just one of the core kernel events:: } } +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + .. tip:: Each event receives a slightly different type of ``$event`` object. For diff --git a/cookbook/testing/insulating_clients.rst b/cookbook/testing/insulating_clients.rst index 3411968eb80..f9c602dcf67 100644 --- a/cookbook/testing/insulating_clients.rst +++ b/cookbook/testing/insulating_clients.rst @@ -7,19 +7,26 @@ How to test the Interaction of several Clients If you need to simulate an interaction between different Clients (think of a chat for instance), create several Clients:: + // ... + $harry = static::createClient(); $sally = static::createClient(); $harry->request('POST', '/say/sally/Hello'); $sally->request('GET', '/messages'); - $this->assertEquals(201, $harry->getResponse()->getStatusCode()); + $this->assertEquals(Response::HTTP_CREATED, $harry->getResponse()->getStatusCode()); $this->assertRegExp('/Hello/', $sally->getResponse()->getContent()); +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. + This works except when your code maintains a global state or if it depends on a third-party library that has some kind of global state. In such a case, you can insulate your clients:: + // ... + $harry = static::createClient(); $sally = static::createClient(); @@ -29,7 +36,7 @@ can insulate your clients:: $harry->request('POST', '/say/sally/Hello'); $sally->request('GET', '/messages'); - $this->assertEquals(201, $harry->getResponse()->getStatusCode()); + $this->assertEquals(Response::HTTP_CREATED, $harry->getResponse()->getStatusCode()); $this->assertRegExp('/Hello/', $sally->getResponse()->getContent()); Insulated clients transparently execute their requests in a dedicated and diff --git a/quick_tour/the_big_picture.rst b/quick_tour/the_big_picture.rst index 9ba1161c7a6..8436651ba33 100644 --- a/quick_tour/the_big_picture.rst +++ b/quick_tour/the_big_picture.rst @@ -232,7 +232,10 @@ controller might create the response by hand, based on the request:: $name = $request->query->get('name'); - return new Response('Hello '.$name, 200, array('Content-Type' => 'text/plain')); + return new Response('Hello '.$name, Response::HTTP_OK, array('Content-Type' => 'text/plain')); + +.. versionadded:: 2.4 + Support for HTTP status code constants was added in Symfony 2.4. .. note:: @@ -421,7 +424,7 @@ When loaded and enabled (by default in the ``dev`` :ref:`environment Date: Sat, 9 Nov 2013 13:38:07 +0100 Subject: [PATCH 071/146] Bumped version number --- components/dependency_injection/lazy_services.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/dependency_injection/lazy_services.rst b/components/dependency_injection/lazy_services.rst index 8f80997777b..3ec19f35fb5 100644 --- a/components/dependency_injection/lazy_services.rst +++ b/components/dependency_injection/lazy_services.rst @@ -40,7 +40,7 @@ the `ProxyManager bridge`_: .. code-block:: json "require": { - "ocramius/proxy-manager": "0.4.*" + "ocramius/proxy-manager": "0.5.*" } to your ``composer.json``. Afterwards compile your container and check From c5ae3dd4c440b25fe150d9599799d4c5cbf2ebe3 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 12 Sep 2013 17:42:39 -0500 Subject: [PATCH 072/146] [#2956] Refactoring the scopes entry entirely to not talk about the request anymore, since it has a simpler solution See sha: b84f52c28d969b5143521261d818105824eaea5e for more information. --- cookbook/service_container/scopes.rst | 201 ++++++++++++++------------ 1 file changed, 107 insertions(+), 94 deletions(-) diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 78ccb76126f..32884424732 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -12,7 +12,9 @@ This entry is all about scopes, a somewhat advanced topic related to the If you are trying to inject the ``request`` service, the simple solution is to inject the ``request_stack`` service instead and access the current - Request by calling the ``getCurrentRequest()`` method. + Request by calling the ``getCurrentRequest()`` method. The rest of this + entry talks about scopes in a theoretical and more advanced way. If you're + dealing with scopes for the ``request`` service, simply inject ``request_stack``. Understanding Scopes -------------------- @@ -32,10 +34,22 @@ also defines a third scope: ``request``. This scope is tied to the request, meaning a new instance is created for each subrequest and is unavailable outside the request (for instance in the CLI). +The Example: client Scope +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Other than the ``request`` service (which has a simple solution, see the +above note), no services in the default Symfony2 container belong to any +scope other than ``container`` and ``prototype``. But for the purposes of +this entry, imagine there is another scope ``client`` and a service ``client_configuration`` +that belongs to it. This is not a common situation, but the idea is that +you may enter and exit multiple ``client`` scopes during a request, and each +has its own ``client_configuration`` service. + Scopes add a constraint on the dependencies of a service: a service cannot depend on services from a narrower scope. For example, if you create a generic -``my_foo`` service, but try to inject the ``request`` service, you will receive -a :class:`Symfony\\Component\\DependencyInjection\\Exception\\ScopeWideningInjectionException` +``my_foo`` service, but try to inject the ``client_configuration`` service, +you will receive a +:class:`Symfony\\Component\\DependencyInjection\\Exception\\ScopeWideningInjectionException` when compiling the container. Read the sidebar below for more details. .. sidebar:: Scopes and Dependencies @@ -45,28 +59,29 @@ when compiling the container. Read the sidebar below for more details. every time you ask the container for the ``my_mailer`` service, you get the same object back. This is usually how you want your services to work. - Imagine, however, that you need the ``request`` service in your ``my_mailer`` - service, maybe because you're reading the URL of the current request. - So, you add it as a constructor argument. Let's look at why this presents - a problem: + Imagine, however, that you need the ``client_configuration`` service + in your ``my_mailer`` service, maybe because you're reading some details + from it, such as what the "sender" address should be. You add it as a + constructor argument. Let's look at why this presents a problem: * When requesting ``my_mailer``, an instance of ``my_mailer`` (let's call - it *MailerA*) is created and the ``request`` service (let's call it - *RequestA*) is passed to it. Life is good! + it *MailerA*) is created and the ``client_configuration`` service (let's + call it *ConfigurationA*) is passed to it. Life is good! - * You've now made a subrequest in Symfony, which is a fancy way of saying - that you've called, for example, the ``{{ render(...) }}`` Twig function, - which executes another controller. Internally, the old ``request`` service - (*RequestA*) is actually replaced by a new request instance (*RequestB*). - This happens in the background, and it's totally normal. + * Your application now needs to do something with another client, and + you've architected your application in such a way that you handle this + by entering a new ``client_configuration`` scope and setting a new + ``client_configuration`` service into the container. Let's call this + *ConfigurationB*. - * In your embedded controller, you once again ask for the ``my_mailer`` + * Somewhere in your application, you once again ask for the ``my_mailer`` service. Since your service is in the ``container`` scope, the same instance (*MailerA*) is just re-used. But here's the problem: the - *MailerA* instance still contains the old *RequestA* object, which - is now **not** the correct request object to have (*RequestB* is now - the current ``request`` service). This is subtle, but the mis-match could - cause major problems, which is why it's not allowed. + *MailerA* instance still contains the old *ConfigurationA* object, which + is now **not** the correct configuration object to have (*ConfigurationB* + is now the current ``client_configuration`` service). This is subtle, + but the mis-match could cause major problems, which is why it's not + allowed. So, that's the reason *why* scopes exist, and how they can cause problems. Keep reading to find out the common solutions. @@ -79,19 +94,14 @@ when compiling the container. Read the sidebar below for more details. Using a Service from a narrower Scope ------------------------------------- -The most common problem with "scope" is when your service has a dependency -on the ``request`` service. The *easiest* way to solve this is to instead -inject the ``request_stack`` service and access the current Request by calling -the ``getCurrentRequest()`` method. - -This solution is great, but there are also others: +There are several solutions to the scope problem: * Use setter injection if the dependency is "synchronized"; (see :ref:`using-synchronized-service`). * Put your service in the same scope as the dependency (or a narrower one). If - you depend on the ``request`` service, this means putting your new service - in the ``request`` scope (see :ref:`changing-service-scope`); + you depend on the ``client_configuration`` service, this means putting your + new service in the ``client`` scope (see :ref:`changing-service-scope`); * Pass the entire container to your service and retrieve your dependency from the container each time you need it to be sure you have the right instance @@ -109,42 +119,81 @@ Using a synchronized Service Synchronized services are new in Symfony 2.3. Injecting the container or setting your service to a narrower scope have -drawbacks. For synchronized services (like the ``request``), using setter -injection is a nice option as it has no drawbacks and everything works -without any special code in your service or in your definition:: +drawbacks. Assume first that the ``client_configuration`` service has been +marked as "synchronized": + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + services: + client_configuration: + class: Acme\HelloBundle\Client\ClientConfiguration + scope: client + synchronized: true + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // app/config/config.php + use Symfony\Component\DependencyInjection\Definition; + + $defn = new Definition( + 'Acme\HelloBundle\Client\ClientConfiguration', + array() + ); + $defn->setScope('client'); + $defn->setSynchronized(true); + $container->setDefinition('client_configuration', $defn); + +Now, if you inject this service using setter injection, there are no drawbacks +and everything works without any special code in your service or in your definition:: // src/Acme/HelloBundle/Mail/Mailer.php namespace Acme\HelloBundle\Mail; - use Symfony\Component\HttpFoundation\Request; + use Acme\HelloBundle\Client\ClientConfiguration; class Mailer { - protected $request; + protected $clientConfiguration; - public function setRequest(Request $request = null) + public function setClientConfiguration(ClientConfiguration $clientConfiguration = null) { - $this->request = $request; + $this->clientConfiguration = $clientConfiguration; } public function sendEmail() { - if (null === $this->request) { + if (null === $this->clientConfiguration) { // throw an error? } - // ... do something using the request here + // ... do something using the client configuration here } } -Whenever the ``request`` scope is entered or left, the service container will -automatically call the ``setRequest()`` method with the current ``request`` -instance. +Whenever the ``client`` scope is entered or left, the service container will +automatically call the ``setClientConfiguration()`` method with the current +``client_configuration`` instance. -You might have noticed that the ``setRequest()`` method accepts ``null`` as a -valid value for the ``request`` argument. That's because when leaving the -``request`` scope, the ``request`` instance can be ``null`` (for the master -request for instance). Of course, you should take care of this possibility in +You might have noticed that the ``setClientConfiguration()`` method accepts +``null`` as a valid value for the ``client_configuration`` argument. That's +because when leaving the ``client`` scope, the ``client_configuration`` instance +can be ``null``. Of course, you should take care of this possibility in your code. This should also be taken into account when declaring your service: .. configuration-block:: @@ -156,7 +205,7 @@ your code. This should also be taken into account when declaring your service: greeting_card_manager: class: Acme\HelloBundle\Mail\GreetingCardManager calls: - - [setRequest, ['@?request=']] + - [setClientConfiguration, ['@?client_configuration=']] .. code-block:: xml @@ -165,8 +214,8 @@ your code. This should also be taken into account when declaring your service: - - + + @@ -181,46 +230,10 @@ your code. This should also be taken into account when declaring your service: 'greeting_card_manager', new Definition('Acme\HelloBundle\Mail\GreetingCardManager') ) - ->addMethodCall('setRequest', array( - new Reference('request', ContainerInterface::NULL_ON_INVALID_REFERENCE, false) + ->addMethodCall('setClientConfiguration', array( + new Reference('client_configuration', ContainerInterface::NULL_ON_INVALID_REFERENCE, false) )); -.. tip:: - - You can declare your own ``synchronized`` services very easily; here is - the declaration of the ``request`` service for reference: - - .. configuration-block:: - - .. code-block:: yaml - - services: - request: - scope: request - synthetic: true - synchronized: true - - .. code-block:: xml - - - - - - .. code-block:: php - - use Symfony\Component\DependencyInjection\Definition; - use Symfony\Component\DependencyInjection\ContainerInterface; - - $definition = $container->setDefinition('request') - ->setScope('request') - ->setSynthetic(true) - ->setSynchronized(true); - -.. caution:: - - The service using the synchronized service will need to be public in order - to have its setter called when the scope changes. - .. _changing-service-scope: Changing the Scope of your Service @@ -236,8 +249,8 @@ Changing the scope of a service should be done in its definition: services: greeting_card_manager: class: Acme\HelloBundle\Mail\GreetingCardManager - scope: request - arguments: [@request] + scope: client + arguments: [@client_configuration] .. code-block:: xml @@ -245,9 +258,9 @@ Changing the scope of a service should be done in its definition: - + .. code-block:: php @@ -259,9 +272,9 @@ Changing the scope of a service should be done in its definition: 'greeting_card_manager', new Definition( 'Acme\HelloBundle\Mail\GreetingCardManager', - array(new Reference('request'), + array(new Reference('client_configuration'), )) - )->setScope('request'); + )->setScope('client'); .. _passing-container: @@ -289,15 +302,15 @@ into your service:: public function sendEmail() { - $request = $this->container->get('request'); - // ... do something using the request here + $request = $this->container->get('client_configuration'); + // ... do something using the client configuration here } } .. caution:: - Take care not to store the request in a property of the object for a - future call of the service as it would cause the same issue described + Take care not to store the client configuration in a property of the object + for a future call of the service as it would cause the same issue described in the first section (except that Symfony cannot detect that you are wrong). From d417f7b4363011dacd6f91a99e94e602fe35f97d Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 11 Nov 2013 21:04:18 -0500 Subject: [PATCH 073/146] [#2972] Many small tweaks - thanks very much to @WouterJ and @xabbuh --- book/service_container.rst | 2 + cookbook/service_container/scopes.rst | 102 +++++++++++++++----------- 2 files changed, 63 insertions(+), 41 deletions(-) diff --git a/book/service_container.rst b/book/service_container.rst index 2d3b65ab0c5..a5c7b3d0748 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -754,6 +754,8 @@ Injecting the dependency by the setter method just needs a change of syntax: and "setter injection". The Symfony2 service container also supports "property injection". +.. _book-container-request-stack: + Injecting the Request ~~~~~~~~~~~~~~~~~~~~~ diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 32884424732..03d94e1a426 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -12,9 +12,10 @@ This entry is all about scopes, a somewhat advanced topic related to the If you are trying to inject the ``request`` service, the simple solution is to inject the ``request_stack`` service instead and access the current - Request by calling the ``getCurrentRequest()`` method. The rest of this - entry talks about scopes in a theoretical and more advanced way. If you're - dealing with scopes for the ``request`` service, simply inject ``request_stack``. + Request by calling the ``getCurrentRequest()`` method (see :ref:`book-container-request-stack`). + The rest of this entry talks about scopes in a theoretical and more advanced + way. If you're dealing with scopes for the ``request`` service, simply + inject ``request_stack``. Understanding Scopes -------------------- @@ -34,8 +35,8 @@ also defines a third scope: ``request``. This scope is tied to the request, meaning a new instance is created for each subrequest and is unavailable outside the request (for instance in the CLI). -The Example: client Scope -~~~~~~~~~~~~~~~~~~~~~~~~~ +An Example: client Scope +~~~~~~~~~~~~~~~~~~~~~~~~ Other than the ``request`` service (which has a simple solution, see the above note), no services in the default Symfony2 container belong to any @@ -64,14 +65,14 @@ when compiling the container. Read the sidebar below for more details. from it, such as what the "sender" address should be. You add it as a constructor argument. Let's look at why this presents a problem: - * When requesting ``my_mailer``, an instance of ``my_mailer`` (let's call - it *MailerA*) is created and the ``client_configuration`` service (let's - call it *ConfigurationA*) is passed to it. Life is good! + * When requesting ``my_mailer``, an instance of ``my_mailer`` (called + *MailerA* here) is created and the ``client_configuration`` service ( + called *ConfigurationA* here) is passed to it. Life is good! * Your application now needs to do something with another client, and you've architected your application in such a way that you handle this by entering a new ``client_configuration`` scope and setting a new - ``client_configuration`` service into the container. Let's call this + ``client_configuration`` service into the container. Call this *ConfigurationB*. * Somewhere in your application, you once again ask for the ``my_mailer`` @@ -96,14 +97,14 @@ Using a Service from a narrower Scope There are several solutions to the scope problem: -* Use setter injection if the dependency is "synchronized"; (see +* A) Use setter injection if the dependency is "synchronized"; (see :ref:`using-synchronized-service`). -* Put your service in the same scope as the dependency (or a narrower one). If +* B) Put your service in the same scope as the dependency (or a narrower one). If you depend on the ``client_configuration`` service, this means putting your new service in the ``client`` scope (see :ref:`changing-service-scope`); -* Pass the entire container to your service and retrieve your dependency from +* C) Pass the entire container to your service and retrieve your dependency from the container each time you need it to be sure you have the right instance -- your service can live in the default ``container`` scope (see :ref:`passing-container`); @@ -112,15 +113,15 @@ Each scenario is detailed in the following sections. .. _using-synchronized-service: -Using a synchronized Service -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A) Using a synchronized Service +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2.3 Synchronized services are new in Symfony 2.3. -Injecting the container or setting your service to a narrower scope have +Both injecting the container and setting your service to a narrower scope have drawbacks. Assume first that the ``client_configuration`` service has been -marked as "synchronized": +marked as ``synchronized``: .. configuration-block:: @@ -132,6 +133,7 @@ marked as "synchronized": class: Acme\HelloBundle\Client\ClientConfiguration scope: client synchronized: true + # ... .. code-block:: xml @@ -139,10 +141,17 @@ marked as "synchronized": + xsi:schemaLocation="http://symfony.com/schema/dic/services + http://symfony.com/schema/dic/services/services-1.0.xsd" + > - + @@ -151,13 +160,13 @@ marked as "synchronized": // app/config/config.php use Symfony\Component\DependencyInjection\Definition; - $defn = new Definition( + $definition = new Definition( 'Acme\HelloBundle\Client\ClientConfiguration', array() ); - $defn->setScope('client'); - $defn->setSynchronized(true); - $container->setDefinition('client_configuration', $defn); + $definition->setScope('client'); + $definition->setSynchronized(true); + $container->setDefinition('client_configuration', $definition); Now, if you inject this service using setter injection, there are no drawbacks and everything works without any special code in your service or in your definition:: @@ -202,8 +211,8 @@ your code. This should also be taken into account when declaring your service: # src/Acme/HelloBundle/Resources/config/services.yml services: - greeting_card_manager: - class: Acme\HelloBundle\Mail\GreetingCardManager + my_mailer: + class: Acme\HelloBundle\Mail\Mailer calls: - [setClientConfiguration, ['@?client_configuration=']] @@ -211,11 +220,16 @@ your code. This should also be taken into account when declaring your service: - - + @@ -227,19 +241,25 @@ your code. This should also be taken into account when declaring your service: use Symfony\Component\DependencyInjection\ContainerInterface; $definition = $container->setDefinition( - 'greeting_card_manager', - new Definition('Acme\HelloBundle\Mail\GreetingCardManager') + 'my_mailer', + new Definition('Acme\HelloBundle\Mail\Mailer') ) ->addMethodCall('setClientConfiguration', array( - new Reference('client_configuration', ContainerInterface::NULL_ON_INVALID_REFERENCE, false) + new Reference( + 'client_configuration', + ContainerInterface::NULL_ON_INVALID_REFERENCE, + false + ) )); .. _changing-service-scope: -Changing the Scope of your Service -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +B) Changing the Scope of your Service +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Changing the scope of a service should be done in its definition: +Changing the scope of a service should be done in its definition. This example +assumes that the ``Mailer`` class has a ``__construct`` function whose first +argument is the ``ClientConfiguration`` object: .. configuration-block:: @@ -247,8 +267,8 @@ Changing the scope of a service should be done in its definition: # src/Acme/HelloBundle/Resources/config/services.yml services: - greeting_card_manager: - class: Acme\HelloBundle\Mail\GreetingCardManager + my_mailer: + class: Acme\HelloBundle\Mail\Mailer scope: client arguments: [@client_configuration] @@ -256,8 +276,8 @@ Changing the scope of a service should be done in its definition: - @@ -269,17 +289,17 @@ Changing the scope of a service should be done in its definition: use Symfony\Component\DependencyInjection\Definition; $definition = $container->setDefinition( - 'greeting_card_manager', + 'my_mailer', new Definition( - 'Acme\HelloBundle\Mail\GreetingCardManager', + 'Acme\HelloBundle\Mail\Mailer', array(new Reference('client_configuration'), )) )->setScope('client'); .. _passing-container: -Passing the Container as a Dependency of your Service -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +C) Passing the Container as a Dependency of your Service +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Setting the scope to a narrower one is not always possible (for instance, a twig extension must be in the ``container`` scope as the Twig environment From 3dcbbc25772b7e87388bf04b79d855b2a2911306 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 11 Nov 2013 21:12:38 -0500 Subject: [PATCH 074/146] [#2972] Clarifying how to use the request_stack with an example --- book/service_container.rst | 93 ++++++++++++++++++++++++++++++++------ 1 file changed, 79 insertions(+), 14 deletions(-) diff --git a/book/service_container.rst b/book/service_container.rst index a5c7b3d0748..8644d93685a 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -762,22 +762,87 @@ Injecting the Request .. versionadded:: 2.4 The ``request_stack`` service was introduced in version 2.4. -Almost all Symfony2 built-in services behave in the same way: a single -instance is created by the container which it returns whenever you get it or -when it is injected into another service. There is one exception in a standard -Symfony2 application: the ``request`` service. - -If you try to inject the ``request`` into a service, you will probably receive -a -:class:`Symfony\\Component\\DependencyInjection\\Exception\\ScopeWideningInjectionException` -exception. That's because the ``request`` can **change** during the life-time -of a container (when a sub-request is created for instance). - As of Symfony 2.4, instead of injecting the ``request`` service, you should inject the ``request_stack`` service instead and access the Request by calling -the ``getCurrentRequest()`` method. For earlier versions, or if you want to -understand this problem better, refer to the cookbook article -:doc:`/cookbook/service_container/scopes`. +the ``getCurrentRequest()`` method: + + namespace Acme\HelloBundle\Newsletter; + + use Symfony\Component\HttpFoundation\RequestStack; + + class NewsletterManager + { + protected $requestStack; + + public function __construct(RequestStack $requestStack) + { + $this->requestStack = $requestStack; + } + + public function anyMethod() + { + $request = $this->requestStack->getCurrentRequest(); + // ... do something with the request + } + + // ... + } + +Now, just inject the ``request_stack``, which behaves like any normal service: + +.. configuration-block:: + + .. code-block:: yaml + + # src/Acme/HelloBundle/Resources/config/services.yml + services: + newsletter_manager: + class: "Acme\HelloBundle\Newsletter\NewsletterManager" + arguments: ["@request_stack"] + + .. code-block:: xml + + + + + + + + + + + + + .. code-block:: php + + // src/Acme/HelloBundle/Resources/config/services.php + use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\DependencyInjection\Reference; + + // ... + $container->setDefinition('newsletter_manager', new Definition( + 'Acme\HelloBundle\Newsletter\NewsletterManager', + array(new Reference('request_stack')) + )); + +.. sidebar: Why not Inject the request Service? + + Almost all Symfony2 built-in services behave in the same way: a single + instance is created by the container which it returns whenever you get it or + when it is injected into another service. There is one exception in a standard + Symfony2 application: the ``request`` service. + + If you try to inject the ``request`` into a service, you will probably receive + a + :class:`Symfony\\Component\\DependencyInjection\\Exception\\ScopeWideningInjectionException` + exception. That's because the ``request`` can **change** during the life-time + of a container (when a sub-request is created for instance). + .. tip:: From 80a364386ed8016fad881d3b911b6bcb90f055cc Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 12 Nov 2013 11:37:27 +0100 Subject: [PATCH 075/146] some tweaks and fixes to d417f7b and 3dcbbc2 --- book/service_container.rst | 7 ++++--- cookbook/service_container/scopes.rst | 21 +++++++++++---------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/book/service_container.rst b/book/service_container.rst index 8644d93685a..830a660e858 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -763,8 +763,9 @@ Injecting the Request The ``request_stack`` service was introduced in version 2.4. As of Symfony 2.4, instead of injecting the ``request`` service, you should -inject the ``request_stack`` service instead and access the Request by calling -the ``getCurrentRequest()`` method: +inject the ``request_stack`` service and access the ``Request`` by calling +the :method:`Symfony\\Component\\HttpFoundation\\RequestStack::getCurrentRequest` +method:: namespace Acme\HelloBundle\Newsletter; @@ -830,7 +831,7 @@ Now, just inject the ``request_stack``, which behaves like any normal service: array(new Reference('request_stack')) )); -.. sidebar: Why not Inject the request Service? +.. sidebar:: Why not Inject the ``request`` Service? Almost all Symfony2 built-in services behave in the same way: a single instance is created by the container which it returns whenever you get it or diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 03d94e1a426..44f9ade52b2 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -12,10 +12,11 @@ This entry is all about scopes, a somewhat advanced topic related to the If you are trying to inject the ``request`` service, the simple solution is to inject the ``request_stack`` service instead and access the current - Request by calling the ``getCurrentRequest()`` method (see :ref:`book-container-request-stack`). - The rest of this entry talks about scopes in a theoretical and more advanced - way. If you're dealing with scopes for the ``request`` service, simply - inject ``request_stack``. + Request by calling the + :method:`Symfony\\Component\\HttpFoundation\\RequestStack::getCurrentRequest` + method (see :ref:`book-container-request-stack`). The rest of this entry + talks about scopes in a theoretical and more advanced way. If you're + dealing with scopes for the ``request`` service, simply inject ``request_stack``. Understanding Scopes -------------------- @@ -35,7 +36,7 @@ also defines a third scope: ``request``. This scope is tied to the request, meaning a new instance is created for each subrequest and is unavailable outside the request (for instance in the CLI). -An Example: client Scope +An Example: Client Scope ~~~~~~~~~~~~~~~~~~~~~~~~ Other than the ``request`` service (which has a simple solution, see the @@ -92,13 +93,13 @@ when compiling the container. Read the sidebar below for more details. A service can of course depend on a service from a wider scope without any issue. -Using a Service from a narrower Scope +Using a Service from a Narrower Scope ------------------------------------- There are several solutions to the scope problem: -* A) Use setter injection if the dependency is "synchronized"; (see - :ref:`using-synchronized-service`). +* A) Use setter injection if the dependency is ``synchronized`` (see + :ref:`using-synchronized-service`); * B) Put your service in the same scope as the dependency (or a narrower one). If you depend on the ``client_configuration`` service, this means putting your @@ -107,13 +108,13 @@ There are several solutions to the scope problem: * C) Pass the entire container to your service and retrieve your dependency from the container each time you need it to be sure you have the right instance -- your service can live in the default ``container`` scope (see - :ref:`passing-container`); + :ref:`passing-container`). Each scenario is detailed in the following sections. .. _using-synchronized-service: -A) Using a synchronized Service +A) Using a Synchronized Service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2.3 From 343a59e9ea58ed750d1c6211db349d3b2cc4352e Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 13 Nov 2013 08:52:16 -0500 Subject: [PATCH 076/146] Removing some 2.1 references that were merged up --- reference/forms/types/options/error_mapping.rst.inc | 3 --- reference/twig_reference.rst | 3 --- 2 files changed, 6 deletions(-) diff --git a/reference/forms/types/options/error_mapping.rst.inc b/reference/forms/types/options/error_mapping.rst.inc index e6b55fb0ff5..05ad2148c34 100644 --- a/reference/forms/types/options/error_mapping.rst.inc +++ b/reference/forms/types/options/error_mapping.rst.inc @@ -3,9 +3,6 @@ error_mapping **type**: ``array`` **default**: ``empty`` -.. versionadded:: 2.1 - The ``error_mapping`` option is new to Symfony 2.1. - This option allows you to modify the target of a validation error. Imagine you have a custom method named ``matchingCityAndZipCode`` that validates diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index 6c091825062..45a920a9481 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -93,9 +93,6 @@ Functions Filters ------- -.. versionadded:: 2.1 - The ``humanize`` filter was added in Symfony 2.1 - +---------------------------------------------------------------------------------+-------------------------------------------------------------------+ | Filter Syntax | Usage | +=================================================================================+===================================================================+ From ff4a44ee605d525ec02e2c7f8bfa8f1284566aa6 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 16 Nov 2013 16:21:52 -0600 Subject: [PATCH 077/146] [#2906][#3190] Removing versionadded:: 2.1 tags after merge --- book/translation.rst | 8 -------- components/translation/introduction.rst | 5 ----- 2 files changed, 13 deletions(-) diff --git a/book/translation.rst b/book/translation.rst index 4dcbe5e2495..7605aee3d16 100644 --- a/book/translation.rst +++ b/book/translation.rst @@ -305,9 +305,6 @@ texts* and complex expressions: Note that this only influences the current template, not any "included" templates (in order to avoid side effects). -.. versionadded:: 2.1 - The ``trans_default_domain`` tag is new in Symfony2.1 - PHP Templates ~~~~~~~~~~~~~ @@ -520,11 +517,6 @@ the framework: 'default_locale' => 'en', )); -.. versionadded:: 2.1 - The ``default_locale`` parameter was defined under the session key - originally, however, as of 2.1 this has been moved. This is because the - locale is now set on the request instead of the session. - .. _book-translation-constraint-messages: Translating Constraint Messages diff --git a/components/translation/introduction.rst b/components/translation/introduction.rst index 31c3074680e..a21ee5d6aea 100644 --- a/components/translation/introduction.rst +++ b/components/translation/introduction.rst @@ -88,11 +88,6 @@ Loader too. The default loaders are: * :class:`Symfony\\Component\\Translation\\Loader\\YamlFileLoader` - to load catalogs from Yaml files (requires the :doc:`Yaml component`). -.. versionadded:: 2.1 - The ``IcuDatFileLoader``, ``IcuResFileLoader``, ``IniFileLoader``, - ``MofileLoader``, ``PoFileLoader`` and ``QtFileLoader`` are new in - Symfony 2.1 - All file loaders require the :doc:`Config component`. At first, you should add one or more loaders to the ``Translator``:: From 55a2de49dce07919f5e79f0d1aaded50e37fe934 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Fri, 22 Nov 2013 18:00:40 -0600 Subject: [PATCH 078/146] Removing a versionadded:: 2.1 that came from the merge --- components/filesystem.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/components/filesystem.rst b/components/filesystem.rst index 1a2252a7f6a..2f84a598ffb 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -6,10 +6,6 @@ The Filesystem Component The Filesystem component provides basic utilities for the filesystem. -.. versionadded:: 2.1 - The Filesystem component is new to Symfony 2.1. Previously, the ``Filesystem`` - class was located in the HttpKernel component. - Installation ------------ From e9a81bfdf19aac7dc4f85f90d01efc65101bbbf8 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sat, 16 Nov 2013 19:06:59 -0600 Subject: [PATCH 079/146] [#3044] Furthering @WouterJ's work on the ExpressionLanguage component This adds more examples, details about how to pass in variables, and working with objects/arrays --- .../expression_language/introduction.rst | 69 ++++++- components/expression_language/syntax.rst | 181 ++++++++++++++++-- 2 files changed, 230 insertions(+), 20 deletions(-) diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index a7f474c732a..da23a869e0f 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -10,24 +10,51 @@ The ExpressionLanguage Component (mostly, but not limited to, Booleans). .. versionadded:: 2.4 - The ExpressionLanguage component was new in Symfony 2.4. + The ExpressionLanguage component was added in Symfony 2.4. Installation ------------ You can install the component in 2 different ways: -* Use the official Git repository (https://github.com/symfony/expression-language); * :doc:`Install it via Composer ` (``symfony/expression-language`` on `Packagist`_). +* Use the official Git repository (https://github.com/symfony/expression-language); + +How can the Expression Engine Help Me? +-------------------------------------- + +The purpose of the component is to allow users to use expressions inside +configuration for more complex logic. In the Symfony2 Framework, for example, +expressions can be used 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*. +The idea is to let the webmaster of a website configure things in a dynamic +way without using PHP and without introducing security problems: + +.. code-block:: text + + # Get the special price if + user.getGroup() in ['good_customers', 'collaborator'] + + # Promote article to the homepage when + article.commentCount > 100 and article.category not in ["misc"] + + # 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. Usage ----- The ExpressionLanguage component can compile and evaluate expressions. -Expressions are one-liners which most of the time return a boolean, you can -compare them to the expression in an ``if`` statement. A simple example of an -expression is ``1 + 2``. You can also use more complicated expressions, such -as ``someArray[3].someMethod('bar')``. +Expressions are one-liners that often return a Boolean, which can be used +by the code executing the expression in an ``if`` statements. A simple example +of an expression is ``1 + 2``. You can also use more complicated expressions, +such as ``someArray[3].someMethod('bar')``. The component provides 2 ways to work with expressions: @@ -49,7 +76,35 @@ The main class of the component is Expression Syntax ----------------- -See ":doc:`/components/expression_language/syntax`" to learn the syntax of the +See :doc:`/components/expression_language/syntax` to learn the syntax of the ExpressionLanguage component. +Passing in Variables +-------------------- + +You can also pass variables into the expression, which can be of any valid +PHP type (including objects):: + + use Symfony\Component\ExpressionLanguage\ExpressionLanguage; + + $language = new ExpressionLanguage(); + + class Apple + { + public $variety; + } + + $apple = new Apple(); + $apple->variety = 'Honeycrisp'; + + echo $language->evaluate( + 'fruit.variety', + array( + 'fruit' => $apple, + ) + ); + +This will print "Honeycrisp". For more information, see the :doc:`/components/expression_language/syntax` +entry, especially :ref:`component-expression-objects` and :ref:`component-expression-arrays`. + .. _Packagist: https://packagist.org/packages/symfony/expression-language diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index 7c3a59fccb9..4cc7da1192b 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -9,24 +9,102 @@ 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 twig notation (e.g. ``[1, 2]``) -* **hashes** - using twig notation (e.g. ``{ foo: 'bar' }``) +* **arrays** - using JSON-like notation (e.g. ``[1, 2]``) +* **hashes** - using JSON-like notation (e.g. ``{ foo: 'bar' }``) * **booleans** - ``true`` and ``false`` * **null** - ``null`` +.. _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 Methods +~~~~~~~~~~~~~~~~~~~~~~~~ + +Public properties on objects can be accessed by using the ``.`` syntax, similar +to JavaScript:: + + class Apple + { + public $variety; + } + + $apple = new Apple(); + $apple->variety = 'Honeycrisp'; + + echo $language->evaluate( + 'fruit.variety', + array( + 'fruit' => $apple, + ) + ); + +Calling Methods +~~~~~~~~~~~~~~~ + +The ``.`` syntax can also be used to call methods on an object, similar to +JavaScript:: + + class Robot + { + public function sayHi($times) + { + $greetings = array(); + for ($i = 0; $i < $times; $i++) { + $greetings[] = 'Hi'; + } + + return implode(' ', $greetings).'!'; + } + } + + $robot = new Robot(); + + echo $language->evaluate( + 'robot.sayHi(3)', + array( + 'robot' => $robot, + ) + ); + +This will print "Hi Hi Hi!"; + +.. _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 = array('life' => 10, 'universe' => 10, 'everything' => 22); + + echo $language->evaluate( + 'data["life"] + data["universe"] + data["everything"]', + array( + 'data' => $data, + ) + ); + +This will print ``42``. + Supported Operators -~~~~~~~~~~~~~~~~~~~ +------------------- The component comes with a lot of operators: Arithmetic Operators -.................... +~~~~~~~~~~~~~~~~~~~~ * ``+`` (addition) * ``-`` (subtraction) @@ -35,20 +113,33 @@ Arithmetic Operators * ``%`` (modulus) * ``**`` (pow) +For example:: + + echo $language->evaluate( + 'life + universe + everything', + array( + 'life' => 10, + 'universe' => 10, + 'everything' => 22, + ) + ); + +This will print out ``42``. + Assignment Operators -.................... +~~~~~~~~~~~~~~~~~~~~ * ``=`` Bitwise Operators -................. +~~~~~~~~~~~~~~~~~ * ``&`` (and) * ``|`` (or) * ``^`` (xor) Comparison Operators -.................... +~~~~~~~~~~~~~~~~~~~~ * ``==`` (equal) * ``===`` (identical) @@ -67,31 +158,95 @@ Comparison Operators $language->evaluate('not "foo" matches "/bar/"'); // returns true +Examples:: + + $ret1 = $language->evaluate( + 'life == everything', + array( + 'life' => 10, + 'universe' => 10, + 'everything' => 22, + ) + ); + + $ret2 = $language->evaluate( + 'life > everything', + array( + 'life' => 10, + 'universe' => 10, + 'everything' => 22, + ) + ); + +These would both return ``false``. + Logical Operators -................. +~~~~~~~~~~~~~~~~~ * ``not`` or ``!`` * ``and`` or ``&&`` * ``or`` or ``||`` +For example:: + + $ret = $language->evaluate( + 'life < universe or life < everything', + array( + 'life' => 10, + 'universe' => 10, + 'everything' => 22, + ) + ); + +This would return ``true``. + String Operators -................ +~~~~~~~~~~~~~~~~ * ``~`` (concatenation) +For example:: + + $ret4 = $language->evaluate( + 'firstName~" "~lastName', + array( + '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'; + + $ret5 = $language->evaluate( + 'user.group in ["human_resources", "marketing"]', + array( + 'user' => $user + ) + ); + Numeric Operators -................. +~~~~~~~~~~~~~~~~~ * ``..`` (range) Ternary Operators -................. +~~~~~~~~~~~~~~~~~ * ``foo ? 'yes' : 'no'`` * ``foo ?: 'no'`` (equal to ``foo ? foo : 'no'``) From a14c39d530eb1ab4e520c49b3bf7ded8c3c9b07b Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 28 Nov 2013 11:16:51 -0600 Subject: [PATCH 080/146] [#3191] Many tweaks to expression language component thanks to @WouterJ, @xabbuh and @cordoval. Thanks guys! --- components/expression_language/introduction.rst | 16 ++++++++-------- components/expression_language/syntax.rst | 14 +++++++++----- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index da23a869e0f..7cdabf56bf1 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -10,22 +10,22 @@ The ExpressionLanguage Component (mostly, but not limited to, Booleans). .. versionadded:: 2.4 - The ExpressionLanguage component was added in Symfony 2.4. + The ExpressionLanguage component was introduced in Symfony 2.4. Installation ------------ You can install the component in 2 different ways: -* :doc:`Install it via Composer ` (``symfony/expression-language`` on `Packagist`_). -* Use the official Git repository (https://github.com/symfony/expression-language); +* :doc:`Install it via Composer ` (``symfony/expression-language`` on `Packagist`_); +* Use the official Git repository (https://github.com/symfony/expression-language). How can the Expression Engine Help Me? -------------------------------------- The purpose of the component is to allow users to use expressions inside -configuration for more complex logic. In the Symfony2 Framework, for example, -expressions can be used in security, for validation rules, and in route matching. +configuration for more complex logic. For some examples, the Symfony2 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*. @@ -52,15 +52,15 @@ Usage The ExpressionLanguage component can compile and evaluate expressions. Expressions are one-liners that often return a Boolean, which can be used -by the code executing the expression in an ``if`` statements. A simple example +by the code executing the expression in an ``if`` statement. A simple example of an expression is ``1 + 2``. You can also use more complicated expressions, such as ``someArray[3].someMethod('bar')``. The component provides 2 ways to work with expressions: +* **evaluation**: the expression is evaluated without being compiled to PHP; * **compile**: the expression is compiled to PHP, so it can be cached and - evaluated; -* **evaluation**: the expression is evaluated without being compiled to PHP. + evaluated. The main class of the component is :class:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage`:: diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index 4cc7da1192b..49a80d46082 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -49,6 +49,8 @@ to JavaScript:: ) ); +This will print ``Honeycrisp``; + Calling Methods ~~~~~~~~~~~~~~~ @@ -77,7 +79,7 @@ JavaScript:: ) ); -This will print "Hi Hi Hi!"; +This will print ``Hi Hi Hi!``. .. _component-expression-arrays: @@ -178,7 +180,7 @@ Examples:: ) ); -These would both return ``false``. +Both variables would be set to ``false``. Logical Operators ~~~~~~~~~~~~~~~~~ @@ -198,7 +200,7 @@ For example:: ) ); -This would return ``true``. +This ``$ret`` variable will be set to ``true``. String Operators ~~~~~~~~~~~~~~~~ @@ -207,7 +209,7 @@ String Operators For example:: - $ret4 = $language->evaluate( + echo $language->evaluate( 'firstName~" "~lastName', array( 'firstName' => 'Arthur', @@ -233,13 +235,15 @@ For example:: $user = new User(); $user->group = 'human_resources'; - $ret5 = $language->evaluate( + $inGroup = $language->evaluate( 'user.group in ["human_resources", "marketing"]', array( 'user' => $user ) ); +The ``$inGroup`` would evaluate to ``true``. + Numeric Operators ~~~~~~~~~~~~~~~~~ From cd98a63f8c830fceee35b8d28b049f8d571e5efd Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 28 Nov 2013 11:21:41 -0600 Subject: [PATCH 081/146] [#3191] Fixing semicolon thanks to @WouterJ --- components/expression_language/syntax.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index 49a80d46082..3552cad5b7d 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -49,7 +49,7 @@ to JavaScript:: ) ); -This will print ``Honeycrisp``; +This will print ``Honeycrisp``. Calling Methods ~~~~~~~~~~~~~~~ From aea65332045da444e3d39365952d5b02dc97cc5f Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sun, 17 Nov 2013 15:02:03 +0100 Subject: [PATCH 082/146] documentation for the regex based exclusion of 404 errors with MonologBundle --- cookbook/logging/index.rst | 3 +- .../logging/monolog_regex_based_excludes.rst | 67 +++++++++++++++++++ cookbook/map.rst.inc | 1 + 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 cookbook/logging/monolog_regex_based_excludes.rst diff --git a/cookbook/logging/index.rst b/cookbook/logging/index.rst index c10cfa54716..dda7d7cafdd 100644 --- a/cookbook/logging/index.rst +++ b/cookbook/logging/index.rst @@ -6,4 +6,5 @@ Logging monolog monolog_email - channels_handlers \ No newline at end of file + monolog_regex_based_excludes + channels_handlers diff --git a/cookbook/logging/monolog_regex_based_excludes.rst b/cookbook/logging/monolog_regex_based_excludes.rst new file mode 100644 index 00000000000..9d1b94060fa --- /dev/null +++ b/cookbook/logging/monolog_regex_based_excludes.rst @@ -0,0 +1,67 @@ +.. index:: + single: Logging + single: Logging; Exclude 404 Errors + single: Monolog; Exclude 404 Errors + +How to Configure Monolog to Exclude 404 Errors from the Log +=========================================================== + +Sometimes you get your logs flooded with unwanted 404 HTTP errors, for example, +when an attacker scans your app for some well-known application paths (e.g. +`/phpmyadmin`). When using a ``fingers_crossed`` handler, you can exclude +logging these 404 errors based on a regular expression in the MonologBundle +configuration: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + monolog: + handlers: + main: + # ... + type: fingers_crossed + handler: ... + excluded_404s: + - ^/phpmyadmin + + .. code-block:: xml + + + + + + + ^/phpmyadmin + + + + + .. code-block:: php + + // app/config/config.php + $container->loadFromExtension('monolog', array( + 'handlers' => array( + 'main' => array( + // ... + 'type' => 'fingers_crossed', + 'handler' => ..., + 'excluded_404s' => array( + '^/phpmyadmin', + ), + ), + ), + )); + +.. note:: + + To be able to use ``excluded_404s`` option you need to update your version + of the MonologBundle to 2.4. diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index 57c7f9b0a4d..76be17eced8 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -97,6 +97,7 @@ * :doc:`/cookbook/logging/monolog` * :doc:`/cookbook/logging/monolog_email` + * :doc:`/cookbook/logging/monolog_regex_based_excludes` * :doc:`/cookbook/logging/channels_handlers` * :doc:`/cookbook/profiler/index` From 6ec097d42664633457e3baf6c51c72c4fa78b555 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 28 Nov 2013 11:56:03 -0600 Subject: [PATCH 083/146] [#3203] Minor tweaks to new 404 logging entry --- cookbook/logging/monolog_regex_based_excludes.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cookbook/logging/monolog_regex_based_excludes.rst b/cookbook/logging/monolog_regex_based_excludes.rst index 9d1b94060fa..42424287d2a 100644 --- a/cookbook/logging/monolog_regex_based_excludes.rst +++ b/cookbook/logging/monolog_regex_based_excludes.rst @@ -6,7 +6,12 @@ How to Configure Monolog to Exclude 404 Errors from the Log =========================================================== -Sometimes you get your logs flooded with unwanted 404 HTTP errors, for example, +.. versionadded:: 2.4 + This feature was introduced to the MonologBundle in version 2.4, which + was first packaged with Symfony at version 2.4. However, the 2.4 version + of the MonologBundle is also compatible with Symfony 2.3. + +Sometimes your logs become flooded with unwanted 404 HTTP errors, for example, when an attacker scans your app for some well-known application paths (e.g. `/phpmyadmin`). When using a ``fingers_crossed`` handler, you can exclude logging these 404 errors based on a regular expression in the MonologBundle @@ -60,8 +65,3 @@ configuration: ), ), )); - -.. note:: - - To be able to use ``excluded_404s`` option you need to update your version - of the MonologBundle to 2.4. From 22b37762f40723846ace0f4b5fad579cac1cee0e Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 28 Nov 2013 12:13:23 -0600 Subject: [PATCH 084/146] [#3205] Tweaking versionadded --- cookbook/logging/channels_handlers.rst | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cookbook/logging/channels_handlers.rst b/cookbook/logging/channels_handlers.rst index 073f6f79ee2..817c062f313 100644 --- a/cookbook/logging/channels_handlers.rst +++ b/cookbook/logging/channels_handlers.rst @@ -93,9 +93,8 @@ Configure Additional Channels without Tagged Services ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2.3 - This feature was introduced to the MonologBundle in version 2.4. This - version is compatible with Symfony 2.3, but only MonologBundle 2.3 is - installed by default. To use this feature, upgrade your bundle manually. + This feature was introduced to the MonologBundle in version 2.4, which + was first packaged with Symfony at version 2.4. With MonologBundle 2.4 you can configure additional channels without the need to tag your services: From 4dba1ac9a7a60ac2830e5d9af71d72e6fcf9c6a0 Mon Sep 17 00:00:00 2001 From: Maks Rafalko Date: Fri, 22 Nov 2013 20:14:20 +0300 Subject: [PATCH 085/146] Changed parameter container to requestStack (2.4+) There is no need to pass @service_container to the voter, @request is enough. please see #3216 --- cookbook/security/voters.rst | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/cookbook/security/voters.rst b/cookbook/security/voters.rst index 344285a7e7d..0d4e526c742 100644 --- a/cookbook/security/voters.rst +++ b/cookbook/security/voters.rst @@ -61,19 +61,18 @@ and compare the IP address against a set of blacklisted IP addresses: // src/Acme/DemoBundle/Security/Authorization/Voter/ClientIpVoter.php namespace Acme\DemoBundle\Security\Authorization\Voter; - use Symfony\Component\DependencyInjection\ContainerInterface; + use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; class ClientIpVoter implements VoterInterface { - private $container; - + protected $requestStack; private $blacklistedIp; - - public function __construct(ContainerInterface $container, array $blacklistedIp = array()) + + public function __construct(RequestStack $requestStack, array $blacklistedIp = array()) { - $this->container = $container; + $this->requestStack = $requestStack; $this->blacklistedIp = $blacklistedIp; } @@ -91,7 +90,7 @@ and compare the IP address against a set of blacklisted IP addresses: public function vote(TokenInterface $token, $object, array $attributes) { - $request = $this->container->get('request'); + $request = $this->requestStack->getCurrentRequest(); if (in_array($request->getClientIp(), $this->blacklistedIp)) { return VoterInterface::ACCESS_DENIED; } @@ -128,7 +127,7 @@ and tag it as a ``security.voter``: services: security.access.blacklist_voter: class: Acme\DemoBundle\Security\Authorization\Voter\ClientIpVoter - arguments: ["@service_container", [123.123.123.123, 171.171.171.171]] + arguments: ["@request_stack", [123.123.123.123, 171.171.171.171]] public: false tags: - { name: security.voter } @@ -138,7 +137,7 @@ and tag it as a ``security.voter``: - + 123.123.123.123 171.171.171.171 @@ -155,7 +154,7 @@ and tag it as a ``security.voter``: $definition = new Definition( 'Acme\DemoBundle\Security\Authorization\Voter\ClientIpVoter', array( - new Reference('service_container'), + new Reference('request_stack'), array('123.123.123.123', '171.171.171.171'), ), ); From 77b84ea6d6724e8009717dbc3b87b47202ab48eb Mon Sep 17 00:00:00 2001 From: Peter Kokot Date: Thu, 28 Nov 2013 21:21:55 +0100 Subject: [PATCH 086/146] executable permission unset --- book/controller.rst | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 book/controller.rst diff --git a/book/controller.rst b/book/controller.rst old mode 100755 new mode 100644 From 0675b562edf1dc72bf0bab6752ab972a25e70096 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Fri, 29 Nov 2013 08:46:29 +0100 Subject: [PATCH 087/146] Removed assignment operator --- components/expression_language/syntax.rst | 5 ----- 1 file changed, 5 deletions(-) diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index 3552cad5b7d..972f16f65ab 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -128,11 +128,6 @@ For example:: This will print out ``42``. -Assignment Operators -~~~~~~~~~~~~~~~~~~~~ - -* ``=`` - Bitwise Operators ~~~~~~~~~~~~~~~~~ From e506f01321335bf6707889b2e0daf1633a025432 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Fri, 29 Nov 2013 08:49:07 +0100 Subject: [PATCH 088/146] Added example of range operator --- components/expression_language/syntax.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index 972f16f65ab..38e4739e0fa 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -244,6 +244,26 @@ Numeric Operators * ``..`` (range) +For example:: + + class User + { + public $age; + } + + $user = new User(); + $user->age = 34; + + $language->evaluate( + 'user.age in 18..45', + array( + 'user' => $user, + ) + ); + +This will evaluate to ``true``, because ``user.age`` is in the range from +``18`` till ``45`` + Ternary Operators ~~~~~~~~~~~~~~~~~ From 0725a8b95a5d9aa7ef38b074f5a16e2cfff74fbd Mon Sep 17 00:00:00 2001 From: Wouter J Date: Fri, 29 Nov 2013 14:19:43 +0100 Subject: [PATCH 089/146] Added docs for using functions --- components/expression_language/syntax.rst | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index 38e4739e0fa..5c4d756f107 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -81,6 +81,24 @@ JavaScript:: This will print ``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'); + + echo $language->evaluate( + 'constant("DB_USER")' + ); + +This will print ``root``. + .. _component-expression-arrays: Working with Arrays From 6e2e5836c483240a97b9db3364e4cdeea055d425 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Fri, 29 Nov 2013 14:20:46 +0100 Subject: [PATCH 090/146] Added article about custom functions --- components/expression_language/extending.rst | 87 ++++++++++++++++++++ components/expression_language/index.rst | 1 + components/expression_language/syntax.rst | 5 ++ components/map.rst.inc | 1 + 4 files changed, 94 insertions(+) create mode 100644 components/expression_language/extending.rst diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst new file mode 100644 index 00000000000..ddcc44d476f --- /dev/null +++ b/components/expression_language/extending.rst @@ -0,0 +1,87 @@ +.. index:: + single: Extending; ExpressionLanguage + +Extending the ExpressionLanguage +================================ + +The ExpressionLanguage can be extended by adding custom functions. For +instance, in the 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`". + +Register Functions +------------------ + +Functions will be registered on the current ``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. + +.. code-block:: php + + use Symfony\Component\ExpressionLanguage\ExpressionLanguage; + + $language = new ExpressionLanguage(); + $language->register('lowercase', function ($str) { + if (!is_string($str)) { + return $str; + } + + return sprintf('strtolower(%s)', $str); + }, function ($str) { + if (!is_string($str)) { + return $str; + } + + return strtolower($str); + }); + + echo $language->evaluate('lowercase("HELLO")'); + +This will print ``hello``. + +Creating a new ExpressionLanguage class +--------------------------------------- + +When you use the ``ExpressionLanguage`` class in your library, it's recommend +to create a new ``ExpressionLanguage`` class and register the functions there. +The class will execute ``registerFunctions`` to register the default +functions, you can override this to also add your own functions:: + + namespace Acme\AwesomeLib\ExpressionLanguage; + + use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage; + + class ExpressionLanguage extends BaseExpressionLanguage + { + protected function registerFunctions() + { + parent::registerFunctions(); // do not forget to also register core functions + + $this->register('lowercase', function ($str) { + if (!is_string($str)) { + return $str; + } + + return sprintf('strtolower(%s)', $str); + }, function ($str) { + if (!is_string($str)) { + return $str; + } + + return strtolower($str); + }); + } + } diff --git a/components/expression_language/index.rst b/components/expression_language/index.rst index e6eb657b4be..5ae40be979f 100644 --- a/components/expression_language/index.rst +++ b/components/expression_language/index.rst @@ -6,3 +6,4 @@ Expression Language introduction syntax + extending diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index 5c4d756f107..e105e82bdb8 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -99,6 +99,11 @@ constant:: This will print ``root``. +.. tip:: + + To read how to register your own function to use in an expression, see + ":doc:`/components/expression_language/extending`". + .. _component-expression-arrays: Working with Arrays diff --git a/components/map.rst.inc b/components/map.rst.inc index 5ec6d81f91e..2703a6057fc 100644 --- a/components/map.rst.inc +++ b/components/map.rst.inc @@ -61,6 +61,7 @@ * :doc:`/components/expression_language/introduction` * :doc:`/components/expression_language/syntax` + * :doc:`/components/expression_language/extending` * **Filesystem** From 4d50f34084ae8f4d775389a536d501530e2d2128 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 28 Nov 2013 14:03:53 -0600 Subject: [PATCH 091/146] [#3022] Adding service container expression language details --- .../_service_container_my_mailer.rst.inc | 34 +++++ book/service_container.rst | 131 +++++++++++++----- 2 files changed, 131 insertions(+), 34 deletions(-) create mode 100644 book/includes/_service_container_my_mailer.rst.inc diff --git a/book/includes/_service_container_my_mailer.rst.inc b/book/includes/_service_container_my_mailer.rst.inc new file mode 100644 index 00000000000..601d188a007 --- /dev/null +++ b/book/includes/_service_container_my_mailer.rst.inc @@ -0,0 +1,34 @@ +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + services: + my_mailer: + class: Acme\HelloBundle\Mailer + arguments: [sendmail] + + .. code-block:: xml + + + + + + + + sendmail + + + + + .. code-block:: php + + // app/config/config.php + use Symfony\Component\DependencyInjection\Definition; + + $container->setDefinition('my_mailer', new Definition( + 'Acme\HelloBundle\Mailer', + array('sendmail') + )); \ No newline at end of file diff --git a/book/service_container.rst b/book/service_container.rst index 84ef36c0c01..6f609e175c1 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -103,40 +103,7 @@ for you. In order for this to work, you must *teach* the container how to create the ``Mailer`` service. This is done via configuration, which can be specified in YAML, XML or PHP: -.. configuration-block:: - - .. code-block:: yaml - - # app/config/config.yml - services: - my_mailer: - class: Acme\HelloBundle\Mailer - arguments: [sendmail] - - .. code-block:: xml - - - - - - - - sendmail - - - - - .. code-block:: php - - // app/config/config.php - use Symfony\Component\DependencyInjection\Definition; - - $container->setDefinition('my_mailer', new Definition( - 'Acme\HelloBundle\Mailer', - array('sendmail') - )); +.. include includes/_service_container_my_mailer.rst.inc .. note:: @@ -660,6 +627,102 @@ service needs the ``my_mailer`` service in order to function. When you define this dependency in the service container, the container takes care of all the work of instantiating the classes. +Using the Expression Language +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The service container also supports an "expression" that allows you to inject +very specific values into a service. + +For example, suppose you have a third service (not shown here), called ``mailer_configuration``, +which has a ``getMailerMethod`` method on it, which will return a string +like ``sendmail`` based on some configuration. Remember that the first argument +to the ``my_mailer`` service is the simple string ``sendmail``: + +.. include includes/_service_container_my_mailer.rst.inc + +But instead of hardcoding this, how could we get this value from the ``getMailerMethod`` +of the new ``mailer_configuration`` service? One way is to use an expression: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + services: + my_mailer: + class: Acme\HelloBundle\Mailer + arguments: ["@=service('mailer_configuration').getMailerMethod()"] + + .. code-block:: xml + + + + + + + + service('mailer_configuration').getMailerMethod() + + + + + .. code-block:: php + + // app/config/config.php + use Symfony\Component\DependencyInjection\Definition; + + $container->setDefinition('my_mailer', new Definition( + 'Acme\HelloBundle\Mailer', + array(new Expression("service('mailer_configuration').getMailerMethod()")) + )); + +To learn more about the expression language syntax, see :doc:`/components/expression_language/syntax`. + +In this context, you have access to 2 functions: + +* ``service`` - returns a given service (see the example above); +* ``parameter`` - returns a specific parameter value (syntax is just like ``service``) + +You also have access to the :class:`Symfony\\Component\\DependencyInjection\\ContainerBuilder` +via a ``container`` variable. Here's another example: + +.. configuration-block:: + + .. code-block:: yaml + + services: + my_mailer: + class: Acme\HelloBundle\Mailer + arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"] + + .. code-block:: xml + + + + + + + @=container.hasParameter('some_param') ? parameter('some_param') : 'default_value' + + + + + .. code-block:: php + + use Symfony\Component\DependencyInjection\Definition; + + $container->setDefinition('my_mailer', new Definition( + 'Acme\HelloBundle\Mailer', + array(new Expression("@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'")) + )); + +Expressions can be used in ``parameters``, ``arguments``, ``properties``, +as arguments with ``configurator`` and as arguments to ``calls`` (method calls). + Optional Dependencies: Setter Injection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 22c940431fea57d7fafe4809c212638330175789 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Fri, 29 Nov 2013 16:42:34 -0500 Subject: [PATCH 092/146] [#3232][#3022] Making many small tweaks thanks to @WouterJ and @xabbuh --- .../_service_container_my_mailer.rst.inc | 4 ++- book/service_container.rst | 27 +++++++++++++------ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/book/includes/_service_container_my_mailer.rst.inc b/book/includes/_service_container_my_mailer.rst.inc index 601d188a007..efc2eaeac26 100644 --- a/book/includes/_service_container_my_mailer.rst.inc +++ b/book/includes/_service_container_my_mailer.rst.inc @@ -14,7 +14,9 @@ + xsi:schemaLocation="http://symfony.com/schema/dic/services + http://symfony.com/schema/dic/services/services-1.0.xsd" + > diff --git a/book/service_container.rst b/book/service_container.rst index 6f609e175c1..ff355e44f8a 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -630,17 +630,20 @@ the work of instantiating the classes. Using the Expression Language ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. versionadded:: 2.4 + The Expression Language functionality was introduced in Symfony 2.4. + The service container also supports an "expression" that allows you to inject very specific values into a service. For example, suppose you have a third service (not shown here), called ``mailer_configuration``, -which has a ``getMailerMethod`` method on it, which will return a string +which has a ``getMailerMethod()`` method on it, which will return a string like ``sendmail`` based on some configuration. Remember that the first argument to the ``my_mailer`` service is the simple string ``sendmail``: .. include includes/_service_container_my_mailer.rst.inc -But instead of hardcoding this, how could we get this value from the ``getMailerMethod`` +But instead of hardcoding this, how could we get this value from the ``getMailerMethod()`` of the new ``mailer_configuration`` service? One way is to use an expression: .. configuration-block:: @@ -659,7 +662,9 @@ of the new ``mailer_configuration`` service? One way is to use an expression: + xsi:schemaLocation="http://symfony.com/schema/dic/services + http://symfony.com/schema/dic/services/services-1.0.xsd" + > @@ -672,10 +677,11 @@ of the new ``mailer_configuration`` service? One way is to use an expression: // app/config/config.php use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\ExpressionLanguage\Expression; $container->setDefinition('my_mailer', new Definition( 'Acme\HelloBundle\Mailer', - array(new Expression("service('mailer_configuration').getMailerMethod()")) + array(new Expression('service("mailer_configuration").getMailerMethod()')) )); To learn more about the expression language syntax, see :doc:`/components/expression_language/syntax`. @@ -694,15 +700,17 @@ via a ``container`` variable. Here's another example: services: my_mailer: - class: Acme\HelloBundle\Mailer - arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"] + class: Acme\HelloBundle\Mailer + arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"] .. code-block:: xml + xsi:schemaLocation="http://symfony.com/schema/dic/services + http://symfony.com/schema/dic/services/services-1.0.xsd" + > @@ -714,10 +722,13 @@ via a ``container`` variable. Here's another example: .. code-block:: php use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\ExpressionLanguage\Expression; $container->setDefinition('my_mailer', new Definition( 'Acme\HelloBundle\Mailer', - array(new Expression("@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'")) + array(new Expression( + "@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'" + )) )); Expressions can be used in ``parameters``, ``arguments``, ``properties``, From 667d590d1492ccfad9ba3b2117d77bfcce4720b6 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Fri, 29 Nov 2013 16:56:02 -0500 Subject: [PATCH 093/146] [#3241] Minor tweaks to new expression language functions --- components/expression_language/extending.rst | 15 +++++++-------- components/expression_language/syntax.rst | 6 +++--- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst index ddcc44d476f..d3c8dbbd3d8 100644 --- a/components/expression_language/extending.rst +++ b/components/expression_language/extending.rst @@ -5,18 +5,18 @@ Extending the ExpressionLanguage ================================ The ExpressionLanguage can be extended by adding custom functions. For -instance, in the framework, the security has custom functions to check the -user's role. +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`". -Register Functions ------------------- +Registering Functions +--------------------- -Functions will be registered on the current ``ExpressionLanguage`` instance. +Functions are registered on each specific ``ExpressionLanguage`` instance. That means the functions can be used in any expression executed by that instance. @@ -52,13 +52,12 @@ This method has 3 arguments: This will print ``hello``. -Creating a new ExpressionLanguage class +Creating a new ExpressionLanguage Class --------------------------------------- When you use the ``ExpressionLanguage`` class in your library, it's recommend to create a new ``ExpressionLanguage`` class and register the functions there. -The class will execute ``registerFunctions`` to register the default -functions, you can override this to also add your own functions:: +Override ``registerFunctions`` to add your own functions:: namespace Acme\AwesomeLib\ExpressionLanguage; diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index e105e82bdb8..4a45f9fbe55 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -88,7 +88,7 @@ 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 +function by default: ``constant()``, which will return the value of the PHP constant:: define('DB_USER', 'root'); @@ -101,7 +101,7 @@ This will print ``root``. .. tip:: - To read how to register your own function to use in an expression, see + To read how to register your own functions to use in an expression, see ":doc:`/components/expression_language/extending`". .. _component-expression-arrays: @@ -285,7 +285,7 @@ For example:: ); This will evaluate to ``true``, because ``user.age`` is in the range from -``18`` till ``45`` +``18`` to ``45``. Ternary Operators ~~~~~~~~~~~~~~~~~ From 4738c754b7114a307518ce3da6668f44dbe256bd Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 1 Dec 2013 14:58:09 -0500 Subject: [PATCH 094/146] [#3232] Fixing note about expressions with parameters thanks to @WouterJ --- book/service_container.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/book/service_container.rst b/book/service_container.rst index ff355e44f8a..bc13aa13aa4 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -731,8 +731,8 @@ via a ``container`` variable. Here's another example: )) )); -Expressions can be used in ``parameters``, ``arguments``, ``properties``, -as arguments with ``configurator`` and as arguments to ``calls`` (method calls). +Expressions can be used in ``arguments``, ``properties``, as arguments with +``configurator`` and as arguments to ``calls`` (method calls). Optional Dependencies: Setter Injection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From ac15bf5c0a7678038f08eea45c8aa2a8fc989e1d Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 1 Dec 2013 15:27:58 -0500 Subject: [PATCH 095/146] [#3022] Adding framework documentation for routing expressions --- book/routing.rst | 98 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 94 insertions(+), 4 deletions(-) diff --git a/book/routing.rst b/book/routing.rst index 357a5c47301..9cb545796ca 100644 --- a/book/routing.rst +++ b/book/routing.rst @@ -507,10 +507,11 @@ to the ``{page}`` parameter. | /blog/my-blog-post | blog | {page} = my-blog-post | +--------------------+-------+-----------------------+ -The answer to the problem is to add route *requirements*. The routes in this -example would work perfectly if the ``/blog/{page}`` path *only* matched -URLs where the ``{page}`` portion is an integer. Fortunately, regular expression -requirements can easily be added for each parameter. For example: +The answer to the problem is to add route *requirements* or route *conditions* +(see :ref:`book-routing-conditions`). The routes in this example would work +perfectly if the ``/blog/{page}`` path *only* matched URLs where the ``{page}`` +portion is an integer. Fortunately, regular expression requirements can easily +be added for each parameter. For example: .. configuration-block:: @@ -717,6 +718,95 @@ You can also match on the HTTP *host* of the incoming request. For more information, see :doc:`/components/routing/hostname_pattern` in the Routing component documentation. +.. _book-routing-conditions: + +Completely Customized Route Matching with Conditions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 2.4 + Route conditions were introduced in Symfony 2.4. + +As you've seen, a route can be made to match only certain routing wildcards +(via regular expressions), HTTP methods, or host names. But the routing system +can be extended to almost an infinite flexibility with ``conditions``: + +.. configuration-block:: + + .. code-block:: yaml + + contact: + path: /contact + defaults: { _controller: AcmeDemoBundle:Main:contact } + condition: "context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i'" + + .. code-block:: xml + + + + + + AcmeDemoBundle:Main:contact + + + + .. code-block:: php + + use Symfony\Component\Routing\RouteCollection; + use Symfony\Component\Routing\Route; + + $collection = new RouteCollection(); + $collection->add('contact', new Route( + '/contact', array( + '_controller' => 'AcmeDemoBundle:Main:contact', + ), + array(), + array(), + '', + array(), + array(), + 'context.getMethod() in ["GET", "HEAD"] and request.headers.get("User-Agent") matches "/firefox/i"' + )); + + return $collection; + +The ``condition`` is an expression, and you can learn more about it syntax +here: :doc:`/components/expression_language/syntax`. With this, the route +won't match unless the HTTP method is either GET or HEAD *and* if the ``User-Agent`` +header matches ``firefox``. + +You can do any complex logic you need here by leveraging two variables that +are passed into the expression: + +* ``context``: An instance of :class:`Symfony\\Component\\Routing\\RequestContext`, + which holds the most fundamental information about the route being matched; +* ``request``: The Symfony :class:`Symfony\\Component\\HttpFoundation\\Request`` + object (see :ref:`component-http-foundation-request`). + +.. caution:: + + Conditions are *not* taken into account when generating a URL. + +.. sidebar:: Expressions are Compiled to PHP + + Behind the scenes, expressions are compiled down to raw PHP. Our example + would generate the following PHP in the cache directory:: + + if (rtrim($pathinfo, '/contact') === '' && ( + in_array($context->getMethod(), array(0 => "GET", 1 => "HEAD")) + && preg_match("/firefox/i", $request->headers->get("User-Agent")) + )) { + // ... + } + + Because of this, using the ``condition`` key causes no extra roverhead + beyond the time it takes for the underlying PHP to execute. + .. index:: single: Routing; Advanced example single: Routing; _format parameter From be86fef5e8457575239360e74fbb9fb8da27465c Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 1 Dec 2013 16:17:33 -0500 Subject: [PATCH 096/146] [#3022] Adding new Expression validation constraint --- .../expression_language/introduction.rst | 2 + reference/constraints.rst | 1 + reference/constraints/Expression.rst | 167 ++++++++++++++++++ reference/constraints/map.rst.inc | 1 + 4 files changed, 171 insertions(+) create mode 100644 reference/constraints/Expression.rst diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index 7cdabf56bf1..9ba2f5de9a0 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -32,6 +32,8 @@ component is a perfect candidate for the foundation of a *business rule engine*. The idea is to let the webmaster of a website configure things in a dynamic way without using PHP and without introducing security problems: +.. _component-expression-language-examples: + .. code-block:: text # Get the special price if diff --git a/reference/constraints.rst b/reference/constraints.rst index efbc0e554a6..0b209bbf012 100644 --- a/reference/constraints.rst +++ b/reference/constraints.rst @@ -53,6 +53,7 @@ Validation Constraints Reference constraints/Issn constraints/Callback + constraints/Expression constraints/All constraints/UserPassword constraints/Valid diff --git a/reference/constraints/Expression.rst b/reference/constraints/Expression.rst new file mode 100644 index 00000000000..812b21dbe73 --- /dev/null +++ b/reference/constraints/Expression.rst @@ -0,0 +1,167 @@ +Expression +========== + +.. versionadded:: 2.4 + The Expression constraint was introduced in Symfony 2.4. + +This constraint allows you to use an :ref:`expression ` +for more complex, dynamic validation. See `Basic Usage`_ for an example. +See :doc:`/reference/constraints/Callback` for a different constraint that +gives you similar flexibility. + ++----------------+-----------------------------------------------------------------------------------------------+ +| Applies to | :ref:`class ` or :ref:`property/method ` | ++----------------+-----------------------------------------------------------------------------------------------+ +| Options | - :ref:`expression ` | +| | - `message`_ | ++----------------+-----------------------------------------------------------------------------------------------+ +| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Expression` | ++----------------+-----------------------------------------------------------------------------------------------+ +| Validator | :class:`Symfony\\Component\\Validator\\Constraints\\ExpressionValidator` | ++----------------+-----------------------------------------------------------------------------------------------+ + +Basic Usage +----------- + +Imagine you have a class ``BlogPost`` with ``category`` and ``isTechnicalPost`` +properties:: + + namespace Acme\DemoBundle\Model; + + use Symfony\Component\Validator\Constraints as Assert; + + class BlogPost + { + private $category; + + private $isTechnicalPost; + + // ... + + public function getCategory() + { + return $this->category; + } + + public function setIsTechnicalPost($isTechnicalPost) + { + $this->isTechnicalPost = $isTechnicalPost; + } + + // ... + } + +To validate the object, you have some special requirements: + +* A) If ``isTechnicalPost`` is true, then ``category`` must be either ``php`` + or ``symfony``; + +* B) If ``isTechnicalPost`` is false, then ``category`` can be anything. + +One way to accomplish this is with the Expression constraint: + +.. configuration-block:: + + .. code-block:: yaml + + # src/Acme/DemoBundle/Resources/config/validation.yml + Acme\DemoBundle\Model\BlogPost: + constraints: + - Expression: + expression: "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()" + message: "If this is a tech post, the category should be php or symfony!" + + .. code-block:: php-annotations + + // src/Acme/DemoBundle/Model/BlogPost.php + namespace Acme\DemoBundle\Model\BlogPost; + + use Symfony\Component\Validator\Constraints as Assert; + + /** + * @Assert\Expression( + * "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()", + * message="If this is a tech post, the category should be php or symfony!" + * ) + */ + class BlogPost + { + // ... + } + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // src/Acme/DemoBundle/Model/BlogPost.php + namespace Acme\DemoBundle\Model\BlogPost; + + use Symfony\Component\Validator\Mapping\ClassMetadata; + use Symfony\Component\Validator\Constraints as Assert; + + class BlogPost + { + public static function loadValidatorMetadata(ClassMetadata $metadata) + { + $metadata->addConstraint(new Assert\Expression(array( + 'expression' => 'this.getCategory() in ["php", "symfony"] or !this.isTechnicalPost()', + 'message' => 'If this is a tech post, the category should be php or symfony!', + ))); + } + + // ... + } + +The :ref:`expression ` option is the +expression that must return true in order for validation to pass. To learn +more about the expression language syntax, see +:doc:`/components/expression_language/syntax`. + +For more information about the expression and what variables you have available +to you, see the :ref:`expression ` +option details below. + +Available Options +----------------- + +.. _reference-constraint-expression-option: + +expression +~~~~~~~~~~ + +**type**: ``string`` [:ref:`default option `] + +The expression that will be evaluated. If the expression evaluates to a false +value (using ``==``, not ``===``), validation will fail. + +To learn more about the expression language syntax, see +:doc:`/components/expression_language/syntax`. + +Inside of the expression, you have access to up to 2 variables: + +Depending on how you use the constraint, you have access to 1 or 2 variables +in your expression: + +* ``this``: The object being validated (e.g. an instance of BlogPost); +* ``value``: The value of the property being validated (only available when + the constraint is applied directly to a property); + +message +~~~~~~~ + +**type**: ``string`` **default**: ``This value is not valid.`` + +The default message supplied when the expression evaluates to false. diff --git a/reference/constraints/map.rst.inc b/reference/constraints/map.rst.inc index 84186b01d25..237329866d4 100644 --- a/reference/constraints/map.rst.inc +++ b/reference/constraints/map.rst.inc @@ -76,6 +76,7 @@ Other Constraints ~~~~~~~~~~~~~~~~~ * :doc:`Callback ` +* :doc:`Expression ` * :doc:`All ` * :doc:`UserPassword ` * :doc:`Valid ` From d72759a958fe048ff54d7f7a6f4df847bf515a84 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 1 Dec 2013 17:45:14 -0500 Subject: [PATCH 097/146] [#3022] Adding all of the security-related expression functionality docs --- book/security.rst | 164 +++++++++++++++++++++++++++++++++++ reference/twig_reference.rst | 6 ++ 2 files changed, 170 insertions(+) diff --git a/book/security.rst b/book/security.rst index 04f97dfcf95..6bc3203593b 100644 --- a/book/security.rst +++ b/book/security.rst @@ -864,6 +864,8 @@ options: (internally, an :class:`Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException` is thrown); +* ``allow_if`` If the expression returns false, then access is denied; + * ``requires_channel`` If the incoming request's channel (e.g. ``http``) does not match this value (e.g. ``https``), the user will be redirected (e.g. redirected from ``http`` to ``https``, or vice versa). @@ -951,6 +953,56 @@ address): * The second access rule is not examined as the first rule matched. +Securing by an Expression +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 2.4 + The ``allow_if`` functionality was introduced in Symfony 2.4. + +Once an ``access_control`` entry is matched, you can deny access via the +``roles`` key or use more complex logic with an expression in the ``allow_if`` +key: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/security.yml + security: + # ... + access_control: + - + path: ^/_internal/secure + allow_if: "'127.0.0.1' == request.getClientIp() or has_role('ROLE_ADMIN')" + + .. code-block:: xml + + + + + + .. code-block:: php + + 'access_control' => array( + array( + 'path' => '^/_internal/secure', + 'allow_if' => '"127.0.0.1" == request.getClientIp() or has_role("ROLE_ADMIN")', + ), + ), + +In this case, when the user tries to access any URL starting with ``/_internal/secure``, +she will only be granted access if the IP address is ``127.0.0.1`` or if +the user has the ``ROLE_ADMIN`` role. + +Inside the expression, you have access to a number of different variables +and functions including ``request``, which is the Symfony +:class:`Symfony\\Component\\HttpFoundation\\Request` object (see +:ref:`component-http-foundation-request`). + +For a list of the other functions and variables, see +:ref:`functions and variables `. + .. _book-security-securing-channel: Securing by Channel @@ -1656,6 +1708,8 @@ doesn't need to be defined anywhere - you can just start using it. Symfony2. If you define your own roles with a dedicated ``Role`` class (more advanced), don't use the ``ROLE_`` prefix. +.. _book-security-role-hierarchy: + Hierarchical Roles ~~~~~~~~~~~~~~~~~~ @@ -1834,6 +1888,31 @@ the built-in helper function: idea to have a main firewall that covers all URLs (as has been shown in this chapter). +.. _book-security-template-expression: + +.. versionadded:: 2.4 + The ``expression`` functionality was introduced in Symfony 2.4. + +You can also use expressions inside your templates: + +.. configuration-block:: + + .. code-block:: html+jinja + + {% if is_granted(expression('has_role("ROLE_ADMIN")')) %} + Delete + {% endif %} + + .. code-block:: html+php + + isGranted(new Expression( + 'has_role("ROLE_ADMIN")' + ))): ?> + Delete + + +For more details on expressions and security, see :ref:`book-security-expressions`. + Access Control in Controllers ----------------------------- @@ -1856,6 +1935,91 @@ method of the security context:: A firewall must be active or an exception will be thrown when the ``isGranted`` method is called. See the note above about templates for more details. +.. _book-security-expressions: + +Complex Access Controls with Expressions +---------------------------------------- + +.. versionadded:: 2.4 + The expression functionality was introduced in Symfony 2.4. + +In addition to a role like ``ROLE_ADMIN``, the ``isGranted`` method also +accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` object:: + + use Symfony\Component\Security\Core\Exception\AccessDeniedException; + use Symfony\Component\ExpressionLanguage\Expression; + // ... + + public function indexAction() + { + if (!$this->get('security.context')->isGranted(new Expression( + '"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())' + ))) { + throw new AccessDeniedException(); + } + + // ... + } + +In this example, if the current user has ``ROLE_ADMIN`` or if the current +user object's ``isSuperAdmin`` method returns ``true``, then access will +be granted (note: your User object may not have an ``isSuperAdmin`` method, +that method is invented for this example). This uses an expression and you +can learn more about the expression language syntax, see :doc:`/components/expression_language/syntax`. + +.. _book-security-expression-variables: + +Inside the expression, you have access to a number of variables: + +* ``user`` The user object (or the string ``anon`` if you're not authenticated); +* ``roles`` The array of roles the user has, including from the + :ref:`role hierarchy ` but not including + the ``IS_AUTHENTICATED_*`` attributes (see the functions below); +* ``object``: The object (if any) that's passed as the second argument to + ``isGranted`` ; +* ``token`` The token object; +* ``trust_resolver``: The :class:`Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationTrustResolverInterface`, + object: probably not useful directly. + +Additionally, you have access to a number of functions inside the expression. +**Note**: some of these functions *look* similar to the ``IS_AUTHENTICATED_*`` +attributes, but work differently. See the note below: + +* ``is_authenticated``: Returns true if the user is authenticated via "remember-me" + or authenticated "fully" - i.e. returns true if the user is "logged in"; +* ``is_anonymous``: Equal to using ``IS_AUTHENTICATED_ANONYMOUSLY`` with + the ``isGranted`` function; +* ``is_remember_me``: Similar, but not equal to ``IS_AUTHENTICATED_REMEMBERED``, + see below; +* ``is_fully_authenticated``: Similar, but not equal to ``IS_AUTHENTICATED_FULLY``, + see below; +* ``has_role``: Checks to see if the user has the given role - equivalent + to an expression like ``'ROLE_ADMIN' in roles``. + +.. sidebar:: ``is_remember_me`` is different than checking ``IS_AUTHENTICATED_REMEMBERED`` + + The ``is_remember_me`` and ``is_authenticated_fully`` functions are *similar* + to using ``IS_AUTHENTICATED_REMEMBERED`` and ``IS_AUTHENTICATED_FULLY`` + with the ``isGranted`` function - but they are **not** the same. The + following shows the difference:: + + use Symfony\Component\ExpressionLanguage\Expression; + // ... + + $sc = $this->get('security.context'); + $access1 = $sc->isGranted('IS_AUTHENTICATED_REMEMBERED'); + + $access2 = $sc->isGranted(new Expression( + 'is_remember_me() or is_fully_authenticated()' + )); + + Here, ``$access1`` and ``$access2`` will be the same value. Unlike the + behavior of ``IS_AUTHENTICATED_REMEMBERED`` and ``IS_AUTHENTICATED_FULLY``, + the ``is_remember_me`` function *only* returns true if the user is authenticated + via a remember me cookie and ``is_fully_authenticated`` *only* returns + true if the user has actually logged in during this session (i.e. is + full-fledged). + Impersonating a User -------------------- diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index 50e43658ece..09ced4ce114 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -21,6 +21,9 @@ Functions The ``render`` and ``controller`` functions are new in Symfony 2.2. Prior, the ``{% render %}`` tag was used and had a different signature. +.. versionadded:: 2.4 + The ``expression`` function was introduced in Symfony 2.4. + +----------------------------------------------------+--------------------------------------------------------------------------------------------+ | Function Syntax | Usage | +====================================================+============================================================================================+ @@ -89,6 +92,9 @@ Functions +----------------------------------------------------+--------------------------------------------------------------------------------------------+ | ``url(name, parameters = {})`` | Equal to ``path(...)`` but it generates an absolute URL | +----------------------------------------------------+--------------------------------------------------------------------------------------------+ +| ``expression(expression)`` | Creates an :class:Symfony\\Component\\ExpressionLanguage\\Expression in Twig. See | +| | ":ref:`Template Expressions `". | ++----------------------------------------------------+--------------------------------------------------------------------------------------------+ Filters ------- From 33676dca47c4a3aa44f7b78fb41e917c0b19f189 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 1 Dec 2013 17:55:35 -0500 Subject: [PATCH 098/146] [#3022] Adding a quick cookbook entry to highlight where the expression component is used in the framework --- book/security.rst | 2 ++ book/service_container.rst | 2 ++ .../expression_language/introduction.rst | 2 +- cookbook/expression/expressions.rst | 24 +++++++++++++++++++ cookbook/expression/index.rst | 7 ++++++ cookbook/index.rst | 1 + cookbook/map.rst.inc | 4 ++++ 7 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 cookbook/expression/expressions.rst create mode 100644 cookbook/expression/index.rst diff --git a/book/security.rst b/book/security.rst index 6bc3203593b..efe7f7a3b63 100644 --- a/book/security.rst +++ b/book/security.rst @@ -953,6 +953,8 @@ address): * The second access rule is not examined as the first rule matched. +.. _book-security-allow-if: + Securing by an Expression ~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/book/service_container.rst b/book/service_container.rst index bc13aa13aa4..3dc5698c853 100644 --- a/book/service_container.rst +++ b/book/service_container.rst @@ -627,6 +627,8 @@ service needs the ``my_mailer`` service in order to function. When you define this dependency in the service container, the container takes care of all the work of instantiating the classes. +.. _book-services-expressions: + Using the Expression Language ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index 9ba2f5de9a0..78fd8ae8a74 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -3,7 +3,7 @@ Single: Components; Expression Language The ExpressionLanguage Component -================================= +================================ The ExpressionLanguage component provides an engine that can compile and evaluate expressions. An expression is a one-liner that returns a value diff --git a/cookbook/expression/expressions.rst b/cookbook/expression/expressions.rst new file mode 100644 index 00000000000..71313a24951 --- /dev/null +++ b/cookbook/expression/expressions.rst @@ -0,0 +1,24 @@ +.. index:: + single: Expressions in the Framework + +How to use Expressions in Security, Routing, Services, and Validation +===================================================================== + +.. versionadded:: 2.4 + The expression functionality was introduced in Symfony 2.4. + +In Symfony 2.4, a powerful :doc:`ExpressionLanguage ` +component was added to Symfony. This allows us to add highly customized +logic inside configuration. + +The Symfony Framework leverages expressions out of the box in the following +ways: + +* :ref:`Configuring services `; +* :ref:`Route matching conditions `; +* :ref:`Checking security ` and + :ref:`access controls with allow_if `; +* :doc:`Validation `. + +For more information about how to create and work with expressions, see +:doc:`/components/expression_language/syntax`. \ No newline at end of file diff --git a/cookbook/expression/index.rst b/cookbook/expression/index.rst new file mode 100644 index 00000000000..909ecc72224 --- /dev/null +++ b/cookbook/expression/index.rst @@ -0,0 +1,7 @@ +Expressions +=========== + +.. toctree:: + :maxdepth: 2 + + expressions diff --git a/cookbook/index.rst b/cookbook/index.rst index 07869cad14a..428661bc374 100644 --- a/cookbook/index.rst +++ b/cookbook/index.rst @@ -15,6 +15,7 @@ The Cookbook doctrine/index email/index event_dispatcher/index + expression/index form/index logging/index profiler/index diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index 76be17eced8..b901380cfa5 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -78,6 +78,10 @@ * :doc:`/cookbook/event_dispatcher/method_behavior` * (service container) :doc:`/cookbook/service_container/event_listener` +* :doc:`/cookbook/expression/index` + + * :doc:`/cookbook/expression/expressions` + * :doc:`/cookbook/form/index` * :doc:`/cookbook/form/form_customization` From 0cf18287b2f861d27d09edf0d728c04a442a3c3c Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Sun, 1 Dec 2013 18:37:09 -0500 Subject: [PATCH 099/146] [#3022][#3258] Tweaks thanks to @cordoval --- book/routing.rst | 10 +++++----- book/security.rst | 4 ++-- cookbook/expression/expressions.rst | 2 +- reference/constraints/Expression.rst | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/book/routing.rst b/book/routing.rst index 9cb545796ca..a9dbe814863 100644 --- a/book/routing.rst +++ b/book/routing.rst @@ -728,7 +728,7 @@ Completely Customized Route Matching with Conditions As you've seen, a route can be made to match only certain routing wildcards (via regular expressions), HTTP methods, or host names. But the routing system -can be extended to almost an infinite flexibility with ``conditions``: +can be extended to have an almost infinite flexibility using ``conditions``: .. configuration-block:: @@ -775,13 +775,13 @@ can be extended to almost an infinite flexibility with ``conditions``: return $collection; -The ``condition`` is an expression, and you can learn more about it syntax +The ``condition`` is an expression, and you can learn more about its syntax here: :doc:`/components/expression_language/syntax`. With this, the route won't match unless the HTTP method is either GET or HEAD *and* if the ``User-Agent`` header matches ``firefox``. -You can do any complex logic you need here by leveraging two variables that -are passed into the expression: +You can do any complex logic you need in the expression by leveraging two +variables that are passed into the expression: * ``context``: An instance of :class:`Symfony\\Component\\Routing\\RequestContext`, which holds the most fundamental information about the route being matched; @@ -804,7 +804,7 @@ are passed into the expression: // ... } - Because of this, using the ``condition`` key causes no extra roverhead + Because of this, using the ``condition`` key causes no extra overhead beyond the time it takes for the underlying PHP to execute. .. index:: diff --git a/book/security.rst b/book/security.rst index efe7f7a3b63..0048b4ef423 100644 --- a/book/security.rst +++ b/book/security.rst @@ -1981,7 +1981,7 @@ Inside the expression, you have access to a number of variables: ``isGranted`` ; * ``token`` The token object; * ``trust_resolver``: The :class:`Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationTrustResolverInterface`, - object: probably not useful directly. + object: you'll probably use the ``is_*`` functions below instead. Additionally, you have access to a number of functions inside the expression. **Note**: some of these functions *look* similar to the ``IS_AUTHENTICATED_*`` @@ -2018,7 +2018,7 @@ attributes, but work differently. See the note below: Here, ``$access1`` and ``$access2`` will be the same value. Unlike the behavior of ``IS_AUTHENTICATED_REMEMBERED`` and ``IS_AUTHENTICATED_FULLY``, the ``is_remember_me`` function *only* returns true if the user is authenticated - via a remember me cookie and ``is_fully_authenticated`` *only* returns + via a remember-me cookie and ``is_fully_authenticated`` *only* returns true if the user has actually logged in during this session (i.e. is full-fledged). diff --git a/cookbook/expression/expressions.rst b/cookbook/expression/expressions.rst index 71313a24951..aba6431edfc 100644 --- a/cookbook/expression/expressions.rst +++ b/cookbook/expression/expressions.rst @@ -21,4 +21,4 @@ ways: * :doc:`Validation `. For more information about how to create and work with expressions, see -:doc:`/components/expression_language/syntax`. \ No newline at end of file +:doc:`/components/expression_language/syntax`. diff --git a/reference/constraints/Expression.rst b/reference/constraints/Expression.rst index 812b21dbe73..db6c726fd33 100644 --- a/reference/constraints/Expression.rst +++ b/reference/constraints/Expression.rst @@ -130,7 +130,7 @@ expression that must return true in order for validation to pass. To learn more about the expression language syntax, see :doc:`/components/expression_language/syntax`. -For more information about the expression and what variables you have available +For more information about the expression and what variables are available to you, see the :ref:`expression ` option details below. From bc22f16911167b05b1c56397e26f22b28b4cdd5e Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 2 Dec 2013 07:52:15 -0500 Subject: [PATCH 100/146] [#3022][#3258] Enhancing example at @ggam's suggestion --- book/security.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/book/security.rst b/book/security.rst index 0048b4ef423..da607eaada9 100644 --- a/book/security.rst +++ b/book/security.rst @@ -1901,14 +1901,16 @@ You can also use expressions inside your templates: .. code-block:: html+jinja - {% if is_granted(expression('has_role("ROLE_ADMIN")')) %} + {% if is_granted(expression( + '"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())' + )) %} Delete {% endif %} .. code-block:: html+php isGranted(new Expression( - 'has_role("ROLE_ADMIN")' + '"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())' ))): ?> Delete From 00002508843a5d05a54c0f92deb7ca2d60c90a34 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 2 Dec 2013 07:58:25 -0500 Subject: [PATCH 101/146] [#3258] A bunch of fixes thanks to @WouterJ --- book/security.rst | 16 ++++++++-------- reference/constraints/Expression.rst | 10 +++++----- reference/twig_reference.rst | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/book/security.rst b/book/security.rst index da607eaada9..974a0f88f9d 100644 --- a/book/security.rst +++ b/book/security.rst @@ -994,7 +994,7 @@ key: ), In this case, when the user tries to access any URL starting with ``/_internal/secure``, -she will only be granted access if the IP address is ``127.0.0.1`` or if +they will only be granted access if the IP address is ``127.0.0.1`` or if the user has the ``ROLE_ADMIN`` role. Inside the expression, you have access to a number of different variables @@ -1966,10 +1966,12 @@ accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` object:: } In this example, if the current user has ``ROLE_ADMIN`` or if the current -user object's ``isSuperAdmin`` method returns ``true``, then access will +user object's ``isSuperAdmin()`` method returns ``true``, then access will be granted (note: your User object may not have an ``isSuperAdmin`` method, -that method is invented for this example). This uses an expression and you -can learn more about the expression language syntax, see :doc:`/components/expression_language/syntax`. +that method is invented for this example). + +This uses an expression and you can learn more about the expression language +syntax, see :doc:`/components/expression_language/syntax`. .. _book-security-expression-variables: @@ -1985,11 +1987,9 @@ Inside the expression, you have access to a number of variables: * ``trust_resolver``: The :class:`Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationTrustResolverInterface`, object: you'll probably use the ``is_*`` functions below instead. -Additionally, you have access to a number of functions inside the expression. -**Note**: some of these functions *look* similar to the ``IS_AUTHENTICATED_*`` -attributes, but work differently. See the note below: +Additionally, you have access to a number of functions inside the expression: -* ``is_authenticated``: Returns true if the user is authenticated via "remember-me" +* ``is_authenticated``: Returns ``true`` if the user is authenticated via "remember-me" or authenticated "fully" - i.e. returns true if the user is "logged in"; * ``is_anonymous``: Equal to using ``IS_AUTHENTICATED_ANONYMOUSLY`` with the ``isGranted`` function; diff --git a/reference/constraints/Expression.rst b/reference/constraints/Expression.rst index db6c726fd33..430e53ecba1 100644 --- a/reference/constraints/Expression.rst +++ b/reference/constraints/Expression.rst @@ -69,7 +69,7 @@ One way to accomplish this is with the Expression constraint: constraints: - Expression: expression: "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()" - message: "If this is a tech post, the category should be php or symfony!" + message: "If this is a tech post, the category should be either php or symfony!" .. code-block:: php-annotations @@ -80,8 +80,8 @@ One way to accomplish this is with the Expression constraint: /** * @Assert\Expression( - * "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()", - * message="If this is a tech post, the category should be php or symfony!" + * "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()", + * message="If this is a tech post, the category should be either php or symfony!" * ) */ class BlogPost @@ -98,7 +98,7 @@ One way to accomplish this is with the Expression constraint: this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()
@@ -118,7 +118,7 @@ One way to accomplish this is with the Expression constraint: { $metadata->addConstraint(new Assert\Expression(array( 'expression' => 'this.getCategory() in ["php", "symfony"] or !this.isTechnicalPost()', - 'message' => 'If this is a tech post, the category should be php or symfony!', + 'message' => 'If this is a tech post, the category should be either php or symfony!', ))); } diff --git a/reference/twig_reference.rst b/reference/twig_reference.rst index 09ced4ce114..5724193f15a 100644 --- a/reference/twig_reference.rst +++ b/reference/twig_reference.rst @@ -92,7 +92,7 @@ Functions +----------------------------------------------------+--------------------------------------------------------------------------------------------+ | ``url(name, parameters = {})`` | Equal to ``path(...)`` but it generates an absolute URL | +----------------------------------------------------+--------------------------------------------------------------------------------------------+ -| ``expression(expression)`` | Creates an :class:Symfony\\Component\\ExpressionLanguage\\Expression in Twig. See | +| ``expression(expression)`` | Creates an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` in Twig. See | | | ":ref:`Template Expressions `". | +----------------------------------------------------+--------------------------------------------------------------------------------------------+ From a9e0e66dd5967788a3b5862022e0080a9b2bb300 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Mon, 2 Dec 2013 14:50:47 +0100 Subject: [PATCH 102/146] Added Caching article --- components/expression_language/caching.rst | 61 +++++++++++++++++++ components/expression_language/index.rst | 1 + .../expression_language/introduction.rst | 6 ++ components/map.rst.inc | 1 + 4 files changed, 69 insertions(+) create mode 100644 components/expression_language/caching.rst diff --git a/components/expression_language/caching.rst b/components/expression_language/caching.rst new file mode 100644 index 00000000000..44b0760612d --- /dev/null +++ b/components/expression_language/caching.rst @@ -0,0 +1,61 @@ +.. index:: + single: Caching; ExpressionLanguage + +Caching Expressions Using ParserCaches +====================================== + +The ExpressionLanguage component already provides a +:method:`Symfony\\Component\\ExpresionLanguage\\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 ``evaluate`` and ``compile`` needs to do some things before it 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'll return 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 +:class:`Symfony\\Component\\ExpressionLanguage\\ParserCache\\ParserCacheInterface` +instance (by default, it uses an +:class:`Symfony\\Component\\ExpressionLanguage\\ParserCache\\ArrayParserCache`). +You can customize this by creating a custom ``ParserCache`` and injecting this +in the object using the constructor:: + + use Symfony\Component\ExpressionLanguage\ExpressionLanguage; + use Acme\ExpressionLanguage\ParserCache\MyDatabaseParserCache; + + $cache = new MyDatabaseParserCache(...); + $language = new ExpressionLanguage($cache); + +Using Parsed and Serialized Expressions +--------------------------------------- + +Both ``evaluate`` and ``compile`` can handle ``ParsedExpression`` and +``SerializedParsedExpression``:: + + use Symfony\Component\ExpressionLanguage\ParsedExpression; + // ... + + $expression = new ParsedExpression($language->parse('1 + 4')); + + echo $language->evaluate($expression); // prints 5 + +.. code-block:: php + + use Symfony\Component\ExpressionLanguage\SerializedParsedExpression; + // ... + + $expression = new SerializedParsedExpression(serialize($language->parse('1 + 4'))); + + echo $language->evaluate($expression); // prints 5 diff --git a/components/expression_language/index.rst b/components/expression_language/index.rst index 5ae40be979f..aa63907d921 100644 --- a/components/expression_language/index.rst +++ b/components/expression_language/index.rst @@ -7,3 +7,4 @@ Expression Language introduction syntax extending + caching diff --git a/components/expression_language/introduction.rst b/components/expression_language/introduction.rst index 78fd8ae8a74..a53c8aa960d 100644 --- a/components/expression_language/introduction.rst +++ b/components/expression_language/introduction.rst @@ -109,4 +109,10 @@ PHP type (including objects):: This will print "Honeycrisp". For more information, see the :doc:`/components/expression_language/syntax` entry, especially :ref:`component-expression-objects` and :ref:`component-expression-arrays`. +Caching +------- + +The component provides some different caching strategies, read more about them +in :doc:`/components/expression_language/caching`. + .. _Packagist: https://packagist.org/packages/symfony/expression-language diff --git a/components/map.rst.inc b/components/map.rst.inc index 2703a6057fc..a5f2d0f8db7 100644 --- a/components/map.rst.inc +++ b/components/map.rst.inc @@ -62,6 +62,7 @@ * :doc:`/components/expression_language/introduction` * :doc:`/components/expression_language/syntax` * :doc:`/components/expression_language/extending` + * :doc:`/components/expression_language/caching` * **Filesystem** From d6b3a14363927d765809e9e1da56ed03064acd8c Mon Sep 17 00:00:00 2001 From: Zbigniew Czapran Date: Mon, 2 Dec 2013 16:54:16 +0100 Subject: [PATCH 103/146] [Cookbook] Fixes a link to the Request class --- book/routing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/routing.rst b/book/routing.rst index a9dbe814863..50473a337c6 100644 --- a/book/routing.rst +++ b/book/routing.rst @@ -785,7 +785,7 @@ variables that are passed into the expression: * ``context``: An instance of :class:`Symfony\\Component\\Routing\\RequestContext`, which holds the most fundamental information about the route being matched; -* ``request``: The Symfony :class:`Symfony\\Component\\HttpFoundation\\Request`` +* ``request``: The Symfony :class:`Symfony\\Component\\HttpFoundation\\Request` object (see :ref:`component-http-foundation-request`). .. caution:: From 0a59f6d4956ccbfe2b58326969c166cd1c14f6f8 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Mon, 2 Dec 2013 16:54:39 +0100 Subject: [PATCH 104/146] Added doctrine note --- components/expression_language/caching.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/components/expression_language/caching.rst b/components/expression_language/caching.rst index 44b0760612d..12953e66cb2 100644 --- a/components/expression_language/caching.rst +++ b/components/expression_language/caching.rst @@ -38,6 +38,12 @@ in the object using the constructor:: $cache = new MyDatabaseParserCache(...); $language = new ExpressionLanguage($cache); +.. note:: + + The `DoctrineBridge`_ has a ParserCache implementation using the + `doctrine cache library`_, which gives you caching for all sorts of cache + strategies, like Apc, Filesystem and Apc. + Using Parsed and Serialized Expressions --------------------------------------- @@ -59,3 +65,6 @@ Both ``evaluate`` and ``compile`` can handle ``ParsedExpression`` and $expression = new SerializedParsedExpression(serialize($language->parse('1 + 4'))); echo $language->evaluate($expression); // prints 5 + +.. _DoctrineBridge: https://github.com/symfony/DoctrineBridge +.. _`doctrine cache library`: http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/caching.html From be60602ac81e851e1e4b10b423c618a5a18aad2a Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 2 Dec 2013 19:09:21 -0500 Subject: [PATCH 105/146] [#3260] Minor tweaks when proofreading --- components/expression_language/caching.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/components/expression_language/caching.rst b/components/expression_language/caching.rst index 12953e66cb2..5adebc50d94 100644 --- a/components/expression_language/caching.rst +++ b/components/expression_language/caching.rst @@ -1,11 +1,11 @@ .. index:: single: Caching; ExpressionLanguage -Caching Expressions Using ParserCaches -====================================== +Caching Expressions Using Parser Caches +======================================= The ExpressionLanguage component already provides a -:method:`Symfony\\Component\\ExpresionLanguage\\ExpressionLanguage::compile` +: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. @@ -13,17 +13,17 @@ compiled/evaluated quicker. The Workflow ------------ -Both ``evaluate`` and ``compile`` needs to do some things before it can +Both ``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'll return a :class:`Symfony\\Component\\ExpressionLanguage\\ParsedExpression`. +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 +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 :class:`Symfony\\Component\\ExpressionLanguage\\ParserCache\\ParserCacheInterface` From a2ec22b2a83fc68f6e82cf21a1e71e38089197c8 Mon Sep 17 00:00:00 2001 From: Christoph Schmidt Date: Tue, 3 Dec 2013 15:51:17 +0100 Subject: [PATCH 106/146] Update Callback.rst add square brackets to yaml codeblock (constraints: - Callback: [validate]). Otherwise an error "Expected argument of type array, string given" is thrown --- reference/constraints/Callback.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index e59754f450a..e370c46ecf1 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -42,7 +42,7 @@ Configuration # src/Acme/BlogBundle/Resources/config/validation.yml Acme\BlogBundle\Entity\Author: constraints: - - Callback: validate + - Callback: [validate] .. code-block:: php-annotations From 1f385daa2c88b4975f7b761c740689712fe14982 Mon Sep 17 00:00:00 2001 From: Philipp Rieber Date: Wed, 4 Dec 2013 07:03:19 +0100 Subject: [PATCH 107/146] [Components][HttpKernel] Add FINISH_REQUEST to events table --- components/http_kernel/introduction.rst | 32 +++++++++++++------------ 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/components/http_kernel/introduction.rst b/components/http_kernel/introduction.rst index 33cf6f17cf3..92fe16307e6 100644 --- a/components/http_kernel/introduction.rst +++ b/components/http_kernel/introduction.rst @@ -569,21 +569,23 @@ each event has their own event object: .. _component-http-kernel-event-table: -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ -| **Name** | ``KernelEvents`` **Constant** | **Argument passed to the listener** | -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ -| kernel.request | ``KernelEvents::REQUEST`` | :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent` | -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ -| kernel.controller | ``KernelEvents::CONTROLLER`` | :class:`Symfony\\Component\\HttpKernel\\Event\\FilterControllerEvent` | -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ -| kernel.view | ``KernelEvents::VIEW`` | :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent` | -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ -| kernel.response | ``KernelEvents::RESPONSE`` | :class:`Symfony\\Component\\HttpKernel\\Event\\FilterResponseEvent` | -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ -| kernel.terminate | ``KernelEvents::TERMINATE`` | :class:`Symfony\\Component\\HttpKernel\\Event\\PostResponseEvent` | -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ -| kernel.exception | ``KernelEvents::EXCEPTION`` | :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForExceptionEvent` | -+-------------------+-------------------------------+-------------------------------------------------------------------------------------+ ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| **Name** | ``KernelEvents`` **Constant** | **Argument passed to the listener** | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| kernel.request | ``KernelEvents::REQUEST`` | :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent` | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| kernel.controller | ``KernelEvents::CONTROLLER`` | :class:`Symfony\\Component\\HttpKernel\\Event\\FilterControllerEvent` | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| kernel.view | ``KernelEvents::VIEW`` | :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent` | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| kernel.response | ``KernelEvents::RESPONSE`` | :class:`Symfony\\Component\\HttpKernel\\Event\\FilterResponseEvent` | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| kernel.finish_request | ``KernelEvents::FINISH_REQUEST`` | :class:`Symfony\\Component\\HttpKernel\\Event\\FinishRequestEvent` | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| kernel.terminate | ``KernelEvents::TERMINATE`` | :class:`Symfony\\Component\\HttpKernel\\Event\\PostResponseEvent` | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ +| kernel.exception | ``KernelEvents::EXCEPTION`` | :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForExceptionEvent` | ++-----------------------+----------------------------------+-------------------------------------------------------------------------------------+ .. _http-kernel-working-example: From 986e876fbe1caf233df02b8abf5cc2dd83a21e60 Mon Sep 17 00:00:00 2001 From: Julius Beckmann Date: Thu, 5 Dec 2013 20:28:04 +0100 Subject: [PATCH 108/146] Updated install page to v2.4.* --- book/installation.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/book/installation.rst b/book/installation.rst index d8097d0d505..265fb48582b 100644 --- a/book/installation.rst +++ b/book/installation.rst @@ -57,7 +57,7 @@ Distribution: .. code-block:: bash - $ php composer.phar create-project symfony/framework-standard-edition /path/to/webroot/Symfony 2.3.* + $ php composer.phar create-project symfony/framework-standard-edition /path/to/webroot/Symfony 2.4.* .. tip:: @@ -104,10 +104,10 @@ one of the following commands (replacing ``###`` with your actual filename): .. code-block:: bash # for .tgz file - $ tar zxvf Symfony_Standard_Vendors_2.3.###.tgz + $ tar zxvf Symfony_Standard_Vendors_2.4.###.tgz # for a .zip file - $ unzip Symfony_Standard_Vendors_2.3.###.zip + $ unzip Symfony_Standard_Vendors_2.4.###.zip If you've downloaded "without vendors", you'll definitely need to read the next section. From a7f2c9870866ee096a4d7426d1a8b0d700023fd5 Mon Sep 17 00:00:00 2001 From: pauliusmasiliunas Date: Sat, 7 Dec 2013 23:19:55 +0200 Subject: [PATCH 109/146] Change symfony version on composer.json --- book/from_flat_php_to_symfony2.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/from_flat_php_to_symfony2.rst b/book/from_flat_php_to_symfony2.rst index b3551b2efae..756bf91ac75 100644 --- a/book/from_flat_php_to_symfony2.rst +++ b/book/from_flat_php_to_symfony2.rst @@ -433,7 +433,7 @@ content: { "require": { - "symfony/symfony": "2.3.*" + "symfony/symfony": "2.4.*" }, "autoload": { "files": ["model.php","controllers.php"] From 7e1e4a22d66a9f51531687afd0c71004ccb254dd Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sun, 8 Dec 2013 14:09:58 +0100 Subject: [PATCH 110/146] some tweaks to the Expression Language cache chapter --- components/expression_language/caching.rst | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/components/expression_language/caching.rst b/components/expression_language/caching.rst index 5adebc50d94..41c9d2a1c26 100644 --- a/components/expression_language/caching.rst +++ b/components/expression_language/caching.rst @@ -13,14 +13,15 @@ compiled/evaluated quicker. The Workflow ------------ -Both ``evaluate`` and ``compile`` need to do some things before each can -provide the return values. For ``evaluate``, this overhead is even bigger. +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 +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 +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 @@ -40,14 +41,14 @@ in the object using the constructor:: .. note:: - The `DoctrineBridge`_ has a ParserCache implementation using the + The `DoctrineBridge`_ provides a Parser Cache implementation using the `doctrine cache library`_, which gives you caching for all sorts of cache - strategies, like Apc, Filesystem and Apc. + strategies, like Apc, Filesystem and Memcached. Using Parsed and Serialized Expressions --------------------------------------- -Both ``evaluate`` and ``compile`` can handle ``ParsedExpression`` and +Both ``evaluate()`` and ``compile()`` can handle ``ParsedExpression`` and ``SerializedParsedExpression``:: use Symfony\Component\ExpressionLanguage\ParsedExpression; From 7bf21c277f1d1487d7395a79b191b92fb0662b0b Mon Sep 17 00:00:00 2001 From: Dorthe Luebbert Date: Sat, 7 Dec 2013 14:48:21 +0100 Subject: [PATCH 111/146] changed create-project example with the current version of composer you can use wildcards like "2.3.*" :-) --- quick_tour/the_big_picture.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quick_tour/the_big_picture.rst b/quick_tour/the_big_picture.rst index 1ab6cea7eea..0d56e6cf381 100644 --- a/quick_tour/the_big_picture.rst +++ b/quick_tour/the_big_picture.rst @@ -66,7 +66,7 @@ have a ``Symfony/`` directory that looks like this: .. code-block:: bash - $ php composer.phar create-project symfony/framework-standard-edition Symfony 2.3.0 + $ php composer.phar create-project symfony/framework-standard-edition Symfony 2.3.* .. _`quick-tour-big-picture-built-in-server`: From 621296819d699c08cf7327506040a0b6d517a7ea Mon Sep 17 00:00:00 2001 From: Dorthe Luebbert Date: Sun, 8 Dec 2013 09:20:24 +0100 Subject: [PATCH 112/146] changed version in create project example to 2.4.* and remove the hint above as it is not longer necessary due to the new wildcard feature in composer --- quick_tour/the_big_picture.rst | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/quick_tour/the_big_picture.rst b/quick_tour/the_big_picture.rst index 0d56e6cf381..2305a55990e 100644 --- a/quick_tour/the_big_picture.rst +++ b/quick_tour/the_big_picture.rst @@ -61,12 +61,11 @@ have a ``Symfony/`` directory that looks like this: .. note:: If you are familiar with `Composer`_, you can download Composer and then - run the following command instead of downloading the archive (replacing - ``2.3.0`` with the latest Symfony release like ``2.3.1``): + run the following command instead of downloading the archive: .. code-block:: bash - $ php composer.phar create-project symfony/framework-standard-edition Symfony 2.3.* + $ php composer.phar create-project symfony/framework-standard-edition Symfony 2.4.* .. _`quick-tour-big-picture-built-in-server`: From 6e610bfe88819ca481f1fc88603a2ba5532574c7 Mon Sep 17 00:00:00 2001 From: William Durand Date: Thu, 12 Dec 2013 16:19:07 +0100 Subject: [PATCH 113/146] [Components] [ExpressionLanguage] Fix missing quote --- components/expression_language/extending.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst index d3c8dbbd3d8..0c92bc5fa83 100644 --- a/components/expression_language/extending.rst +++ b/components/expression_language/extending.rst @@ -21,7 +21,7 @@ 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``. +:method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::register`. This method has 3 arguments: * **name** - The name of the function in an expression; From a45464f578b1901abb09e5176594ea0cf4ade823 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Thu, 12 Dec 2013 14:18:56 +0000 Subject: [PATCH 114/146] Added missing argument to the evaluator function --- components/expression_language/extending.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst index d3c8dbbd3d8..d3b278c627b 100644 --- a/components/expression_language/extending.rst +++ b/components/expression_language/extending.rst @@ -40,7 +40,7 @@ This method has 3 arguments: } return sprintf('strtolower(%s)', $str); - }, function ($str) { + }, function ($arguments, $str) { if (!is_string($str)) { return $str; } @@ -75,7 +75,7 @@ Override ``registerFunctions`` to add your own functions:: } return sprintf('strtolower(%s)', $str); - }, function ($str) { + }, function ($arguments, $str) { if (!is_string($str)) { return $str; } From 2f486ce60aa1eb9466fe4527bd6c53a6e1343ded Mon Sep 17 00:00:00 2001 From: Mathieu Lemoine Date: Thu, 12 Dec 2013 14:18:43 -0500 Subject: [PATCH 115/146] [Security][Acl] Documentation for the new updateUserSecurityIdentity method in Dbal\MutableAclProvider --- cookbook/security/acl_advanced.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cookbook/security/acl_advanced.rst b/cookbook/security/acl_advanced.rst index 1bc217d8e6e..45d164aa29c 100644 --- a/cookbook/security/acl_advanced.rst +++ b/cookbook/security/acl_advanced.rst @@ -45,6 +45,13 @@ Security Identities This is analog to the object identity, but represents a user, or a role in your application. Each role, or user has its own security identity. +.. versionadded:: 2.5 + For users, the security identity is based on the username. This means that, + if for any reason, a user's username was to change, you must ensure its + security identity is updated too. The method ``updateUserSecurityIdentity`` + of the :class:`Symfony\\Component\\Security\\Acl\\Dbal\\MutableAclProvider` + class is there to handle the update. + Database Table Structure ------------------------ From 37deaa779402d85bc7df4b3d1a50a9949b7e88e0 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 19 Aug 2013 19:32:06 +0200 Subject: [PATCH 116/146] document the new authentication customization options --- cookbook/map.rst.inc | 1 + cookbook/security/custom_authenticator.rst | 208 +++++++++++++++++++++ cookbook/security/index.rst | 1 + 3 files changed, 210 insertions(+) create mode 100644 cookbook/security/custom_authenticator.rst diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index b901380cfa5..686620c99f7 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -135,6 +135,7 @@ * :doc:`/cookbook/security/form_login` * :doc:`/cookbook/security/securing_services` * :doc:`/cookbook/security/custom_provider` + * :doc:`/cookbook/security/custom_authenticator` * :doc:`/cookbook/security/custom_authentication_provider` * :doc:`/cookbook/security/target_path` diff --git a/cookbook/security/custom_authenticator.rst b/cookbook/security/custom_authenticator.rst new file mode 100644 index 00000000000..817952489e8 --- /dev/null +++ b/cookbook/security/custom_authenticator.rst @@ -0,0 +1,208 @@ +.. index:: + single: Security; Custom Authenticator + +How to create a custom Authenticator +==================================== + +Introduction +------------ + +Imagine you want to allow access to your website only between 2pm and 4pm (for +the UTC timezone). Before Symfony 2.4, you had to create a custom token, factory, +listener and provider. + +The Authenticator +----------------- + +Thanks to new simplified authentication customization options in Symfony 2.4, +you don't need to create a whole bunch of new classes, but use the +:class:`Symfony\\Component\\Security\\Core\\Authentication\\SimpleFormAuthenticatorInterface` +interface instead:: + + // src/Acme/HelloBundle/Security/TimeAuthenticator.php + namespace Acme\HelloBundle\Security; + + use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\Security\Core\Authentication\SimpleFormAuthenticatorInterface; + use Symfony\Component\Security\Core\Authentication\TokenInterface; + use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; + use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; + use Symfony\Component\Security\Core\Exception\AuthenticationException; + use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; + use Symfony\Component\Security\Core\User\UserProviderInterface; + + class TimeAuthenticator implements SimpleFormAuthenticatorInterface + { + private $encoderFactory; + + public function __construct(EncoderFactoryInterface $encoderFactory) + { + $this->encoderFactory = $encoderFactory; + } + + public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) + { + try { + $user = $userProvider->loadUserByUsername($token->getUsername()); + } catch (UsernameNotFoundException $e) { + throw new AuthenticationException('Invalid username or password'); + } + + $encoder = $this->encoderFactory->getEncoder($user); + $passwordValid = $encoder->isPasswordValid( + $user->getPassword(), + $token->getCredentials(), + $user->getSalt() + ); + + if ($passwordValid) { + $currentHour = date('G'); + if ($currentHour < 14 || $currentHour > 16) { + throw new AuthenticationException( + 'You can only log in between 2 and 4!', + 100 + ); + } + + return new UsernamePasswordToken( + $user->getUsername(), + $user->getPassword(), + $providerKey, + $user->getRoles() + ); + } + + throw new AuthenticationException('Invalid username or password'); + } + + public function supportsToken(TokenInterface $token, $providerKey) + { + return $token instanceof UsernamePasswordToken + && $token->getProviderKey() === $providerKey; + } + + public function createToken(Request $request, $username, $password, $providerKey) + { + return new UsernamePasswordToken($username, $password, $providerKey); + } + } + +.. versionadded:: 2.4 + The ``SimpleFormAuthenticatorInterface`` interface was added in Symfony 2.4. + +How it works +------------ + +There are a lot of things going on: + +* ``createToken()`` creates a Token that will be used to authenticate the user; +* ``authenticateToken()`` checks that the Token is allowed to log in by first + getting the User via the user provider and then, by checking the password + and the current time (a Token with roles is authenticated); +* ``supportsToken()`` is just a way to allow several authentication mechanisms to + be used for the same firewall (that way, you can for instance first try to + authenticate the user via a certificate or an API key and fall back to a + form login); +* An encoder is needed to check the user password's validity; this is a + service provided by default:: + + $encoder = $this->encoderFactory->getEncoder($user); + $passwordValid = $encoder->isPasswordValid( + $user->getPassword(), + $token->getCredentials(), + $user->getSalt() + ); + +Configuration +------------- + +Now, configure your ``TimeAuthenticator`` as a service: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + services: + time_authenticator: + class: Acme\HelloBundle\Security\TimeAuthenticator + arguments: [@security.encoder_factory] + + .. code-block:: xml + + + + + + + + + .. code-block:: php + + // app/config/config.php + use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\DependencyInjection\Reference; + + $container->setDefinition('time_authenticator', new Definition( + 'Acme\HelloBundle\Security\TimeAuthenticator', + array(new Reference('security.encoder_factory')) + )); + +Then, activate it in your ``firewalls`` section using the ``simple-form`` key +like this: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/security.yml + security: + # ... + + firewalls: + secured_area: + pattern: ^/admin + provider: authenticator + simple-form: + provider: ... + authenticator: time_authenticator + check_path: login_check + login_path: login + + .. code-block:: xml + + + + + + + + + + + + + .. code-block:: php + + // app/config/security.php + $container->loadFromExtension('security', array( + 'firewalls' => array( + 'secured_area' => array( + 'pattern' => '^/admin', + 'provider' => 'authenticator', + 'simple-form' => array( + 'provider' => ..., + 'authenticator' => 'time_authenticator', + 'check_path' => 'login_check', + 'login_path' => 'login', + ), + ), + ), + )); diff --git a/cookbook/security/index.rst b/cookbook/security/index.rst index a8edbdc4317..c61b279ff3c 100644 --- a/cookbook/security/index.rst +++ b/cookbook/security/index.rst @@ -13,5 +13,6 @@ Security form_login securing_services custom_provider + custom_authenticator custom_authentication_provider target_path From 1bd187fe17c599682da7b0547ed43ab7ddbc196a Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 19 Aug 2013 20:10:58 +0200 Subject: [PATCH 117/146] fixes thanks to @WouterJ --- cookbook/security/custom_authenticator.rst | 40 +++++++++++++--------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/cookbook/security/custom_authenticator.rst b/cookbook/security/custom_authenticator.rst index 817952489e8..de17f80d7d9 100644 --- a/cookbook/security/custom_authenticator.rst +++ b/cookbook/security/custom_authenticator.rst @@ -1,12 +1,9 @@ .. index:: single: Security; Custom Authenticator -How to create a custom Authenticator +How to create a Custom Authenticator ==================================== -Introduction ------------- - Imagine you want to allow access to your website only between 2pm and 4pm (for the UTC timezone). Before Symfony 2.4, you had to create a custom token, factory, listener and provider. @@ -14,8 +11,8 @@ listener and provider. The Authenticator ----------------- -Thanks to new simplified authentication customization options in Symfony 2.4, -you don't need to create a whole bunch of new classes, but use the +But now, thanks to new simplified authentication customization options in +Symfony 2.4, you don't need to create a whole bunch of new classes, but use the :class:`Symfony\\Component\\Security\\Core\\Authentication\\SimpleFormAuthenticatorInterface` interface instead:: @@ -90,7 +87,7 @@ interface instead:: .. versionadded:: 2.4 The ``SimpleFormAuthenticatorInterface`` interface was added in Symfony 2.4. -How it works +How it Works ------------ There are a lot of things going on: @@ -131,18 +128,26 @@ Now, configure your ``TimeAuthenticator`` as a service: .. code-block:: xml - - - - - + + + + + + + + .. code-block:: php // app/config/config.php use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; + + // ... $container->setDefinition('time_authenticator', new Definition( 'Acme\HelloBundle\Security\TimeAuthenticator', @@ -180,11 +185,12 @@ like this: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - - + + check-path="login_check" + login-path="login" /> From 8ddb26b36960ee35cf654ab61ae263eabbb76409 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Fri, 13 Sep 2013 14:09:41 +0200 Subject: [PATCH 118/146] clarify the authenticator type --- cookbook/map.rst.inc | 2 +- ....rst => custom_password_authenticator.rst} | 33 ++++++++++++------- cookbook/security/index.rst | 2 +- 3 files changed, 24 insertions(+), 13 deletions(-) rename cookbook/security/{custom_authenticator.rst => custom_password_authenticator.rst} (94%) diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index 686620c99f7..e876acec3d3 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -135,7 +135,7 @@ * :doc:`/cookbook/security/form_login` * :doc:`/cookbook/security/securing_services` * :doc:`/cookbook/security/custom_provider` - * :doc:`/cookbook/security/custom_authenticator` + * :doc:`/cookbook/security/custom_password_authenticator` * :doc:`/cookbook/security/custom_authentication_provider` * :doc:`/cookbook/security/target_path` diff --git a/cookbook/security/custom_authenticator.rst b/cookbook/security/custom_password_authenticator.rst similarity index 94% rename from cookbook/security/custom_authenticator.rst rename to cookbook/security/custom_password_authenticator.rst index de17f80d7d9..2560bd52223 100644 --- a/cookbook/security/custom_authenticator.rst +++ b/cookbook/security/custom_password_authenticator.rst @@ -1,15 +1,18 @@ .. index:: - single: Security; Custom Authenticator + single: Security; Custom Password Authenticator -How to create a Custom Authenticator -==================================== +How to create a Custom Password Authenticator +============================================= Imagine you want to allow access to your website only between 2pm and 4pm (for the UTC timezone). Before Symfony 2.4, you had to create a custom token, factory, listener and provider. -The Authenticator ------------------ +The Password Authenticator +-------------------------- + +.. versionadded:: 2.4 + The ``SimpleFormAuthenticatorInterface`` interface was added in Symfony 2.4. But now, thanks to new simplified authentication customization options in Symfony 2.4, you don't need to create a whole bunch of new classes, but use the @@ -84,9 +87,6 @@ interface instead:: } } -.. versionadded:: 2.4 - The ``SimpleFormAuthenticatorInterface`` interface was added in Symfony 2.4. - How it Works ------------ @@ -121,6 +121,8 @@ Now, configure your ``TimeAuthenticator`` as a service: # app/config/config.yml services: + # ... + time_authenticator: class: Acme\HelloBundle\Security\TimeAuthenticator arguments: [@security.encoder_factory] @@ -134,9 +136,12 @@ Now, configure your ``TimeAuthenticator`` as a service: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> + + - + class="Acme\HelloBundle\Security\TimeAuthenticator" + > + @@ -185,12 +190,15 @@ like this: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> + + + login-path="login" + /> @@ -198,6 +206,9 @@ like this: .. code-block:: php // app/config/security.php + + // .. + $container->loadFromExtension('security', array( 'firewalls' => array( 'secured_area' => array( diff --git a/cookbook/security/index.rst b/cookbook/security/index.rst index c61b279ff3c..6de91f12a88 100644 --- a/cookbook/security/index.rst +++ b/cookbook/security/index.rst @@ -13,6 +13,6 @@ Security form_login securing_services custom_provider - custom_authenticator + custom_password_authenticator custom_authentication_provider target_path From afdb708ded8d4ae88a3a00fbf464279bb0cb5c58 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Fri, 13 Sep 2013 17:37:15 +0200 Subject: [PATCH 119/146] add example on how to use the new SimplePreAuthenticatorInterface --- cookbook/map.rst.inc | 1 + cookbook/security/api_key_authentication.rst | 208 +++++++++++++++++++ cookbook/security/index.rst | 1 + 3 files changed, 210 insertions(+) create mode 100644 cookbook/security/api_key_authentication.rst diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index e876acec3d3..37d9c9dcf0a 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -136,6 +136,7 @@ * :doc:`/cookbook/security/securing_services` * :doc:`/cookbook/security/custom_provider` * :doc:`/cookbook/security/custom_password_authenticator` + * :doc:`/cookbook/security/api_key_authentication` * :doc:`/cookbook/security/custom_authentication_provider` * :doc:`/cookbook/security/target_path` diff --git a/cookbook/security/api_key_authentication.rst b/cookbook/security/api_key_authentication.rst new file mode 100644 index 00000000000..48aa3f0aa20 --- /dev/null +++ b/cookbook/security/api_key_authentication.rst @@ -0,0 +1,208 @@ +.. index:: + single: Security; Custom Request Authenticator + +How to Authenticate Users with API Keys +======================================= + +Nowadays, it's quite usual to authenticate the user via an API key (when developing +a web service for instance). The API key is provided for every request and is +passed as a query string parameter or via a HTTP header. + +The API Key Authenticator +------------------------- + +.. versionadded:: 2.4 + The ``SimplePreAuthenticatorInterface`` interface was added in Symfony 2.4. + +Authenticating a user based on the Request information should be done via a +pre-authentication mechanism. The :class:`Symfony\\Component\\Security\\Core\\Authentication\\SimplePreAuthenticatorInterface` +interface allows to implement such a scheme really easily:: + + // src/Acme/HelloBundle/Security/ApiKeyAuthenticator.php + namespace Acme\HelloBundle\Security; + + use Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface; + use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; + use Symfony\Component\Security\Core\Exception\AuthenticationException; + use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken; + use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\Security\Core\User\User; + use Symfony\Component\Security\Core\User\UserProviderInterface; + use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; + use Symfony\Component\Security\Core\Exception\BadCredentialsException; + + class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface + { + protected $userProvider; + + public function __construct(ApiKeyUserProviderInterface $userProvider) + { + $this->userProvider = $userProvider; + } + + public function createToken(Request $request, $providerKey) + { + if (!$request->query->has('apikey')) { + throw new BadCredentialsException('No API key found'); + } + + return new PreAuthenticatedToken( + 'anon.', + $request->query->get('apikey'), + $providerKey + ); + } + + public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) + { + $apikey = $token->getCredentials(); + if (!$this->userProvider->getUsernameForApiKey($apikey)) { + throw new AuthenticationException( + sprintf('API Key "%s" does not exist.', $apikey) + ); + } + + $user = new User( + $this->userProvider->getUsernameForApiKey($apikey), + $apikey, + array('ROLE_USER') + ); + + return new PreAuthenticatedToken( + $user, + $apikey, + $providerKey, + $user->getRoles() + ); + } + + public function supportsToken(TokenInterface $token, $providerKey) + { + return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey; + } + } + +``$userProvider`` can be any user provider implementing an interface similar to +this:: + + // src/Acme/HelloBundle/Security/ApiKeyUserProviderInterface.php + namespace Acme\HelloBundle\Security; + + use Symfony\Component\Security\Core\User\UserProviderInterface; + + interface ApiKeyUserProviderInterface extends UserProviderInterface + { + public function getUsernameForApiKey($apikey); + } + +.. note:: + + Read the dedicated article to learn + :doc:`how to create a custom user provider `. + +To access a resource protected by such an authenticator, you need to add an apikey +parameter to the query string, like in ``http://example.com/admin/foo?apikey=37b51d194a7513e45b56f6524f2d51f2``. + +Configuration +------------- + +Configure your ``ApiKeyAuthenticator`` as a service: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + services: + # ... + + apikey_authenticator: + class: Acme\HelloBundle\Security\ApiKeyAuthenticator + arguments: [@your_api_key_user_provider] + + .. code-block:: xml + + + + + + + + + + + + + + .. code-block:: php + + // app/config/config.php + use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\DependencyInjection\Reference; + + // ... + + $container->setDefinition('apikey_authenticator', new Definition( + 'Acme\HelloBundle\Security\ApiKeyAuthenticator', + array(new Reference('your_api_key_user_provider')) + )); + +Then, activate it in your firewalls section using the ``simple-preauth`` key +like this: + +.. configuration-block:: + + .. code-block:: yaml + + security: + firewalls: + secured_area: + pattern: ^/admin + simple-preauth: + provider: ... + authenticator: apikey_authenticator + + .. code-block:: xml + + + + + + + + + + + + + + .. code-block:: php + + // app/config/security.php + + // .. + + $container->loadFromExtension('security', array( + 'firewalls' => array( + 'secured_area' => array( + 'pattern' => '^/admin', + 'provider' => 'authenticator', + 'simple-preauth' => array( + 'provider' => ..., + 'authenticator' => 'apikey_authenticator', + ), + ), + ), + )); diff --git a/cookbook/security/index.rst b/cookbook/security/index.rst index 6de91f12a88..d0856f144cf 100644 --- a/cookbook/security/index.rst +++ b/cookbook/security/index.rst @@ -14,5 +14,6 @@ Security securing_services custom_provider custom_password_authenticator + api_key_authentication custom_authentication_provider target_path From a7b80a6bdb1a2a042d61a97d7b9c8adf0021590f Mon Sep 17 00:00:00 2001 From: Bilal Amarni Date: Tue, 17 Dec 2013 12:49:33 +0100 Subject: [PATCH 120/146] [Form] added multiple option to file type doc --- reference/forms/types/file.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/reference/forms/types/file.rst b/reference/forms/types/file.rst index a33dae8d992..03da93ffa78 100644 --- a/reference/forms/types/file.rst +++ b/reference/forms/types/file.rst @@ -9,6 +9,8 @@ The ``file`` type represents a file input in your form. +-------------+---------------------------------------------------------------------+ | Rendered as | ``input`` ``file`` field | +-------------+---------------------------------------------------------------------+ +| Options | - `multiple`_ | ++-------------+---------------------------------------------------------------------+ | Inherited | - `required`_ | | options | - `label`_ | | | - `read_only`_ | @@ -76,6 +78,16 @@ before using it directly. Read the :doc:`cookbook ` for an example of how to manage a file upload associated with a Doctrine entity. +Field Options +------------- + +multiple +~~~~~~~~ + +**type**: ``Boolean`` **default**: ``false`` + +When set to true, the user will be able to upload multiple files at the same time. + Inherited options ----------------- From bf98517e92118e97a53e96fbbd6ec5259cbabc1e Mon Sep 17 00:00:00 2001 From: Bilal Amarni Date: Tue, 17 Dec 2013 12:52:22 +0100 Subject: [PATCH 121/146] fixed spaces --- reference/forms/types/file.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference/forms/types/file.rst b/reference/forms/types/file.rst index 03da93ffa78..78d08fba3e4 100644 --- a/reference/forms/types/file.rst +++ b/reference/forms/types/file.rst @@ -9,7 +9,7 @@ The ``file`` type represents a file input in your form. +-------------+---------------------------------------------------------------------+ | Rendered as | ``input`` ``file`` field | +-------------+---------------------------------------------------------------------+ -| Options | - `multiple`_ | +| Options | - `multiple`_ | +-------------+---------------------------------------------------------------------+ | Inherited | - `required`_ | | options | - `label`_ | From 827014eea11d20931683d98968ce6bd659e44555 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Fri, 13 Sep 2013 21:42:44 +0100 Subject: [PATCH 122/146] Documented xml namespace autodiscovery. --- components/dom_crawler.rst | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index 61f28d37e95..65cdd93eb38 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -95,6 +95,52 @@ To remove a node the anonymous function must return false. All filter methods return a new :class:`Symfony\\Component\\DomCrawler\\Crawler` instance with filtered content. +Both :method:`Symfony\\Component\\DomCrawler\\Crawler::filterXPath` and +:method:`Symfony\\Component\\DomCrawler\\Crawler::filter` methods work with +XML namespaces, which are automatically registered. + +.. versionadded:: 2.4 + Auto discovery of namespaces was introduced in Symfony 2.4. + +Consider an XML below: + + + + tag:youtube.com,2008:video:kgZRZmEc9j4 + + + + Chordates - CrashCourse Biology #24 + widescreen + + + +It can be filtered with ``DomCrawler`` without a need to register namespace +aliases both with :method:`Symfony\\Component\\DomCrawler\\Crawler::filterXPath`:: + + $crawler = $crawler->filterXPath('//default:entry/media:group//yt:aspectRatio'); + +and :method:`Symfony\\Component\\DomCrawler\\Crawler::filter`:: + + use Symfony\Component\CssSelector\CssSelector; + + CssSelector::disableHtmlExtension(); + $crawler = $crawler->filter('default|entry media|group yt|aspectRatio'); + +.. note:: + + The default namespace is registered with a name "default". + +.. caution:: + + To query an XML with a CSS selector, the HTML extension needs to be disabled with + :method:`Symfony\\Component\\CssSelector\\CssSelector::disableHtmlExtension` + to avoid converting the selector to lowercase. + + Node Traversing ~~~~~~~~~~~~~~~ From 47bc7dc258189b55dd74f9618b14ab0d348ce7f2 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Wed, 18 Sep 2013 13:22:31 +0100 Subject: [PATCH 123/146] Documented changing of default namespace prefix. --- components/dom_crawler.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index 65cdd93eb38..17d4a8fc2b2 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -132,7 +132,9 @@ and :method:`Symfony\\Component\\DomCrawler\\Crawler::filter`:: .. note:: - The default namespace is registered with a name "default". + The default namespace is registered with a prefix "default". It can be + changed with the + :method:`Symfony\\Component\\DomCrawler\\Crawler::setDefaultNamespacePrefix`. .. caution:: From 68fa18e8fc53924e32fe77f28e02950ce28088cd Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Sun, 22 Sep 2013 23:41:41 +0100 Subject: [PATCH 124/146] Documented explicit namespace registration. --- components/dom_crawler.rst | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index 17d4a8fc2b2..0062a4bbd7c 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -97,10 +97,12 @@ To remove a node the anonymous function must return false. Both :method:`Symfony\\Component\\DomCrawler\\Crawler::filterXPath` and :method:`Symfony\\Component\\DomCrawler\\Crawler::filter` methods work with -XML namespaces, which are automatically registered. +XML namespaces, which can be either automatically discovered or registered +explicitly. .. versionadded:: 2.4 - Auto discovery of namespaces was introduced in Symfony 2.4. + Auto discovery and explicit registration of namespaces was introduced + in Symfony 2.4. Consider an XML below: @@ -136,13 +138,18 @@ and :method:`Symfony\\Component\\DomCrawler\\Crawler::filter`:: changed with the :method:`Symfony\\Component\\DomCrawler\\Crawler::setDefaultNamespacePrefix`. +Namespaces can be explicitly registered with the +:method:`Symfony\\Component\\DomCrawler\\Crawler::registerNamespace`:: + + $crawler->registerNamespace('m', 'http://search.yahoo.com/mrss/'); + $crawler = $crawler->filterXPath('//m:group//yt:aspectRatio'); + .. caution:: To query an XML with a CSS selector, the HTML extension needs to be disabled with :method:`Symfony\\Component\\CssSelector\\CssSelector::disableHtmlExtension` to avoid converting the selector to lowercase. - Node Traversing ~~~~~~~~~~~~~~~ From baec6deae76d311a0f41d2dde232c1bf5f8a4c72 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Mon, 16 Dec 2013 22:25:11 +0000 Subject: [PATCH 125/146] Added a note about removing the default namespace. --- components/dom_crawler.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index 0062a4bbd7c..af4cc3f93d0 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -138,6 +138,9 @@ and :method:`Symfony\\Component\\DomCrawler\\Crawler::filter`:: changed with the :method:`Symfony\\Component\\DomCrawler\\Crawler::setDefaultNamespacePrefix`. + The default namespace is removed when loading the content if it's the only + namespace in the document. It's done to simplify the xpath queries. + Namespaces can be explicitly registered with the :method:`Symfony\\Component\\DomCrawler\\Crawler::registerNamespace`:: From daf5d3c8776531cd7f60fe4078ab84eff16852e1 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 17 Dec 2013 11:29:48 -0600 Subject: [PATCH 126/146] [#2979] Minor tweaks --- components/dom_crawler.rst | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index af4cc3f93d0..568f0202417 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -95,7 +95,7 @@ To remove a node the anonymous function must return false. All filter methods return a new :class:`Symfony\\Component\\DomCrawler\\Crawler` instance with filtered content. -Both :method:`Symfony\\Component\\DomCrawler\\Crawler::filterXPath` and +Both the :method:`Symfony\\Component\\DomCrawler\\Crawler::filterXPath` and :method:`Symfony\\Component\\DomCrawler\\Crawler::filter` methods work with XML namespaces, which can be either automatically discovered or registered explicitly. @@ -104,7 +104,7 @@ explicitly. Auto discovery and explicit registration of namespaces was introduced in Symfony 2.4. -Consider an XML below: +Consider the XML below: -It can be filtered with ``DomCrawler`` without a need to register namespace +This can be filtered with the ``Crawler`` without needing to register namespace aliases both with :method:`Symfony\\Component\\DomCrawler\\Crawler::filterXPath`:: $crawler = $crawler->filterXPath('//default:entry/media:group//yt:aspectRatio'); @@ -136,21 +136,22 @@ and :method:`Symfony\\Component\\DomCrawler\\Crawler::filter`:: The default namespace is registered with a prefix "default". It can be changed with the - :method:`Symfony\\Component\\DomCrawler\\Crawler::setDefaultNamespacePrefix`. + :method:`Symfony\\Component\\DomCrawler\\Crawler::setDefaultNamespacePrefix` + method. The default namespace is removed when loading the content if it's the only namespace in the document. It's done to simplify the xpath queries. Namespaces can be explicitly registered with the -:method:`Symfony\\Component\\DomCrawler\\Crawler::registerNamespace`:: +:method:`Symfony\\Component\\DomCrawler\\Crawler::registerNamespace` method:: $crawler->registerNamespace('m', 'http://search.yahoo.com/mrss/'); $crawler = $crawler->filterXPath('//m:group//yt:aspectRatio'); .. caution:: - To query an XML with a CSS selector, the HTML extension needs to be disabled with - :method:`Symfony\\Component\\CssSelector\\CssSelector::disableHtmlExtension` + To query XML with a CSS selector, the HTML extension needs to be disabled with + :method:`CssSelector::disableHtmlExtension ` to avoid converting the selector to lowercase. Node Traversing From 14c538217b32d47833e02281c85c4c0d48fe5b8a Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sun, 15 Sep 2013 15:17:31 +0200 Subject: [PATCH 127/146] document how to restrict a firewall to a specific host --- cookbook/map.rst.inc | 1 + cookbook/security/host_restriction.rst | 62 ++++++++++++++++++++++++++ cookbook/security/index.rst | 1 + 3 files changed, 64 insertions(+) create mode 100644 cookbook/security/host_restriction.rst diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index 37d9c9dcf0a..92c7bdc8957 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -132,6 +132,7 @@ * :doc:`/cookbook/security/acl` * :doc:`/cookbook/security/acl_advanced` * :doc:`/cookbook/security/force_https` + * :doc:`/cookbook/security/host_restriction` * :doc:`/cookbook/security/form_login` * :doc:`/cookbook/security/securing_services` * :doc:`/cookbook/security/custom_provider` diff --git a/cookbook/security/host_restriction.rst b/cookbook/security/host_restriction.rst new file mode 100644 index 00000000000..fcb2960651b --- /dev/null +++ b/cookbook/security/host_restriction.rst @@ -0,0 +1,62 @@ +.. index:: + single: Security; Restrict Security Firewalls to a Host + +How to restrict Firewalls to a Specific Host +============================================ + +.. versionadded:: 2.4 + Support for restricting security firewalls to a specific host was added in + Symfony 2.4. + +When using the Security component, you can create firewalls that match certain +url patterns and thereby restrict access to all urls matching these patterns. +Additionally, you can restrict a firewall to a host using the ``host`` key: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/security.yml + + # ... + + security: + firewalls: + secured_area: + pattern: ^/ + host: admin\.example\.com + http_basic: true + + .. code-block:: xml + + + + + + + + + + + + + + .. code-block:: php + + // app/config/security.php + + // ... + + $container->loadFromExtension('security', array( + 'firewalls' => array( + 'secured_area' => array( + 'pattern' => '^/', + 'host' => 'admin.example.com', + 'http_basic' => true, + ), + ), + )); diff --git a/cookbook/security/index.rst b/cookbook/security/index.rst index d0856f144cf..e9cad89cb50 100644 --- a/cookbook/security/index.rst +++ b/cookbook/security/index.rst @@ -10,6 +10,7 @@ Security acl acl_advanced force_https + host_restriction form_login securing_services custom_provider From 0a9241d1756aba87382b6b325a06481824fe5461 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 17 Dec 2013 11:35:03 -0600 Subject: [PATCH 128/146] [#2953][#2986] Tweaks to firewall hostname Biggest change is to clarify that matching a firewall has no guarantee (is unrelated) to whether or not access is restricted. Also, fixed up some of the regex. --- cookbook/security/host_restriction.rst | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/cookbook/security/host_restriction.rst b/cookbook/security/host_restriction.rst index fcb2960651b..9ac7a294a8e 100644 --- a/cookbook/security/host_restriction.rst +++ b/cookbook/security/host_restriction.rst @@ -1,7 +1,7 @@ .. index:: single: Security; Restrict Security Firewalls to a Host -How to restrict Firewalls to a Specific Host +How to Restrict Firewalls to a Specific Host ============================================ .. versionadded:: 2.4 @@ -9,8 +9,9 @@ How to restrict Firewalls to a Specific Host Symfony 2.4. When using the Security component, you can create firewalls that match certain -url patterns and thereby restrict access to all urls matching these patterns. -Additionally, you can restrict a firewall to a host using the ``host`` key: +URL patterns and therefore are activated for all pages whose URL matches +that pattern. Additionally, you can restrict the initialization of a firewall +to a host using the ``host`` key: .. configuration-block:: @@ -24,7 +25,7 @@ Additionally, you can restrict a firewall to a host using the ``host`` key: firewalls: secured_area: pattern: ^/ - host: admin\.example\.com + host: ^admin\.example\.com$ http_basic: true .. code-block:: xml @@ -39,7 +40,7 @@ Additionally, you can restrict a firewall to a host using the ``host`` key: - + @@ -55,8 +56,15 @@ Additionally, you can restrict a firewall to a host using the ``host`` key: 'firewalls' => array( 'secured_area' => array( 'pattern' => '^/', - 'host' => 'admin.example.com', + 'host' => '^admin\.example\.com$', 'http_basic' => true, ), ), )); + +The ``host`` (like the ``path``) is a regular expression. In this example, +the firewall will only be activated if the host is equal exactly (due to +the ``^`` and ``$`` regex characters) to the hostname ``admin.example.com``. +If the hostname does not match this pattern, the firewall will not be activated +and subsequent firewalls will have the opportunity to be matched for this +request. From 77455c94b4b3884f88c79032bbcdf0e4e0bc0439 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 17 Dec 2013 16:29:26 -0600 Subject: [PATCH 129/146] [#2986] Fix thanks to @WouterJ --- cookbook/security/host_restriction.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cookbook/security/host_restriction.rst b/cookbook/security/host_restriction.rst index 9ac7a294a8e..232f1cd5ff6 100644 --- a/cookbook/security/host_restriction.rst +++ b/cookbook/security/host_restriction.rst @@ -62,7 +62,7 @@ to a host using the ``host`` key: ), )); -The ``host`` (like the ``path``) is a regular expression. In this example, +The ``host`` (like the ``pattern``) is a regular expression. In this example, the firewall will only be activated if the host is equal exactly (due to the ``^`` and ``$`` regex characters) to the hostname ``admin.example.com``. If the hostname does not match this pattern, the firewall will not be activated From d86e542abe3131edd1f2e2b88563b732ef84464d Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 19 Dec 2013 12:43:09 -0500 Subject: [PATCH 130/146] [#3315] Adding a little bit more information about the $arguments argument --- components/expression_language/extending.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst index d3b278c627b..8d52ba2bb59 100644 --- a/components/expression_language/extending.rst +++ b/components/expression_language/extending.rst @@ -50,7 +50,10 @@ This method has 3 arguments: echo $language->evaluate('lowercase("HELLO")'); -This will print ``hello``. +This will print ``hello``. Both the **compiler** and **evaluator** are passed +an ``arguments`` variable as their first argument, which is equal to the +second argument to ``evaluate()`` or ``compile()`` (e.g. the "values" when +evaluating or the "names" if compiling). Creating a new ExpressionLanguage Class --------------------------------------- From 2a10a46c9dc1709fd926d2d79490b365bbaf00df Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 23 Dec 2013 17:37:35 -0500 Subject: [PATCH 131/146] [#3319] Linking to the whole method --- cookbook/security/acl_advanced.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cookbook/security/acl_advanced.rst b/cookbook/security/acl_advanced.rst index 45d164aa29c..163760c1a80 100644 --- a/cookbook/security/acl_advanced.rst +++ b/cookbook/security/acl_advanced.rst @@ -48,9 +48,9 @@ your application. Each role, or user has its own security identity. .. versionadded:: 2.5 For users, the security identity is based on the username. This means that, if for any reason, a user's username was to change, you must ensure its - security identity is updated too. The method ``updateUserSecurityIdentity`` - of the :class:`Symfony\\Component\\Security\\Acl\\Dbal\\MutableAclProvider` - class is there to handle the update. + security identity is updated too. The + :method:`MutableAclProvider::updateUserSecurityIdentity ` + ``updateUserSecurityIdentity`` method is there to handle the update. Database Table Structure ------------------------ From 2cbca5f03c71f59792e6f43d39aad3c4d539964c Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 23 Dec 2013 17:44:18 -0500 Subject: [PATCH 132/146] Removing versionadded 2.1 from merge --- reference/forms/types/options/disabled.rst.inc | 3 --- 1 file changed, 3 deletions(-) diff --git a/reference/forms/types/options/disabled.rst.inc b/reference/forms/types/options/disabled.rst.inc index 89e8177a6e3..130b7d7f6b3 100644 --- a/reference/forms/types/options/disabled.rst.inc +++ b/reference/forms/types/options/disabled.rst.inc @@ -1,9 +1,6 @@ disabled ~~~~~~~~ -.. versionadded:: 2.1 - The ``disabled`` option is new in version 2.1 - **type**: ``boolean`` **default**: ``false`` If you don't want a user to modify the value of a field, you can set From 34551d2cd380d8cf32988bea0e6ed4000607884d Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Thu, 26 Dec 2013 10:34:20 -0500 Subject: [PATCH 133/146] [#3319] Fixing typos thanks to @xabbuh --- cookbook/security/acl_advanced.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cookbook/security/acl_advanced.rst b/cookbook/security/acl_advanced.rst index 163760c1a80..01228220bb6 100644 --- a/cookbook/security/acl_advanced.rst +++ b/cookbook/security/acl_advanced.rst @@ -49,8 +49,8 @@ your application. Each role, or user has its own security identity. For users, the security identity is based on the username. This means that, if for any reason, a user's username was to change, you must ensure its security identity is updated too. The - :method:`MutableAclProvider::updateUserSecurityIdentity ` - ``updateUserSecurityIdentity`` method is there to handle the update. + :method:`MutableAclProvider::updateUserSecurityIdentity() ` + method is there to handle the update. Database Table Structure ------------------------ From 4834b7739f1e1bda169f75f62d211e3ca665cfee Mon Sep 17 00:00:00 2001 From: Tom Van Looy Date: Sat, 14 Dec 2013 17:50:28 +0100 Subject: [PATCH 134/146] How to Configure Monolog to display Console messages --- components/console/introduction.rst | 8 ++ cookbook/logging/index.rst | 1 + cookbook/logging/monolog.rst | 4 +- cookbook/logging/monolog_console.rst | 176 +++++++++++++++++++++++++++ cookbook/map.rst.inc | 1 + reference/configuration/monolog.rst | 11 ++ 6 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 cookbook/logging/monolog_console.rst diff --git a/components/console/introduction.rst b/components/console/introduction.rst index 6af03289796..6f60f2e7512 100644 --- a/components/console/introduction.rst +++ b/components/console/introduction.rst @@ -160,6 +160,8 @@ You can also set these colors and options inside the tagname:: // bold text on a yellow background $output->writeln('foo'); +.. verbosity-levels: + Verbosity Levels ~~~~~~~~~~~~~~~~ @@ -226,6 +228,11 @@ When the quiet level is used, all output is suppressed as the default :method:`Symfony\Component\Console\Output::write ` method returns without actually printing. +.. tip:: + + You can use `MonologBundle`_ 2.4 to display messages on the console. This + is cleaner than wrapping your output calls in conditions (see :doc:/cookbook/logging/monolog_console). + Using Command Arguments ----------------------- @@ -520,3 +527,4 @@ Learn More! .. _Packagist: https://packagist.org/packages/symfony/console .. _ANSICON: https://github.com/adoxa/ansicon/downloads +.. _MonologBundle: https://github.com/symfony/MonologBundle diff --git a/cookbook/logging/index.rst b/cookbook/logging/index.rst index dda7d7cafdd..2570b3d5627 100644 --- a/cookbook/logging/index.rst +++ b/cookbook/logging/index.rst @@ -6,5 +6,6 @@ Logging monolog monolog_email + monolog_console monolog_regex_based_excludes channels_handlers diff --git a/cookbook/logging/monolog.rst b/cookbook/logging/monolog.rst index 32e064598e1..c2c6559dd75 100644 --- a/cookbook/logging/monolog.rst +++ b/cookbook/logging/monolog.rst @@ -23,8 +23,7 @@ your controller:: } The ``logger`` service has different methods for different logging levels. -See :class:`Symfony\\Component\\HttpKernel\\Log\\LoggerInterface` for details -on which methods are available. +See LoggerInterface_ for details on which methods are available. Handlers and Channels: Writing logs to different Locations ---------------------------------------------------------- @@ -351,3 +350,4 @@ using a processor. handler level instead of globally. .. _Monolog: https://github.com/Seldaek/monolog +.. _LoggerInterface: https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php diff --git a/cookbook/logging/monolog_console.rst b/cookbook/logging/monolog_console.rst new file mode 100644 index 00000000000..358bd5bee2a --- /dev/null +++ b/cookbook/logging/monolog_console.rst @@ -0,0 +1,176 @@ +.. index:: + single: Logging; Console messages + +How to Configure Monolog to Display Console Messages +==================================================== + +It is possible to use the console to print messages for a certain :ref:`verbosity-levels` +using the :class:`Symfony\\Component\\Console\\Output\\OutputInterface` +instance that is passed when a command gets executed. + +When a lot of logging has to happen, it's cumbersome to print information +depending on the verbosity settings (``-v``, ``-vv``, ``-vvv``) because the +calls need to be wrapped in conditions. The code quickly gets verbose or dirty. +For example:: + + use Symfony\Component\Console\Input\InputInterface; + use Symfony\Component\Console\Output\OutputInterface; + + protected function execute(InputInterface $input, OutputInterface $output) + { + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { + $output->writeln('Some info'); + } + + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { + $output->writeln('Some more info'); + } + } + +Instead of using these semantic methods to test for each of the verbosity +levels, `MonologBundle`_ 2.4 provides a `ConsoleHandler`_ that listens to +console events and writes log messages to the console output depending on the +current log level and the console verbosity. + +The example above could then be rewritten as:: + + use Symfony\Component\Console\Input\InputInterface; + use Symfony\Component\Console\Output\OutputInterface; + + protected function execute(InputInterface $input, OutputInterface $output) + { + $logger->debug('Some info'); + + $logger->notice('Some more info'); + } + +These messages will get displayed on the console, timestamped, colored +depending on the log level and error logs are written to the error output +(php://stderr). There is no need to conditionally handle the verbosity +settings anymore. + +The Monolog console handler is enabled in the Monolog configuration. This is +the default in Symfony Standard Edition 2.4 too. + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + monolog: + handlers: + console: + type: console + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // app/config/config.php + $container->loadFromExtension('monolog', array( + 'handlers' => array( + 'console' => array( + 'type' => 'console', + ), + ), + )); + +With the ``verbosity_levels`` option you can adapt the mapping between +verbosity and log level. In the given example it will also show notices in +normal verbosity mode (instead of warnings only). Additionally, it will only +use messages logged with the custom ``my_channel`` channel and it changes the +display style via a custom formatter. See also the :doc:`reference/configuration/monolog` +for more information: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/config.yml + monolog: + handlers: + console: + type: console + verbosity_levels: + VERBOSITY_NORMAL: NOTICE + channels: my_channel + formatter: my_formatter + + .. code-block:: xml + + + + + + + + + my_channel + + + + + .. code-block:: php + + // app/config/config.php + $container->loadFromExtension('monolog', array( + 'handlers' => array( + 'console' => array( + 'type' => 'console', + 'verbosity_levels' => array( + 'VERBOSITY_NORMAL' => 'NOTICE', + ), + 'channels' => 'my_channel', + 'formatter' => 'my_formatter', + ), + ), + )); + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/services.yml + services: + my_formatter: + class: Symfony\Bridge\Monolog\Formatter\ConsoleFormatter + arguments: + - "[%%datetime%%] %%start_tag%%%%message%%%%end_tag%% (%%level_name%%) %%context%% %%extra%%\n" + + .. code-block:: xml + + + + + + + + [%%datetime%%] %%start_tag%%%%message%%%%end_tag%% (%%level_name%%) %%context%% %%extra%%\n + + + + + + .. code-block:: php + + // app/config/services.php + $container + ->register('my_formatter', 'Symfony\Bridge\Monolog\Formatter\ConsoleFormatter') + ->addArgument('[%%datetime%%] %%start_tag%%%%message%%%%end_tag%% (%%level_name%%) %%context%% %%extra%%\n') + ; + +.. _ConsoleHandler: https://github.com/symfony/MonologBridge/blob/master/Handler/ConsoleHandler.php +.. _MonologBundle: https://github.com/symfony/MonologBundle diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index b612238e7ac..64590e38e1d 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -101,6 +101,7 @@ * :doc:`/cookbook/logging/monolog` * :doc:`/cookbook/logging/monolog_email` + * :doc:`/cookbook/logging/monolog_console` * :doc:`/cookbook/logging/monolog_regex_based_excludes` * :doc:`/cookbook/logging/channels_handlers` diff --git a/reference/configuration/monolog.rst b/reference/configuration/monolog.rst index 24365fbd682..1b09cbc020c 100644 --- a/reference/configuration/monolog.rst +++ b/reference/configuration/monolog.rst @@ -25,6 +25,13 @@ MonologBundle Configuration ("monolog") action_level: WARNING buffer_size: 30 handler: custom + console: + type: console + verbosity_levels: + VERBOSITY_NORMAL: WARNING + VERBOSITY_VERBOSE: NOTICE + VERBOSITY_VERY_VERBOSE: INFO + VERBOSITY_DEBUG: DEBUG custom: type: service id: my_handler @@ -84,6 +91,10 @@ MonologBundle Configuration ("monolog") action-level="warning" handler="custom" /> + Date: Thu, 26 Dec 2013 12:56:01 -0500 Subject: [PATCH 135/146] [#3340] Tweaks to console logging: * Tweaked language in the components section to be more useful for component people * Added versionadded * Tweaked description of how this feature works --- components/console/introduction.rst | 7 ++++--- cookbook/logging/monolog_console.rst | 17 ++++++++++++----- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/components/console/introduction.rst b/components/console/introduction.rst index 6f60f2e7512..ea60102dcd6 100644 --- a/components/console/introduction.rst +++ b/components/console/introduction.rst @@ -230,8 +230,10 @@ method returns without actually printing. .. tip:: - You can use `MonologBundle`_ 2.4 to display messages on the console. This - is cleaner than wrapping your output calls in conditions (see :doc:/cookbook/logging/monolog_console). + The MonologBridge provides a :class:`Symfony\\Bridge\\Monolog\\Handler\\ConsoleHandler` + class that allows you to display messages on the console. This is cleaner + than wrapping your output calls in conditions. For an example use in + the Symfony Framework, see :doc:/cookbook/logging/monolog_console. Using Command Arguments ----------------------- @@ -527,4 +529,3 @@ Learn More! .. _Packagist: https://packagist.org/packages/symfony/console .. _ANSICON: https://github.com/adoxa/ansicon/downloads -.. _MonologBundle: https://github.com/symfony/MonologBundle diff --git a/cookbook/logging/monolog_console.rst b/cookbook/logging/monolog_console.rst index 358bd5bee2a..3a22b7dcfbc 100644 --- a/cookbook/logging/monolog_console.rst +++ b/cookbook/logging/monolog_console.rst @@ -4,7 +4,11 @@ How to Configure Monolog to Display Console Messages ==================================================== -It is possible to use the console to print messages for a certain :ref:`verbosity-levels` +.. versionadded:: 2.3 + This feature was introduced to the MonologBundle in version 2.4, which + was first packaged with Symfony at version 2.4 (but compatible with Symfony 2.3). + +It is possible to use the console to print messages for certain :ref:`verbosity-levels` using the :class:`Symfony\\Component\\Console\\Output\\OutputInterface` instance that is passed when a command gets executed. @@ -39,15 +43,18 @@ The example above could then be rewritten as:: protected function execute(InputInterface $input, OutputInterface $output) { + // assuming the Command extends ContainerAwareCommand... + $logger = $this->getContainer()->get('logger'); $logger->debug('Some info'); $logger->notice('Some more info'); } -These messages will get displayed on the console, timestamped, colored -depending on the log level and error logs are written to the error output -(php://stderr). There is no need to conditionally handle the verbosity -settings anymore. +Depending on the verbosity level that the command is run in and the user's +configuration (see below), these messages may or may not be displayed to +the console. If they are displayed, they are timestamped and colored appropriately. +Additionally, error logs are written to the error output (php://stderr). +There is no need to conditionally handle the verbosity settings anymore. The Monolog console handler is enabled in the Monolog configuration. This is the default in Symfony Standard Edition 2.4 too. From 4ef1a714acc1cb516c8624be714b77744d8f84e7 Mon Sep 17 00:00:00 2001 From: yanickj Date: Tue, 17 Dec 2013 12:04:48 -0500 Subject: [PATCH 136/146] Synchronized setter injection occurs on Container::set() not on Container::enterScope() --- cookbook/service_container/scopes.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 8f6fd9fd34d..663636fded3 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -134,6 +134,7 @@ marked as ``synchronized``: class: Acme\HelloBundle\Client\ClientConfiguration scope: client synchronized: true + synthetic: true # ... .. code-block:: xml @@ -151,6 +152,7 @@ marked as ``synchronized``: id="client_configuration" scope="client" synchronized="true" + synthetic="true" class="Acme\HelloBundle\Client\ClientConfiguration" /> @@ -196,9 +198,9 @@ and everything works without any special code in your service or in your definit } } -Whenever the ``client`` scope is entered or left, the service container will -automatically call the ``setClientConfiguration()`` method with the current -``client_configuration`` instance. +Whenever the ``client`` scope is active, the service container will +automatically call the ``setClientConfiguration()`` method when the +``client_configuration`` service is set in the container. You might have noticed that the ``setClientConfiguration()`` method accepts ``null`` as a valid value for the ``client_configuration`` argument. That's From 0dfffffe38eea592a5bef4fccf59c0915386ae0b Mon Sep 17 00:00:00 2001 From: yanickj Date: Tue, 17 Dec 2013 13:30:59 -0500 Subject: [PATCH 137/146] Update PHP example to include synthetic attribute. --- cookbook/service_container/scopes.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 663636fded3..59d4cd425a4 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -169,6 +169,7 @@ marked as ``synchronized``: ); $definition->setScope('client'); $definition->setSynchronized(true); + $definition->setSynthetic(true); $container->setDefinition('client_configuration', $definition); Now, if you inject this service using setter injection, there are no drawbacks From f76369e5b0e581c1ca875aca6bb44e430bd59042 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 11:12:54 +0100 Subject: [PATCH 138/146] Removed duplicated DQL documentation The doctrine docs already has a big great documentation on this. There is no reason to duplicate it in the sf docs. This commit removes everything except a simple example. It also moves the sentence about the return result above, since that makes more sense now the getSingleResult example is removed. --- book/doctrine.rst | 55 ++++------------------------------------------- 1 file changed, 4 insertions(+), 51 deletions(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index 026a3b4f977..d2b9387611e 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -728,65 +728,18 @@ a controller, do the following:: $products = $query->getResult(); +The ``getResult()`` method returns an array of results. + If you're comfortable with SQL, then DQL should feel very natural. The biggest difference is that you need to think in terms of "objects" instead of rows -in a database. For this reason, you select *from* ``AcmeStoreBundle:Product`` -and then alias it as ``p``. - -The ``getResult()`` method returns an array of results. If you're querying -for just one object, you can use the ``getSingleResult()`` method instead:: - - $product = $query->getSingleResult(); - -.. caution:: - - The ``getSingleResult()`` method throws a ``Doctrine\ORM\NoResultException`` - exception if no results are returned and a ``Doctrine\ORM\NonUniqueResultException`` - if *more* than one result is returned. If you use this method, you may - need to wrap it in a try-catch block and ensure that only one result is - returned (if you're querying on something that could feasibly return - more than one result):: - - $query = $em->createQuery('SELECT ...') - ->setMaxResults(1); - - try { - $product = $query->getSingleResult(); - } catch (\Doctrine\Orm\NoResultException $e) { - $product = null; - } - // ... +in a database. For this reason, you select *from* the ``AcmeStoreBundle:Product`` +*object* and then alias it as ``p``. The DQL syntax is incredibly powerful, allowing you to easily join between entities (the topic of :ref:`relations ` will be covered later), group, etc. For more information, see the official Doctrine `Doctrine Query Language`_ documentation. -.. sidebar:: Setting Parameters - - Take note of the ``setParameter()`` method. When working with Doctrine, - it's always a good idea to set any external values as "placeholders", - which was done in the above query: - - .. code-block:: text - - ... WHERE p.price > :price ... - - You can then set the value of the ``price`` placeholder by calling the - ``setParameter()`` method:: - - ->setParameter('price', '19.99') - - Using parameters instead of placing values directly in the query string - is done to prevent SQL injection attacks and should *always* be done. - If you're using multiple parameters, you can set their values at once - using the ``setParameters()`` method:: - - ->setParameters(array( - 'price' => '19.99', - 'name' => 'Foo', - )) - Using Doctrine's Query Builder ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 9da598637cebd750c44c37ba153d8084a78f64c2 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 11:17:17 +0100 Subject: [PATCH 139/146] Minor tweaks to Repository section --- book/doctrine.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index d2b9387611e..f78be755922 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -772,10 +772,10 @@ Custom Repository Classes In the previous sections, you began constructing and using more complex queries from inside a controller. In order to isolate, test and reuse these queries, -it's a good idea to create a custom repository class for your entity and +it's a good practise to create a custom repository class for your entity and add methods with your query logic there. -To do this, add the name of the repository class to your mapping definition. +To do this, add the name of the repository class to your mapping definition: .. configuration-block:: From d751011c2dbe33e0a7158607cb9acfb4de31af32 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 12:08:53 +0100 Subject: [PATCH 140/146] Minor tweak to configuration section --- book/doctrine.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index f78be755922..bbce8ad9ff6 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -1253,7 +1253,7 @@ Configuration Doctrine is highly configurable, though you probably won't ever need to worry about most of its options. To find out more about configuring Doctrine, see -the Doctrine section of the :doc:`reference manual `. +the Doctrine section of the :doc:`config reference `. Lifecycle Callbacks ------------------- From 8be18a352a671819ab6b709629c1118594f68149 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 12:11:41 +0100 Subject: [PATCH 141/146] Removed some duplicated Livecycle docs The list is also included in the doctrine docs. There is no need to duplicate that in the sf docs. And if it's usefull, it certainly isn't when there is no more documentation about their meaning. --- book/doctrine.rst | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index bbce8ad9ff6..c30cc8e05bd 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -1265,7 +1265,7 @@ stages of the lifecycle of an entity (e.g. the entity is inserted, updated, deleted, etc). If you're using annotations for your metadata, start by enabling the lifecycle -callbacks. This is not necessary if you're using YAML or XML for your mapping: +callbacks. This is not necessary if you're using YAML or XML for your mapping. .. code-block:: php-annotations @@ -1328,20 +1328,8 @@ the current date, only when the entity is first persisted (i.e. inserted): Now, right before the entity is first persisted, Doctrine will automatically call this method and the ``createdAt`` field will be set to the current date. - -This can be repeated for any of the other lifecycle events, which include: - -* ``preRemove`` -* ``postRemove`` -* ``prePersist`` -* ``postPersist`` -* ``preUpdate`` -* ``postUpdate`` -* ``postLoad`` -* ``loadClassMetadata`` - -For more information on what these lifecycle events mean and lifecycle callbacks -in general, see Doctrine's `Lifecycle Events documentation`_ +For more information on other lifecycle events and lifecycle callbacks in +general, see Doctrine's `Lifecycle Events documentation`_. .. sidebar:: Lifecycle Callbacks and Event Listeners From f1c6e94f8e5886def04a368d2d982923c62b110b Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 12:15:13 +0100 Subject: [PATCH 142/146] Removed "Doctrine Extensions" section It's enough to add it to the "Read more" list, there is no need to introduce each cookbook article in a seperate section. --- book/doctrine.rst | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index c30cc8e05bd..a68a2186b3b 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -1344,17 +1344,6 @@ general, see Doctrine's `Lifecycle Events documentation`_. or subscriber and give it access to whatever resources you need. For more information, see :doc:`/cookbook/doctrine/event_listeners_subscribers`. -Doctrine Extensions: Timestampable, Sluggable, etc. ---------------------------------------------------- - -Doctrine is quite flexible, and a number of third-party extensions are available -that allow you to easily perform repeated and common tasks on your entities. -These include thing such as *Sluggable*, *Timestampable*, *Loggable*, *Translatable*, -and *Tree*. - -For more information on how to find and use these extensions, see the cookbook -article about :doc:`using common Doctrine extensions `. - .. _book-doctrine-field-types: Doctrine Field Types Reference From 9d03b69d9fffeba9c1319df48b4cae6c98066b59 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 12:16:39 +0100 Subject: [PATCH 143/146] Removed types list This is really doctrine specific, the sf docs should not document this, kind of SoC for docs :wink:. --- book/doctrine.rst | 102 +--------------------------------------------- 1 file changed, 2 insertions(+), 100 deletions(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index a68a2186b3b..7e78b106307 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -1351,106 +1351,8 @@ Doctrine Field Types Reference Doctrine comes with a large number of field types available. Each of these maps a PHP data type to a specific column type in whatever database you're -using. The following types are supported in Doctrine: - -* **Strings** - - * ``string`` (used for shorter strings) - * ``text`` (used for larger strings) - -* **Numbers** - - * ``integer`` - * ``smallint`` - * ``bigint`` - * ``decimal`` - * ``float`` - -* **Dates and Times** (use a `DateTime`_ object for these fields in PHP) - - * ``date`` - * ``time`` - * ``datetime`` - * ``datetimetz`` - -* **Other Types** - - * ``boolean`` - * ``object`` (serialized and stored in a ``CLOB`` field) - * ``array`` (serialized and stored in a ``CLOB`` field) - * ``blob`` (mapped to a resource stream) - * ``simple_array`` (serialized using :phpfunction:`implode()` and :phpfunction:`explode()`, - with a comma as delimiter, and stored in a ``CLOB`` field) - * ``json_array`` (serialized using :phpfunction:`json_encode()` and :phpfunction:`json_decode()`, - and stored in a ``CLOB`` field) - * ``guid`` - -For more information, see Doctrine's `Mapping Types documentation`_. - -Field Options -~~~~~~~~~~~~~ - -Each field can have a set of options applied to it. The available options -include ``type`` (defaults to ``string``), ``name``, ``length``, ``unique`` -and ``nullable``. Take a few examples: - -.. configuration-block:: - - .. code-block:: php-annotations - - /** - * A string field with length 255 that cannot be null - * (reflecting the default values for the "type", "length" - * and *nullable* options) - * - * @ORM\Column() - */ - protected $name; - - /** - * A string field of length 150 that persists to an "email_address" column - * and has a unique index. - * - * @ORM\Column(name="email_address", unique=true, length=150) - */ - protected $email; - - .. code-block:: yaml - - fields: - # A string field length 255 that cannot be null - # (reflecting the default values for the "length" and *nullable* options) - # type attribute is necessary in YAML definitions - name: - type: string - - # A string field of length 150 that persists to an "email_address" column - # and has a unique index. - email: - type: string - column: email_address - length: 150 - unique: true - - .. code-block:: xml - - - - - -.. note:: - - There are a few more options not listed here. For more details, see - Doctrine's `Property Mapping documentation`_ +using. To see a list of all available types and more information, see +Doctrine's `Mapping Types documentation`_. .. index:: single: Doctrine; ORM console commands From 7c2ad2956093cdd3f91e6c3dd57fed89e2109a24 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 12:22:31 +0100 Subject: [PATCH 144/146] Moved commands to cookbook It's not really basic information. All important commands are already discussed in the rest of the chapter. The rest are just usefull commands, which is a perfect topic for a cookbook. --- book/doctrine.rst | 62 +---------------------------------- cookbook/doctrine/console.rst | 60 +++++++++++++++++++++++++++++++++ cookbook/doctrine/index.rst | 1 + cookbook/map.rst.inc | 1 + 4 files changed, 63 insertions(+), 61 deletions(-) create mode 100644 cookbook/doctrine/console.rst diff --git a/book/doctrine.rst b/book/doctrine.rst index 7e78b106307..8abdaaf4958 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -1354,67 +1354,6 @@ maps a PHP data type to a specific column type in whatever database you're using. To see a list of all available types and more information, see Doctrine's `Mapping Types documentation`_. -.. index:: - single: Doctrine; ORM console commands - single: CLI; Doctrine ORM - -Console Commands ----------------- - -The Doctrine2 ORM integration offers several console commands under the -``doctrine`` namespace. To view the command list you can run the console -without any arguments: - -.. code-block:: bash - - $ php app/console - -A list of available commands will print out, many of which start with the -``doctrine:`` prefix. You can find out more information about any of these -commands (or any Symfony command) by running the ``help`` command. For example, -to get details about the ``doctrine:database:create`` task, run: - -.. code-block:: bash - - $ php app/console help doctrine:database:create - -Some notable or interesting tasks include: - -* ``doctrine:ensure-production-settings`` - checks to see if the current - environment is configured efficiently for production. This should always - be run in the ``prod`` environment: - - .. code-block:: bash - - $ php app/console doctrine:ensure-production-settings --env=prod - -* ``doctrine:mapping:import`` - allows Doctrine to introspect an existing - database and create mapping information. For more information, see - :doc:`/cookbook/doctrine/reverse_engineering`. - -* ``doctrine:mapping:info`` - tells you all of the entities that Doctrine - is aware of and whether or not there are any basic errors with the mapping. - -* ``doctrine:query:dql`` and ``doctrine:query:sql`` - allow you to execute - DQL or SQL queries directly from the command line. - -.. note:: - - To be able to load data fixtures to your database, you will need to have - the DoctrineFixturesBundle bundle installed. To learn how to do it, - read the ":doc:`/bundles/DoctrineFixturesBundle/index`" entry of the - documentation. - -.. tip:: - - This page shows working with Doctrine within a controller. You may also - want to work with Doctrine elsewhere in your application. The - :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::getDoctrine` - method of the controller returns the ``doctrine`` service, you can work with - this in the same way elsewhere by injecting this into your own - services. See :doc:`/book/service_container` for more on creating - your own services. - Summary ------- @@ -1434,6 +1373,7 @@ For more information about Doctrine, see the *Doctrine* section of the * :doc:`/bundles/DoctrineFixturesBundle/index` * :doc:`/cookbook/doctrine/common_extensions` +* :doc:`/cookbook/doctrine/console` .. _`Doctrine`: http://www.doctrine-project.org/ .. _`MongoDB`: http://www.mongodb.org/ diff --git a/cookbook/doctrine/console.rst b/cookbook/doctrine/console.rst new file mode 100644 index 00000000000..b48cd3e3f3c --- /dev/null +++ b/cookbook/doctrine/console.rst @@ -0,0 +1,60 @@ +.. index:: + single: Doctrine; ORM console commands + single: CLI; Doctrine ORM + +Console Commands +---------------- + +The Doctrine2 ORM integration offers several console commands under the +``doctrine`` namespace. To view the command list you can run the console +without any arguments: + +.. code-block:: bash + + $ php app/console + +A list of available commands will print out, many of which start with the +``doctrine:`` prefix. You can find out more information about any of these +commands (or any Symfony command) by running the ``help`` command. For example, +to get details about the ``doctrine:database:create`` task, run: + +.. code-block:: bash + + $ php app/console help doctrine:database:create + +Some notable or interesting tasks include: + +* ``doctrine:ensure-production-settings`` - checks to see if the current + environment is configured efficiently for production. This should always + be run in the ``prod`` environment: + + .. code-block:: bash + + $ php app/console doctrine:ensure-production-settings --env=prod + +* ``doctrine:mapping:import`` - allows Doctrine to introspect an existing + database and create mapping information. For more information, see + :doc:`/cookbook/doctrine/reverse_engineering`. + +* ``doctrine:mapping:info`` - tells you all of the entities that Doctrine + is aware of and whether or not there are any basic errors with the mapping. + +* ``doctrine:query:dql`` and ``doctrine:query:sql`` - allow you to execute + DQL or SQL queries directly from the command line. + +.. note:: + + To be able to load data fixtures to your database, you will need to have + the DoctrineFixturesBundle bundle installed. To learn how to do it, + read the ":doc:`/bundles/DoctrineFixturesBundle/index`" entry of the + documentation. + +.. tip:: + + This page shows working with Doctrine within a controller. You may also + want to work with Doctrine elsewhere in your application. The + :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::getDoctrine` + method of the controller returns the ``doctrine`` service, you can work with + this in the same way elsewhere by injecting this into your own + services. See :doc:`/book/service_container` for more on creating + your own services. diff --git a/cookbook/doctrine/index.rst b/cookbook/doctrine/index.rst index 7f19ef7d4fe..a62c736db11 100644 --- a/cookbook/doctrine/index.rst +++ b/cookbook/doctrine/index.rst @@ -14,3 +14,4 @@ Doctrine resolve_target_entity mapping_model_classes registration_form + console diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index 6986e4b1ca0..b4833557d7a 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -62,6 +62,7 @@ * :doc:`/cookbook/doctrine/resolve_target_entity` * :doc:`/cookbook/doctrine/mapping_model_classes` * :doc:`/cookbook/doctrine/registration_form` + * :doc:`/cookbook/doctrine/console` * :doc:`/cookbook/email/index` From 36df97502fcf28ce67b5a0d3beb3ac13051763fc Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 12:25:14 +0100 Subject: [PATCH 145/146] Small tweaks to summary --- book/doctrine.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index 8abdaaf4958..ab09847d3e7 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -1369,11 +1369,12 @@ that allow you to take different actions as objects go through their persistence lifecycle. For more information about Doctrine, see the *Doctrine* section of the -:doc:`cookbook `, which includes the following articles: +:doc:`cookbook `. Some usefull articles might be: -* :doc:`/bundles/DoctrineFixturesBundle/index` * :doc:`/cookbook/doctrine/common_extensions` * :doc:`/cookbook/doctrine/console` +* :doc:`/bundles/DoctrineFixturesBundle/index` +* :doc:`/bundles/DoctrineMongoDBBundle/index` .. _`Doctrine`: http://www.doctrine-project.org/ .. _`MongoDB`: http://www.mongodb.org/ From 86719ee69d6570198c5337bfdc530101bb27e87b Mon Sep 17 00:00:00 2001 From: WouterJ Date: Sat, 18 Jan 2014 12:27:37 +0100 Subject: [PATCH 146/146] Clean up reference pointers list --- book/doctrine.rst | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/book/doctrine.rst b/book/doctrine.rst index ab09847d3e7..8fc6e72dc6e 100644 --- a/book/doctrine.rst +++ b/book/doctrine.rst @@ -1382,10 +1382,8 @@ For more information about Doctrine, see the *Doctrine* section of the .. _`Query Builder`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html .. _`Doctrine Query Language`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html .. _`Association Mapping Documentation`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html -.. _`DateTime`: http://php.net/manual/en/class.datetime.php .. _`Mapping Types Documentation`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#doctrine-mapping-types -.. _`Property Mapping documentation`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#property-mapping +.. _`Property Mapping`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#property-mapping .. _`Lifecycle Events documentation`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-events .. _`Reserved SQL keywords documentation`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#quoting-reserved-words .. _`Persistent classes`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#persistent-classes -.. _`Property Mapping`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#property-mapping