From d935ceafe093d96e44ee08e312b3dbd02eb1afe0 Mon Sep 17 00:00:00 2001 From: Samuel Chiriluta Date: Mon, 31 Aug 2015 12:21:25 +0300 Subject: [PATCH 01/21] Update security.rst For return array($kevin, $anne); you receive ContextErrorException: Catchable Fatal Error: Argument 3 passed to Sonata\AdminBundle\Util\AdminObjectAclData::__construct() must implement interface Traversable, array given, called in C:\_\xampp\htdocs\_projects\laas\git\vendor\sonata-project\admin-bundle\Controller\CRUDController.php on line 1027 and defined 500 Internal Server Error - ContextErrorException Also maybe $container can be replaced by $this->container on line 689? Thanks! --- Resources/doc/reference/security.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Resources/doc/reference/security.rst b/Resources/doc/reference/security.rst index 751d0779be..a8bb1173cf 100644 --- a/Resources/doc/reference/security.rst +++ b/Resources/doc/reference/security.rst @@ -692,7 +692,7 @@ return an iterable collection of users. $kevin = $userManager->findUserByUsername('kevin'); $anne = $userManager->findUserByUsername('anne'); - return array($kevin, $anne); + return new \ArrayIterator(array($kevin, $anne)); } Custom user manager From 986f850e5b5fc44cb809a15a9bec33b6e363fa38 Mon Sep 17 00:00:00 2001 From: Cezar Pendarovski Date: Sat, 5 Dec 2015 15:42:55 +0100 Subject: [PATCH 02/21] Corrected small grammar errors and typos --- Resources/doc/reference/security.rst | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Resources/doc/reference/security.rst b/Resources/doc/reference/security.rst index 751d0779be..434b8fc447 100644 --- a/Resources/doc/reference/security.rst +++ b/Resources/doc/reference/security.rst @@ -32,7 +32,7 @@ The install process is available on the dedicated Security handlers ----------------- -The security part is managed by a ``SecurityHandler``, the bundle comes with 3 handlers +The security part is managed by a ``SecurityHandler``, the bundle comes with 3 handlers: - ``sonata.admin.security.handler.role``: ROLES to handle permissions - ``sonata.admin.security.handler.acl``: ACL and ROLES to handle permissions @@ -101,7 +101,7 @@ Configuration First, activate the role security handler as described above. -Each time an user tries to do an action in the admin, Sonata checks if he is +Each time a user tries to do an action in the admin, Sonata checks if he is either a super admin (``ROLE_SUPER_ADMIN``) **or** has the permission. The permissions are: @@ -118,7 +118,7 @@ service), Sonata will check if the user has the ``ROLE_SONATA_ADMIN_DEMO_FOO_EDI The role name will be based on the name of your admin service. For instance, `acme.blog.post.admin` will become `ROLE_ACME_BLOG_POST_ADMIN_{ACTION}`. -So our ``security.yml`` file may look to something like this: +So our ``security.yml`` file may look something like this: .. configuration-block:: @@ -297,7 +297,7 @@ The following configuration for the SonataUserBundle defines: - the login form for authentication - the access control: resources with related required roles, the important part is the admin configuration -- the ``acl`` option to enable the ACL. +- the ``acl`` option to enable the ACL - the ``AdminPermissionMap`` defines the permissions of the Admin class .. configuration-block:: @@ -443,10 +443,10 @@ Owner: Vocabulary used for Access Control Lists: - **Role:** a user role; -- **ACL:** a list of access rules, the Admin uses 2 types: +- **ACL:** a list of access rules, the Admin uses 2 types; - **Admin ACL:** created from the Security information of the Admin class for each admin and shares the Access Control Entries that specify what - the user can do (permissions) with the admin + the user can do (permissions) with the admin; - **Object ACL:** also created from the security information of the ``Admin`` class however created for each object, it uses 2 scopes: @@ -482,9 +482,9 @@ In the application the security context is asked if access is granted for a role or a permission (``admin.isGranted``): - **Token:** a token identifies a user between requests; -- **Voter:** sort of judge that returns if access is granted of denied, if the +- **Voter:** sort of judge that returns whether access is granted or denied, if the voter should not vote for a case, it returns abstain; -- **AccessDecisionManager:** decides if access is granted or denied according +- **AccessDecisionManager:** decides whether access is granted or denied according a specific strategy. It grants access if at least one (affirmative strategy), all (unanimous strategy) or more then half (consensus strategy) of the counted votes granted access; From 092c8af9acf32ca0ace75d31828a97916cea250f Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sat, 12 Dec 2015 18:43:28 +0100 Subject: [PATCH 03/21] Move Security ACL dependency to required again --- composer.json | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 1ec30940d4..712ecd862f 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,7 @@ "symfony/form": "~2.3", "symfony/validator": "~2.3", "symfony/security-bundle": "~2.3", + "symfony/security-acl": "~2.4", "symfony/routing": "~2.3", "symfony/config": "~2.3", "symfony/console": "~2.3", @@ -42,14 +43,12 @@ "require-dev": { "jms/translation-bundle": "~1.1", "symfony/yaml": "~2.3", - "symfony/security-acl": "~2.4", "sonata-project/intl-bundle": "~2.1", "symfony/phpunit-bridge": "~2.7|~3.0" }, "suggest": { "jms/translation-bundle": "Extract message keys from Admins", - "sonata-project/intl-bundle": "Add localized date and number into the list", - "symfony/security-acl": "To make sonata working with Symfony >=2.8" + "sonata-project/intl-bundle": "Add localized date and number into the list" }, "autoload": { "psr-4": { "Sonata\\AdminBundle\\": "" } From 9aef9f3559beb7a1b2acbe0ed80aa4f49a44cc4f Mon Sep 17 00:00:00 2001 From: Wouter J Date: Sat, 12 Dec 2015 20:23:49 +0100 Subject: [PATCH 04/21] Fix build --- composer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/composer.json b/composer.json index 712ecd862f..adc5812017 100644 --- a/composer.json +++ b/composer.json @@ -26,6 +26,7 @@ "symfony/config": "~2.3", "symfony/console": "~2.3", "symfony/twig-bridge": "~2.3", + "symfony/twig-bundle": "~2.3", "symfony/class-loader":"~2.3", "symfony/expression-language": "~2.4", "symfony/property-access": "~2.3", From 214b9e7de695cb1fa1e2870556e04277fcf959c1 Mon Sep 17 00:00:00 2001 From: "Konstantin.Myakshin" Date: Fri, 29 Jan 2016 19:25:31 +0200 Subject: [PATCH 05/21] Fix tests for 2.3 branch --- .travis.yml | 11 ++++------ .../doc/cookbook/recipe_sortable_listing.rst | 8 +++---- Resources/doc/reference/advanced.rst | 8 +++---- Resources/doc/reference/getting_started.rst | 10 ++++----- Resources/doc/reference/preview_mode.rst | 2 +- Tests/Controller/CRUDControllerTest.php | 5 ++++- Tests/Controller/CoreControllerTest.php | 22 +++++++++++++++++++ composer.json | 3 +++ 8 files changed, 47 insertions(+), 22 deletions(-) diff --git a/.travis.yml b/.travis.yml index c05e13a178..fdd325d168 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,7 @@ sudo: false cache: directories: - - $HOME/.composer/cache + - $HOME/.composer/cache/files - $HOME/.cache/pip env: @@ -38,14 +38,11 @@ matrix: - php: 5.6 env: SYMFONY_VERSION=2.7.* - php: 5.6 - env: SYMFONY_VERSION=2.8.*@dev - - php: 5.6 - env: SYMFONY_VERSION="3.0.x-dev as 2.8" + env: SYMFONY_VERSION=2.8.* allow_failures: - php: 7.0 - php: hhvm - - env: SYMFONY_VERSION=2.8.*@dev - - env: SYMFONY_VERSION="3.0.x-dev as 2.8" + - env: SYMFONY_VERSION=2.8.* before_script: - mkdir -p ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d && echo "memory_limit=-1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini @@ -53,7 +50,7 @@ before_script: - composer config -q -g github-oauth.github.com $GITHUB_OAUTH_TOKEN - composer global require phpunit/phpunit:@stable fabpot/php-cs-fixer --no-update - composer global update --prefer-dist --no-interaction - - if [ "$SYMFONY_VERSION" = "2.8.*@dev" ] || [ "$SYMFONY_VERSION" = "3.0.x-dev as 2.8" ]; then SYMFONY_DEPRECATIONS_HELPER=strict; fi; + - if [ "$SYMFONY_VERSION" = "2.8.*" ]; then SYMFONY_DEPRECATIONS_HELPER=strict; fi; - if [ "$SYMFONY_VERSION" != "" ]; then composer require "symfony/symfony:${SYMFONY_VERSION}" --no-update; fi; - travis_wait composer update --prefer-dist --no-interaction $COMPOSER_FLAGS - export PATH=$HOME/.local/bin:$PATH diff --git a/Resources/doc/cookbook/recipe_sortable_listing.rst b/Resources/doc/cookbook/recipe_sortable_listing.rst index 632e173a2e..af821a870d 100644 --- a/Resources/doc/cookbook/recipe_sortable_listing.rst +++ b/Resources/doc/cookbook/recipe_sortable_listing.rst @@ -109,7 +109,7 @@ also define the sort by field to be position { $this->positionService = $positionHandler; } - + protected $datagridValues = array( '_page' => 1, '_sort_order' => 'ASC', @@ -132,9 +132,9 @@ also define the sort by field to be position And in the admin.yml add the following call .. code-block:: yaml - - - [ setContainer, [ @service_container ] ] - - [ setPositionService, [@pix_sortable_behavior.position]] + + - [ setContainer, [ "@service_container" ]] + - [ setPositionService, [ "@pix_sortable_behavior.position" ]] You should now have in your listing a new action column with 4 arrows to sort your records. diff --git a/Resources/doc/reference/advanced.rst b/Resources/doc/reference/advanced.rst index 2f1ccd9772..3435bb0764 100644 --- a/Resources/doc/reference/advanced.rst +++ b/Resources/doc/reference/advanced.rst @@ -106,8 +106,8 @@ You have 2 ways of defining the dependencies inside ``services.xml``: - Acme\ProjectBundle\Entity\Project - ~ calls: - - [ setLabelTranslatorStrategy, [ @sonata.admin.label.strategy.native ]] - - [ setRouteBuilder, [ @sonata.admin.route.path_info ]] + - [ setLabelTranslatorStrategy, [ "@sonata.admin.label.strategy.native" ]] + - [ setRouteBuilder, [ "@sonata.admin.route.path_info" ]] If you want to modify the service that is going to be injected, add the following code to your application's config file: @@ -179,9 +179,9 @@ To create your own RouteBuilder create the PHP class and register it as a servic services: acme.admin.entity_route_builder: - class: %acme.admin.entity_route_builder.class% + class: "%acme.admin.entity_route_builder.class%" arguments: - - @sonata.admin.audit.manager + - "@sonata.admin.audit.manager" Inherited classes diff --git a/Resources/doc/reference/getting_started.rst b/Resources/doc/reference/getting_started.rst index e76dcb29d8..3bc5a72b49 100644 --- a/Resources/doc/reference/getting_started.rst +++ b/Resources/doc/reference/getting_started.rst @@ -189,7 +189,7 @@ use the correct file extension): # app/config/config.yml imports: - - { resource: @AcmeDemoBundle/Resources/config/admin.xml } + - { resource: "@AcmeDemoBundle/Resources/config/admin.xml" } 2 - Have your bundle load it ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -202,12 +202,12 @@ file, using the ``load()`` method as described in the `symfony cookbook`_. .. code-block:: xml # Acme/DemoBundle/DependencyInjection/AcmeDemoBundleExtension.php for XML configurations - + namespace Acme\DemoBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\Config\FileLocator; - + class AcmeDemoBundleExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { @@ -220,7 +220,7 @@ file, using the ``load()`` method as described in the `symfony cookbook`_. .. code-block:: yaml # Acme/DemoBundle/DependencyInjection/AcmeDemoBundleExtension.php for YAML configurations - + namespace Acme\DemoBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Loader; @@ -244,7 +244,7 @@ your mapped model. You can start creating, listing, editing and deleting instanc You probably want to put your own project's name and logo on the top bar. Put your logo file here ``src/Acme/DemoBundle/Resources/public/img/fancy_acme_logo.png`` - + Install your assets: .. code-block:: sh diff --git a/Resources/doc/reference/preview_mode.rst b/Resources/doc/reference/preview_mode.rst index 00eace4bc0..e9f1a3f280 100644 --- a/Resources/doc/reference/preview_mode.rst +++ b/Resources/doc/reference/preview_mode.rst @@ -124,7 +124,7 @@ Hiding the fieldset tags with css (display:none) will be enough to only show the Or if you prefer less: -.. code-block:: sass +.. code-block:: scss div.sonata-preview-form { .row { diff --git a/Tests/Controller/CRUDControllerTest.php b/Tests/Controller/CRUDControllerTest.php index a0994a0600..70bebd130e 100644 --- a/Tests/Controller/CRUDControllerTest.php +++ b/Tests/Controller/CRUDControllerTest.php @@ -19,7 +19,6 @@ use Sonata\AdminBundle\Tests\Fixtures\Controller\BatchAdminController; use Sonata\AdminBundle\Util\AdminObjectAclManipulator; use Symfony\Bridge\Twig\Extension\FormExtension; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface; use Symfony\Component\HttpFoundation\Request; @@ -281,6 +280,10 @@ protected function setUp() return true; } + if ($id == 'templating') { + return true; + } + return false; })); diff --git a/Tests/Controller/CoreControllerTest.php b/Tests/Controller/CoreControllerTest.php index 730e320553..42e5718d2f 100644 --- a/Tests/Controller/CoreControllerTest.php +++ b/Tests/Controller/CoreControllerTest.php @@ -46,6 +46,17 @@ public function testdashboardActionStandardRequest() $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use ($values) { return $values[$id]; })); + + $container->expects($this->any()) + ->method('has') + ->will($this->returnCallback(function ($id) { + if ($id == 'templating') { + return true; + } + + return false; + })); + $container->expects($this->any())->method('getParameter')->will($this->returnCallback(function ($name) { if ($name == 'sonata.admin.configuration.dashboard_blocks') { return array(); @@ -89,6 +100,17 @@ public function testdashboardActionAjaxLayout() $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use ($values) { return $values[$id]; })); + + $container->expects($this->any()) + ->method('has') + ->will($this->returnCallback(function ($id) { + if ($id == 'templating') { + return true; + } + + return false; + })); + $container->expects($this->any())->method('getParameter')->will($this->returnCallback(function ($name) { if ($name == 'sonata.admin.configuration.dashboard_blocks') { return array(); diff --git a/composer.json b/composer.json index adc5812017..e8f592d69e 100644 --- a/composer.json +++ b/composer.json @@ -41,6 +41,9 @@ "knplabs/knp-menu-bundle": ">=1.1.0,<3.0.0", "knplabs/knp-menu": ">=1.1.0,<3.0.0" }, + "conflict": { + "symfony/security": ">2.8.999" + }, "require-dev": { "jms/translation-bundle": "~1.1", "symfony/yaml": "~2.3", From d5c37e200dd3d110be5f81275c02d96f8a10cc15 Mon Sep 17 00:00:00 2001 From: Konstantin Myakshin Date: Wed, 30 Dec 2015 14:42:39 +0200 Subject: [PATCH 06/21] Allow using overriden layout template in empty_layout --- Resources/views/empty_layout.html.twig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Resources/views/empty_layout.html.twig b/Resources/views/empty_layout.html.twig index b4c4370414..792a68ea70 100644 --- a/Resources/views/empty_layout.html.twig +++ b/Resources/views/empty_layout.html.twig @@ -9,7 +9,7 @@ file that was distributed with this source code. #} -{% extends 'SonataAdminBundle::standard_layout.html.twig' %} +{% extends admin_pool.getTemplate('layout') %} {% block sonata_header %}{% endblock %} {% block sonata_left_side %}{% endblock %} @@ -32,4 +32,4 @@ file that was distributed with this source code. {% block sonata_page_content %} {{ parent() }} {% endblock %} -{% endblock %} \ No newline at end of file +{% endblock %} From 61612242665125cf88f117d88ce59d6ab698d4dd Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Wed, 22 Apr 2015 12:17:16 +1000 Subject: [PATCH 07/21] Add support for entities outside of bundles --- Admin/Admin.php | 2 +- Tests/Admin/AdminTest.php | 30 ++++++++++++++++++++++-------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/Admin/Admin.php b/Admin/Admin.php index 44f3559076..ddd48d41b8 100644 --- a/Admin/Admin.php +++ b/Admin/Admin.php @@ -47,7 +47,7 @@ abstract class Admin implements AdminInterface, DomainObjectInterface const CONTEXT_MENU = 'menu'; const CONTEXT_DASHBOARD = 'dashboard'; - const CLASS_REGEX = '@(?:([A-Za-z0-9]*)\\\)?(Bundle\\\)?([A-Za-z0-9]+)Bundle\\\(Entity|Document|Model|PHPCR|CouchDocument|Phpcr|Doctrine\\\Orm|Doctrine\\\Phpcr|Doctrine\\\MongoDB|Doctrine\\\CouchDB)\\\(.*)@'; + const CLASS_REGEX = '@(?:([A-Za-z0-9]*)\\\)?(Bundle\\\)?([A-Za-z0-9]+?)(?:Bundle)?\\\(Entity|Document|Model|PHPCR|CouchDocument|Phpcr|Doctrine\\\Orm|Doctrine\\\Phpcr|Doctrine\\\MongoDB|Doctrine\\\CouchDB)\\\(.*)@'; /** * The class name managed by the admin class. diff --git a/Tests/Admin/AdminTest.php b/Tests/Admin/AdminTest.php index 536cf4beac..4b5983df77 100644 --- a/Tests/Admin/AdminTest.php +++ b/Tests/Admin/AdminTest.php @@ -437,6 +437,10 @@ public function provideGetBaseRoutePattern() 'AppBundle\Entity\User', '/app/user', ), + array( + 'App\Entity\User', + '/app/user', + ), ); } @@ -449,13 +453,16 @@ public function testGetBaseRoutePattern($objFqn, $expected) $this->assertSame($expected, $admin->getBaseRoutePattern()); } - public function testGetBaseRoutePatternWithChildAdmin() + /** + * @dataProvider provideGetBaseRoutePattern + */ + public function testGetBaseRoutePatternWithChildAdmin($objFqn, $expected) { - $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin'); + $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin'); $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin'); $commentAdmin->setParent($postAdmin); - $this->assertSame('/sonata/news/post/{id}/comment', $commentAdmin->getBaseRoutePattern()); + $this->assertSame($expected.'/{id}/comment', $commentAdmin->getBaseRoutePattern()); } /** @@ -463,7 +470,7 @@ public function testGetBaseRoutePatternWithChildAdmin() */ public function testGetBaseRoutePatternWithUnreconizedClassname() { - $admin = new PostAdmin('sonata.post.admin.post', 'News\Entity\Post', 'SonataNewsBundle:PostAdmin'); + $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin'); $admin->getBaseRoutePattern(); } @@ -526,6 +533,10 @@ public function provideGetBaseRouteName() 'AppBundle\Entity\User', 'admin_app_user', ), + array( + 'App\Entity\User', + 'admin_app_user', + ), ); } @@ -539,7 +550,10 @@ public function testGetBaseRouteName($objFqn, $expected) $this->assertSame($expected, $admin->getBaseRouteName()); } - public function testGetBaseRouteNameWithChildAdmin() + /** + * @dataProvider provideGetBaseRouteName + */ + public function testGetBaseRouteNameWithChildAdmin($objFqn, $expected) { $routeGenerator = new DefaultRouteGenerator( $this->getMock('Symfony\Component\Routing\RouterInterface'), @@ -547,7 +561,7 @@ public function testGetBaseRouteNameWithChildAdmin() ); $pathInfo = new \Sonata\AdminBundle\Route\PathInfoBuilder($this->getMock('Sonata\AdminBundle\Model\AuditManagerInterface')); - $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin'); + $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin'); $postAdmin->setRouteBuilder($pathInfo); $postAdmin->setRouteGenerator($routeGenerator); $postAdmin->initialize(); @@ -559,7 +573,7 @@ public function testGetBaseRouteNameWithChildAdmin() $postAdmin->addChild($commentAdmin); - $this->assertSame('admin_sonata_news_post_comment', $commentAdmin->getBaseRouteName()); + $this->assertSame($expected.'_comment', $commentAdmin->getBaseRouteName()); $this->assertTrue($postAdmin->hasRoute('show')); $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post.show')); @@ -574,7 +588,7 @@ public function testGetBaseRouteNameWithChildAdmin() */ public function testGetBaseRouteNameWithUnreconizedClassname() { - $admin = new PostAdmin('sonata.post.admin.post', 'News\Entity\Post', 'SonataNewsBundle:PostAdmin'); + $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin'); $admin->getBaseRouteName(); } From 6892d7c92428ab5cf9a4d6b453225d618d0fbd05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Thu, 18 Feb 2016 18:18:16 +0100 Subject: [PATCH 08/21] allow version 3.0 of the generator bundle It is the version required by default when installing a brand new sf 2.8 project. See symfony/symfony-standard Fixes #3596 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index e8f592d69e..926fec50cd 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,7 @@ "symfony/class-loader":"~2.3", "symfony/expression-language": "~2.4", "symfony/property-access": "~2.3", - "sensio/generator-bundle": "~2.3", + "sensio/generator-bundle": "~2.3|^3.0", "twig/twig": "~1.15", "twig/extensions": "~1.0", "sonata-project/exporter": "~1.0", From 13040b58c8c41cb440c8449359521a0187fffa0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Wed, 16 Mar 2016 20:11:23 +0100 Subject: [PATCH 09/21] mock Kernel::getContainer() Apparently, it is called and needs to return something. --- Tests/Command/GenerateAdminCommandTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Tests/Command/GenerateAdminCommandTest.php b/Tests/Command/GenerateAdminCommandTest.php index 74ea7c9739..af2b09afc2 100644 --- a/Tests/Command/GenerateAdminCommandTest.php +++ b/Tests/Command/GenerateAdminCommandTest.php @@ -72,6 +72,10 @@ protected function setUp() ->with($this->equalTo('AcmeDemoBundle')) ->will($this->returnValue($bundle)); + $kernel->expects($this->any()) + ->method('getContainer') + ->will($this->returnValue($this->container)); + $this->application = new Application($kernel); $this->command = new GenerateAdminCommand(); From 9f152086379ce9cb7b7a0b642b8c0a15cd1817b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Mon, 14 Mar 2016 22:27:41 +0100 Subject: [PATCH 10/21] use class names for types in 2.8 too This should generate less deprecation notices. --- Form/Extension/Field/Type/FormTypeFieldExtension.php | 5 ++++- Form/Type/CollectionType.php | 5 ++++- .../Extension/Field/Type/FormTypeFieldExtensionTest.php | 7 ++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Form/Extension/Field/Type/FormTypeFieldExtension.php b/Form/Extension/Field/Type/FormTypeFieldExtension.php index f663f3665b..2a9a9fbb81 100644 --- a/Form/Extension/Field/Type/FormTypeFieldExtension.php +++ b/Form/Extension/Field/Type/FormTypeFieldExtension.php @@ -153,7 +153,10 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function getExtendedType() { - return 'form'; + return + method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix') ? + 'Symfony\Component\Form\Extension\Core\Type\FormType' : + 'form'; } /** diff --git a/Form/Type/CollectionType.php b/Form/Type/CollectionType.php index 8a72266002..684fd55fd0 100644 --- a/Form/Type/CollectionType.php +++ b/Form/Type/CollectionType.php @@ -26,7 +26,10 @@ class CollectionType extends AbstractType */ public function getParent() { - return 'collection'; + return + method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix') ? + 'Symfony\Component\Form\Extension\Core\Type\CollectionType' : + 'collection'; } /** diff --git a/Tests/Form/Extension/Field/Type/FormTypeFieldExtensionTest.php b/Tests/Form/Extension/Field/Type/FormTypeFieldExtensionTest.php index 27acdeda83..4b259ee349 100644 --- a/Tests/Form/Extension/Field/Type/FormTypeFieldExtensionTest.php +++ b/Tests/Form/Extension/Field/Type/FormTypeFieldExtensionTest.php @@ -23,7 +23,12 @@ public function testExtendedType() { $extension = new FormTypeFieldExtension(); - $this->assertSame('form', $extension->getExtendedType()); + $this->assertSame( + method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix') ? + 'Symfony\Component\Form\Extension\Core\Type\FormType' : + 'form', + $extension->getExtendedType() + ); } public function testDefaultOptions() From 77b4c16f58858df7d0cf0ffcca0792be81c64e00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Wed, 16 Mar 2016 21:04:25 +0100 Subject: [PATCH 11/21] use the request stack if available The request service has been deprecated --- Controller/CRUDController.php | 310 ++++++++++++++++++++++------------ 1 file changed, 201 insertions(+), 109 deletions(-) diff --git a/Controller/CRUDController.php b/Controller/CRUDController.php index b14b76bb82..37dd19e015 100644 --- a/Controller/CRUDController.php +++ b/Controller/CRUDController.php @@ -44,13 +44,14 @@ class CRUDController extends Controller * * @return Response with json encoded data */ - protected function renderJson($data, $status = 200, $headers = array()) + protected function renderJson($data, $status = 200, $headers = array(), Request $request = null) { + $request = $this->resolveRequest($request); // fake content-type so browser does not show the download popup when this // response is rendered through an iframe (used by the jquery.form.js plugin) // => don't know yet if it is the best solution - if ($this->get('request')->get('_xml_http_request') - && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) { + if ($request->get('_xml_http_request') + && strpos($request->headers->get('Content-Type'), 'multipart/form-data') === 0) { $headers['Content-Type'] = 'text/plain'; } else { $headers['Content-Type'] = 'application/json'; @@ -64,20 +65,25 @@ protected function renderJson($data, $status = 200, $headers = array()) * * @return bool True if the request is an XMLHttpRequest, false otherwise */ - protected function isXmlHttpRequest() + protected function isXmlHttpRequest(Request $request = null) { - return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request'); + $request = $this->resolveRequest($request); + + return $request->isXmlHttpRequest() || $request->get('_xml_http_request'); } /** * Returns the correct RESTful verb, given either by the request itself or * via the "_method" parameter. * + * @param Request $request + * * @return string HTTP method, either */ - protected function getRestMethod() + protected function getRestMethod(Request $request = null) { - $request = $this->getRequest(); + $request = $this->resolveRequest($request); + if (Request::getHttpMethodParameterOverride() || !$request->request->has('_method')) { return $request->getMethod(); } @@ -104,7 +110,9 @@ public function setContainer(ContainerInterface $container = null) */ protected function configure() { - $adminCode = $this->container->get('request')->get('_sonata_admin'); + $request = $this->getRequest(); + + $adminCode = $request->get('_sonata_admin'); if (!$adminCode) { throw new \RuntimeException(sprintf( @@ -130,8 +138,6 @@ protected function configure() $rootAdmin = $rootAdmin->getParent(); } - $request = $this->container->get('request'); - $rootAdmin->setRequest($request); if ($request->get('uniqid')) { @@ -157,11 +163,15 @@ protected function getLogger() /** * Returns the base template name. * + * @param Request $request + * * @return string The template name */ - protected function getBaseTemplate() + protected function getBaseTemplate(Request $request = null) { - if ($this->isXmlHttpRequest()) { + $request = $this->resolveRequest($request); + + if ($this->isXmlHttpRequest($request)) { return $this->admin->getTemplate('ajax'); } @@ -170,16 +180,22 @@ protected function getBaseTemplate() /** * {@inheritdoc} + * + * @param Request $request */ - public function render($view, array $parameters = array(), Response $response = null) + public function render($view, array $parameters = array(), Response $response = null, Request $request = null) { - $parameters['admin'] = isset($parameters['admin']) ? + $request = $this->resolveRequest($request); + + $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin; + $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : - $this->getBaseTemplate(); - $parameters['admin_pool'] = $this->get('sonata.admin.pool'); + $this->getBaseTemplate($request); + + $parameters['admin_pool'] = $this->get('sonata.admin.pool'); return parent::render($view, $parameters, $response); } @@ -196,12 +212,16 @@ private function logModelManagerException($e) /** * List action. * + * @param Request $request + * * @return Response * * @throws AccessDeniedException If access is not granted */ - public function listAction() + public function listAction(Request $request = null) { + $request = $this->resolveRequest($request); + if (false === $this->admin->isGranted('LIST')) { throw new AccessDeniedException(); } @@ -217,24 +237,27 @@ public function listAction() 'form' => $formView, 'datagrid' => $datagrid, 'csrf_token' => $this->getCsrfToken('sonata.batch'), - )); + ), null, $request); } /** * Execute a batch delete. * * @param ProxyQueryInterface $query + * @param Request $request * * @return RedirectResponse * * @throws AccessDeniedException If access is not granted */ - public function batchActionDelete(ProxyQueryInterface $query) + public function batchActionDelete(ProxyQueryInterface $query, Request $request = null) { if (false === $this->admin->isGranted('DELETE')) { throw new AccessDeniedException(); } + $request = $this->resolveRequest($request); + $modelManager = $this->admin->getModelManager(); try { $modelManager->batchDelete($this->admin->getClass(), $query); @@ -254,16 +277,18 @@ public function batchActionDelete(ProxyQueryInterface $query) * Delete action. * * @param int|string|null $id + * @param Request $request * * @return Response|RedirectResponse * * @throws NotFoundHttpException If the object does not exist * @throws AccessDeniedException If access is not granted */ - public function deleteAction($id) + public function deleteAction($id, Request $request = null) { - $id = $this->get('request')->get($this->admin->getIdParameter()); - $object = $this->admin->getObject($id); + $request = $this->resolveRequest($request); + $id = $request->get($this->admin->getIdParameter()); + $object = $this->admin->getObject($id); if (!$object) { throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id)); @@ -280,8 +305,8 @@ public function deleteAction($id) try { $this->admin->delete($object); - if ($this->isXmlHttpRequest()) { - return $this->renderJson(array('result' => 'ok')); + if ($this->isXmlHttpRequest($request)) { + return $this->renderJson(array('result' => 'ok'), 200, array(), $request); } $this->addFlash( @@ -295,8 +320,8 @@ public function deleteAction($id) } catch (ModelManagerException $e) { $this->logModelManagerException($e); - if ($this->isXmlHttpRequest()) { - return $this->renderJson(array('result' => 'error')); + if ($this->isXmlHttpRequest($request)) { + return $this->renderJson(array('result' => 'error'), 200, array(), $request); } $this->addFlash( @@ -309,32 +334,34 @@ public function deleteAction($id) ); } - return $this->redirectTo($object); + return $this->redirectTo($object, $request); } return $this->render($this->admin->getTemplate('delete'), array( 'object' => $object, 'action' => 'delete', 'csrf_token' => $this->getCsrfToken('sonata.delete'), - )); + ), null, $request); } /** * Edit action. * * @param int|string|null $id + * @param Request $request * * @return Response|RedirectResponse * * @throws NotFoundHttpException If the object does not exist * @throws AccessDeniedException If access is not granted */ - public function editAction($id = null) + public function editAction($id = null, Request $request = null) { + $request = $this->resolveRequest($request); // the key used to lookup the template $templateKey = 'edit'; - $id = $this->get('request')->get($this->admin->getIdParameter()); + $id = $request->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); if (!$object) { @@ -350,22 +377,23 @@ public function editAction($id = null) /** @var $form \Symfony\Component\Form\Form */ $form = $this->admin->getForm(); $form->setData($object); + $form->handleRequest($request); if ($this->getRestMethod() == 'POST') { - $form->submit($this->get('request')); + $form->submit($request); $isFormValid = $form->isValid(); // persist if the form was valid and if in preview mode the preview was approved - if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) { + if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) { try { $object = $this->admin->update($object); - if ($this->isXmlHttpRequest()) { + if ($this->isXmlHttpRequest($request)) { return $this->renderJson(array( - 'result' => 'ok', - 'objectId' => $this->admin->getNormalizedIdentifier($object), - )); + 'result' => 'ok', + 'objectId' => $this->admin->getNormalizedIdentifier($object), + ), 200, array(), $request); } $this->addFlash( @@ -378,7 +406,7 @@ public function editAction($id = null) ); // redirect to edit mode - return $this->redirectTo($object); + return $this->redirectTo($object, $request); } catch (ModelManagerException $e) { $this->logModelManagerException($e); @@ -388,7 +416,7 @@ public function editAction($id = null) // show an error message if the form failed validation if (!$isFormValid) { - if (!$this->isXmlHttpRequest()) { + if (!$this->isXmlHttpRequest($request)) { $this->addFlash( 'sonata_flash_error', $this->admin->trans( @@ -398,7 +426,7 @@ public function editAction($id = null) ) ); } - } elseif ($this->isPreviewRequested()) { + } elseif ($this->isPreviewRequested($request)) { // enable the preview template if the form was valid and preview was requested $templateKey = 'preview'; $this->admin->getShow(); @@ -414,36 +442,39 @@ public function editAction($id = null) 'action' => 'edit', 'form' => $view, 'object' => $object, - )); + ), null, $request); } /** * Redirect the user depend on this choice. * - * @param object $object + * @param object $object + * @param Request $request * * @return RedirectResponse */ - protected function redirectTo($object) + protected function redirectTo($object, Request $request = null) { + $request = $this->resolveRequest($request); + $url = false; - if (null !== $this->get('request')->get('btn_update_and_list')) { + if (null !== $request->get('btn_update_and_list')) { $url = $this->admin->generateUrl('list'); } - if (null !== $this->get('request')->get('btn_create_and_list')) { + if (null !== $request->get('btn_create_and_list')) { $url = $this->admin->generateUrl('list'); } - if (null !== $this->get('request')->get('btn_create_and_create')) { + if (null !== $request->get('btn_create_and_create')) { $params = array(); if ($this->admin->hasActiveSubClass()) { - $params['subclass'] = $this->get('request')->get('subclass'); + $params['subclass'] = $request->get('subclass'); } $url = $this->admin->generateUrl('create', $params); } - if ($this->getRestMethod() == 'DELETE') { + if ($this->getRestMethod($request) === 'DELETE') { $url = $this->admin->generateUrl('list'); } @@ -457,37 +488,40 @@ protected function redirectTo($object) /** * Batch action. * + * @param Request $request + * * @return Response|RedirectResponse * * @throws NotFoundHttpException If the HTTP method is not POST * @throws \RuntimeException If the batch action is not defined */ - public function batchAction() + public function batchAction(Request $request = null) { - $restMethod = $this->getRestMethod(); + $request = $this->resolveRequest($request); + $restMethod = $this->getRestMethod($request); if ('POST' !== $restMethod) { throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod)); } // check the csrf token - $this->validateCsrfToken('sonata.batch'); + $this->validateCsrfToken('sonata.batch', $request); - $confirmation = $this->get('request')->get('confirmation', false); + $confirmation = $request->get('confirmation', false); - if ($data = json_decode($this->get('request')->get('data'), true)) { + if ($data = json_decode($request->get('data'), true)) { $action = $data['action']; $idx = $data['idx']; $allElements = $data['all_elements']; - $this->get('request')->request->replace($data); + $request->request->replace($data); } else { - $this->get('request')->request->set('idx', $this->get('request')->get('idx', array())); - $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false)); + $request->request->set('idx', $request->get('idx', array())); + $request->request->set('all_elements', $request->get('all_elements', false)); - $action = $this->get('request')->get('action'); - $idx = $this->get('request')->get('idx'); - $allElements = $this->get('request')->get('all_elements'); - $data = $this->get('request')->request->all(); + $action = $request->get('action'); + $idx = $request->get('idx'); + $allElements = $request->get('all_elements'); + $data = $request->request->all(); unset($data['_sonata_csrf_token']); } @@ -501,7 +535,7 @@ public function batchAction() $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction)); if (method_exists($this, $isRelevantAction)) { - $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements); + $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements, $request); } else { $nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected } @@ -540,7 +574,7 @@ public function batchAction() 'form' => $formView, 'data' => $data, 'csrf_token' => $this->getCsrfToken('sonata.batch'), - )); + ), null, $request); } // execute the action, batchActionXxxxx @@ -562,18 +596,21 @@ public function batchAction() $query = null; } - return call_user_func(array($this, $finalAction), $query); + return call_user_func(array($this, $finalAction), $query, $request); } /** * Create action. * + * @param Request $request + * * @return Response * * @throws AccessDeniedException If access is not granted */ - public function createAction() + public function createAction(Request $request = null) { + $request = $this->resolveRequest($request); // the key used to lookup the template $templateKey = 'edit'; @@ -590,12 +627,12 @@ public function createAction() $form->setData($object); if ($this->getRestMethod() == 'POST') { - $form->submit($this->get('request')); + $form->submit($request); $isFormValid = $form->isValid(); // persist if the form was valid and if in preview mode the preview was approved - if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) { + if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) { if (false === $this->admin->isGranted('CREATE', $object)) { throw new AccessDeniedException(); } @@ -603,11 +640,11 @@ public function createAction() try { $object = $this->admin->create($object); - if ($this->isXmlHttpRequest()) { + if ($this->isXmlHttpRequest($request)) { return $this->renderJson(array( 'result' => 'ok', 'objectId' => $this->admin->getNormalizedIdentifier($object), - )); + ), 200, array(), $request); } $this->addFlash( @@ -620,7 +657,7 @@ public function createAction() ); // redirect to edit mode - return $this->redirectTo($object); + return $this->redirectTo($object, $request); } catch (ModelManagerException $e) { $this->logModelManagerException($e); @@ -630,7 +667,7 @@ public function createAction() // show an error message if the form failed validation if (!$isFormValid) { - if (!$this->isXmlHttpRequest()) { + if (!$this->isXmlHttpRequest($request)) { $this->addFlash( 'sonata_flash_error', $this->admin->trans( @@ -640,7 +677,7 @@ public function createAction() ) ); } - } elseif ($this->isPreviewRequested()) { + } elseif ($this->isPreviewRequested($request)) { // pick the preview template if the form was valid and preview was requested $templateKey = 'preview'; $this->admin->getShow(); @@ -656,27 +693,35 @@ public function createAction() 'action' => 'create', 'form' => $view, 'object' => $object, - )); + ), null, $request); } /** * Returns true if the preview is requested to be shown. * + * @param Request $request + * * @return bool */ - protected function isPreviewRequested() + protected function isPreviewRequested(Request $request = null) { - return $this->get('request')->get('btn_preview') !== null; + $request = $this->resolveRequest($request); + + return $request->get('btn_preview') !== null; } /** * Returns true if the preview has been approved. * + * @param Request $request + * * @return bool */ - protected function isPreviewApproved() + protected function isPreviewApproved(Request $request = null) { - return $this->get('request')->get('btn_preview_approve') !== null; + $request = $this->resolveRequest($request); + + return $request->get('btn_preview_approve') !== null; } /** @@ -685,39 +730,49 @@ protected function isPreviewApproved() * That means either a preview is requested or the preview has already been shown * and it got approved/declined. * + * @param Request $request + * * @return bool */ - protected function isInPreviewMode() + protected function isInPreviewMode(Request $request = null) { + $request = $this->resolveRequest($request); + return $this->admin->supportsPreviewMode() - && ($this->isPreviewRequested() - || $this->isPreviewApproved() - || $this->isPreviewDeclined()); + && ($this->isPreviewRequested($request) + || $this->isPreviewApproved($request) + || $this->isPreviewDeclined($request)); } /** * Returns true if the preview has been declined. * + * @param Request $request + * * @return bool */ - protected function isPreviewDeclined() + protected function isPreviewDeclined(Request $request = null) { - return $this->get('request')->get('btn_preview_decline') !== null; + $request = $this->resolveRequest($request); + + return $request->get('btn_preview_decline') !== null; } /** * Show action. * * @param int|string|null $id + * @param Request $request * * @return Response * * @throws NotFoundHttpException If the object does not exist * @throws AccessDeniedException If access is not granted */ - public function showAction($id = null) + public function showAction($id = null, Request $request = null) { - $id = $this->get('request')->get($this->admin->getIdParameter()); + $request = $this->resolveRequest($request); + $id = $request->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); @@ -735,22 +790,24 @@ public function showAction($id = null) 'action' => 'show', 'object' => $object, 'elements' => $this->admin->getShow(), - )); + ), null, $request); } /** * Show history revisions for object. * * @param int|string|null $id + * @param Request $request * * @return Response * * @throws AccessDeniedException If access is not granted * @throws NotFoundHttpException If the object does not exist or the audit reader is not available */ - public function historyAction($id = null) + public function historyAction($id = null, Request $request = null) { - $id = $this->get('request')->get($this->admin->getIdParameter()); + $request = $this->resolveRequest($request); + $id = $request->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); @@ -778,11 +835,11 @@ public function historyAction($id = null) $revisions = $reader->findRevisions($this->admin->getClass(), $id); return $this->render($this->admin->getTemplate('history'), array( - 'action' => 'history', - 'object' => $object, - 'revisions' => $revisions, - 'currentRevision' => $revisions ? current($revisions) : false, - )); + 'action' => 'history', + 'object' => $object, + 'revisions' => $revisions, + 'currentRevision' => $revisions ? current($revisions) : false, + ), null, $request); } /** @@ -790,15 +847,17 @@ public function historyAction($id = null) * * @param int|string|null $id * @param string|null $revision + * @param Request $request * * @return Response * * @throws AccessDeniedException If access is not granted * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available */ - public function historyViewRevisionAction($id = null, $revision = null) + public function historyViewRevisionAction($id = null, $revision = null, Request $request = null) { - $id = $this->get('request')->get($this->admin->getIdParameter()); + $request = $this->resolveRequest($request); + $id = $request->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); @@ -843,7 +902,7 @@ public function historyViewRevisionAction($id = null, $revision = null) 'action' => 'show', 'object' => $object, 'elements' => $this->admin->getShow(), - )); + ), null, $request); } /** @@ -852,19 +911,21 @@ public function historyViewRevisionAction($id = null, $revision = null) * @param int|string|null $id * @param int|string|null $base_revision * @param int|string|null $compare_revision + * @param Request $request * * @return Response * * @throws AccessDeniedException If access is not granted * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available */ - public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null) + public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null, Request $request = null) { + $request = $this->resolveRequest($request); if (false === $this->admin->isGranted('EDIT')) { throw new AccessDeniedException(); } - $id = $this->get('request')->get($this->admin->getIdParameter()); + $id = $request->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); @@ -914,11 +975,11 @@ public function historyCompareRevisionsAction($id = null, $base_revision = null, $this->admin->setSubject($base_object); return $this->render($this->admin->getTemplate('show_compare'), array( - 'action' => 'show', - 'object' => $base_object, - 'object_compare' => $compare_object, - 'elements' => $this->admin->getShow(), - )); + 'action' => 'show', + 'object' => $base_object, + 'object_compare' => $compare_object, + 'elements' => $this->admin->getShow(), + ), null, $request); } /** @@ -931,8 +992,9 @@ public function historyCompareRevisionsAction($id = null, $base_revision = null, * @throws AccessDeniedException If access is not granted * @throws \RuntimeException If the export format is invalid */ - public function exportAction(Request $request) + public function exportAction(Request $request = null) { + $request = $this->resolveRequest($request); if (false === $this->admin->isGranted('EXPORT')) { throw new AccessDeniedException(); } @@ -991,19 +1053,22 @@ protected function getAclUsers() * Returns the Response object associated to the acl action. * * @param int|string|null $id + * @param Request $request * * @return Response|RedirectResponse * * @throws AccessDeniedException If access is not granted. * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled */ - public function aclAction($id = null) + public function aclAction($id = null, Request $request = null) { + $request = $this->resolveRequest($request); + if (!$this->admin->isAclEnabled()) { throw new NotFoundHttpException('ACL are not enabled for this admin'); } - $id = $this->get('request')->get($this->admin->getIdParameter()); + $id = $request->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); @@ -1028,7 +1093,6 @@ public function aclAction($id = null) $form = $adminObjectAclManipulator->createForm($adminObjectAclData); - $request = $this->getRequest(); if ($request->getMethod() === 'POST') { $form->submit($request); @@ -1047,7 +1111,7 @@ public function aclAction($id = null) 'object' => $object, 'users' => $aclUsers, 'form' => $form->createView(), - )); + ), null, $request); } /** @@ -1066,19 +1130,21 @@ protected function addFlash($type, $message) /** * Validate CSRF token for action without form. * - * @param string $intention + * @param string $intention + * @param Request $request * * @throws HttpException */ - protected function validateCsrfToken($intention) + protected function validateCsrfToken($intention, Request $request = null) { + $request = $this->resolveRequest($request); if (!$this->container->has('form.csrf_provider')) { return; } if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid( $intention, - $this->get('request')->request->get('_sonata_csrf_token', false) + $request->request->get('_sonata_csrf_token', false) )) { throw new HttpException(400, 'The csrf token is not valid, CSRF attack?'); } @@ -1111,4 +1177,30 @@ protected function getCsrfToken($intention) return $this->container->get('form.csrf_provider')->generateCsrfToken($intention); } + + /** + * To keep backwards compatibility with older Sonata Admin code. + * + * @internal + */ + private function resolveRequest(Request $request = null) + { + if (null === $request) { + return $this->getRequest(); + } + + return $request; + } + + /** + * @return Request + */ + public function getRequest() + { + if ($this->container->has('request_stack')) { + return $this->container->get('request_stack')->getCurrentRequest(); + } + + return $this->container->get('request'); + } } From ffec3b23dbfedfaa536c8cf0e8242e087dee82ec Mon Sep 17 00:00:00 2001 From: WouterJ Date: Thu, 26 Feb 2015 18:32:52 +0100 Subject: [PATCH 12/21] (2.2) Pattern is deprecated in favor of path --- Command/ExplainAdminCommand.php | 2 +- Resources/config/routing/sonata_admin.xml | 16 ++++++++-------- .../Resources/config/routing/routing.xml | 6 +++--- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Command/ExplainAdminCommand.php b/Command/ExplainAdminCommand.php index 65554844a0..ac4de0099f 100644 --- a/Command/ExplainAdminCommand.php +++ b/Command/ExplainAdminCommand.php @@ -57,7 +57,7 @@ public function execute(InputInterface $input, OutputInterface $output) $output->writeln(''); $output->writeln('Routes'); foreach ($admin->getRoutes()->getElements() as $route) { - $output->writeln(sprintf(' - % -25s %s', $route->getDefault('_sonata_name'), $route->getPattern())); + $output->writeln(sprintf(' - % -25s %s', $route->getDefault('_sonata_name'), $route->getPath())); } $output->writeln(''); diff --git a/Resources/config/routing/sonata_admin.xml b/Resources/config/routing/sonata_admin.xml index 0b54b6691a..bf083109b3 100644 --- a/Resources/config/routing/sonata_admin.xml +++ b/Resources/config/routing/sonata_admin.xml @@ -4,39 +4,39 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd"> - + FrameworkBundle:Redirect:redirect sonata_admin_dashboard true - + SonataAdminBundle:Core:dashboard - + sonata.admin.controller.admin:retrieveFormFieldElementAction - + sonata.admin.controller.admin:appendFormFieldElementAction - + sonata.admin.controller.admin:getShortObjectDescriptionAction html html|json - + sonata.admin.controller.admin:setObjectFieldValueAction - + SonataAdminBundle:Core:search - + sonata.admin.controller.admin:retrieveAutocompleteItemsAction diff --git a/Tests/Fixtures/Resources/config/routing/routing.xml b/Tests/Fixtures/Resources/config/routing/routing.xml index 611f8e16d1..0c1baa4280 100644 --- a/Tests/Fixtures/Resources/config/routing/routing.xml +++ b/Tests/Fixtures/Resources/config/routing/routing.xml @@ -4,15 +4,15 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd"> - + SonataAdminBundle:RouteAdminController:foo - + SonataAdminBundle:RouteAdminController:fooParam - + SonataAdminBundle:RouteAdminController:fooObject From 2631de9879f2a88f50ba96f0ac227bab1ef45182 Mon Sep 17 00:00:00 2001 From: Sullivan SENECHAL Date: Tue, 1 Sep 2015 10:44:11 +0200 Subject: [PATCH 13/21] Fix deprecated autoescape option Using "true" as the default strategy is deprecated. Use "html" instead --- Tests/Twig/Extension/SonataAdminExtensionTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Twig/Extension/SonataAdminExtensionTest.php b/Tests/Twig/Extension/SonataAdminExtensionTest.php index add9e2954e..8bf0f2316a 100644 --- a/Tests/Twig/Extension/SonataAdminExtensionTest.php +++ b/Tests/Twig/Extension/SonataAdminExtensionTest.php @@ -86,7 +86,7 @@ public function setUp() __DIR__.'/../../../Resources/views/CRUD', )); - $this->environment = new \Twig_Environment($loader, array('strict_variables' => true, 'cache' => false, 'autoescape' => true, 'optimizations' => 0)); + $this->environment = new \Twig_Environment($loader, array('strict_variables' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0)); $this->environment->addExtension($this->twigExtension); // translation extension From de9e17f69f75d2c8390e1c7344c339a94708838a Mon Sep 17 00:00:00 2001 From: Sullivan SENECHAL Date: Tue, 1 Sep 2015 11:14:20 +0200 Subject: [PATCH 14/21] Fix deprecated Twig_Environment constructor usage --- Tests/Controller/HelperControllerTest.php | 27 ++++++++++------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/Tests/Controller/HelperControllerTest.php b/Tests/Controller/HelperControllerTest.php index 81d9fb8c6b..5b575a6284 100644 --- a/Tests/Controller/HelperControllerTest.php +++ b/Tests/Controller/HelperControllerTest.php @@ -16,13 +16,10 @@ use Sonata\AdminBundle\Admin\Pool; use Sonata\AdminBundle\Controller\HelperController; use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo; -use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\Validator\ConstraintViolationList; -use Twig_Environment as Twig; -use Twig_ExtensionInterface as Twig_ExtensionInterface; class AdminControllerHelper_Foo { @@ -87,7 +84,7 @@ protected function setUp() $this->admin = $this->getMock('Sonata\AdminBundle\Admin\AdminInterface'); - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $helper = new AdminHelper($pool); $validator = $this->getMock('Symfony\Component\Validator\ValidatorInterface'); $this->controller = new HelperController($twig, $pool, $helper, $validator); @@ -115,7 +112,7 @@ protected function setUp() public function testgetShortObjectDescriptionActionInvalidAdmin() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $request = new Request(array( 'code' => 'sonata.post.admin', 'objectId' => 42, @@ -143,7 +140,7 @@ public function testgetShortObjectDescriptionActionObjectDoesNotExist() $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->any())->method('get')->will($this->returnValue($admin)); - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $request = new Request(array( 'code' => 'sonata.post.admin', 'objectId' => 42, @@ -170,7 +167,7 @@ public function testgetShortObjectDescriptionActionEmptyObjectId() $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->any())->method('get')->will($this->returnValue($admin)); - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $request = new Request(array( 'code' => 'sonata.post.admin', 'objectId' => '', @@ -209,7 +206,7 @@ public function testgetShortObjectDescriptionActionObject() $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->any())->method('get')->will($this->returnValue($admin)); - $twig = $this->getMock('Twig_Environment'); + $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->once())->method('render') ->with($mockTemplate) @@ -254,11 +251,11 @@ public function testsetObjectFieldValueAction() $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->any())->method('get')->will($this->returnValue($admin)); - $adminExtension = $this->getMock('Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); + $adminExtension = $this->getMock('\Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); $adminExtension->expects($this->once())->method('getName')->will($this->returnValue('sonata_admin')); $adminExtension->expects($this->once())->method('renderListElement')->will($this->returnValue('')); - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $twig->addExtension($adminExtension); $request = new Request(array( 'code' => 'sonata.post.admin', @@ -310,14 +307,14 @@ public function testappendFormFieldElementAction() ->method('searchAndRenderBlock') ->will($this->returnValue(new Response())); - $formExtension = $this->getMock('Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); + $formExtension = $this->getMock('\Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); $formExtension->expects($this->once())->method('getName')->will($this->returnValue('form')); $formExtension->expects($this->never())->method('searchAndRenderBlock'); $formExtension->expects($this->never())->method('setTheme'); $formExtension->renderer = $mockRenderer; - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $twig->addExtension($formExtension); $request = new Request(array( 'code' => 'sonata.post.admin', @@ -394,13 +391,13 @@ public function testretrieveFormFieldElementAction() ->method('searchAndRenderBlock') ->will($this->returnValue(new Response())); - $formExtension = $this->getMock('Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); + $formExtension = $this->getMock('\Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); $formExtension->expects($this->once())->method('getName')->will($this->returnValue('form')); $formExtension->expects($this->never())->method('searchAndRenderBlock'); $formExtension->expects($this->never())->method('setTheme'); $formExtension->renderer = $mockRenderer; - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $twig->addExtension($formExtension); $request = new Request(array( 'code' => 'sonata.post.admin', @@ -444,7 +441,7 @@ public function testSetObjectFieldValueActionWithViolations() $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->any())->method('get')->will($this->returnValue($admin)); - $twig = new Twig(); + $twig = new \Twig_Environment($this->getMock('\Twig_LoaderInterface')); $request = new Request(array( 'code' => 'sonata.post.admin', 'objectId' => 42, From 0adc97fb5f8461b555a63183e9378beb63ff3d2e Mon Sep 17 00:00:00 2001 From: WouterJ Date: Thu, 26 Feb 2015 18:24:59 +0100 Subject: [PATCH 15/21] (2.5) ElementMetadata is deprecated in favor of ElementMetadata Sf <2.5 compatibility is taken care of --- Tests/Command/ExplainAdminCommandTest.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Tests/Command/ExplainAdminCommandTest.php b/Tests/Command/ExplainAdminCommandTest.php index b41d0bda84..5d716d3aea 100644 --- a/Tests/Command/ExplainAdminCommandTest.php +++ b/Tests/Command/ExplainAdminCommandTest.php @@ -163,12 +163,19 @@ public function testExecute() ->with($this->equalTo('Acme\Entity\Foo')) ->will($this->returnValue($metadata)); - $propertyMetadata = $this->getMockForAbstractClass('Symfony\Component\Validator\Mapping\ElementMetadata'); - $propertyMetadata->constraints = array(new NotNull(), new Length(array('min' => 2, 'max' => 50, 'groups' => array('create', 'edit')))); + if (class_exists('Symfony\Component\Validator\Mapping\GenericMetadata')) { + $class = 'GenericMetadata'; + } else { + // Symfony <2.5 compatibility + $class = 'ElementMetadata'; + } + + $propertyMetadata = $this->getMockForAbstractClass('Symfony\Component\Validator\Mapping\\'.$class); + $propertyMetadata->constraints = array(new NotNull(), new Length(array('min' => 2, 'max' => 50, 'groups' => array('create', 'edit'),))); $metadata->properties = array('firstName' => $propertyMetadata); - $getterMetadata = $this->getMockForAbstractClass('Symfony\Component\Validator\Mapping\ElementMetadata'); - $getterMetadata->constraints = array(new NotNull(), new Email(array('groups' => array('registration', 'edit')))); + $getterMetadata = $this->getMockForAbstractClass('Symfony\Component\Validator\Mapping\\'.$class); + $getterMetadata->constraints = array(new NotNull(), new Email(array('groups' => array('registration', 'edit'),))); $metadata->getters = array('email' => $getterMetadata); $modelManager = $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'); From fed39e10f65a9b773249a66e60a711045213d3ff Mon Sep 17 00:00:00 2001 From: WouterJ Date: Thu, 26 Feb 2015 18:32:21 +0100 Subject: [PATCH 16/21] (2.0) getRequest() and the request service are deprecated --- Controller/CRUDController.php | 46 ++++-- Controller/CoreController.php | 19 ++- Tests/Controller/CRUDControllerTest.php | 181 ++++++++++++------------ Tests/Controller/CoreControllerTest.php | 4 +- 4 files changed, 140 insertions(+), 110 deletions(-) diff --git a/Controller/CRUDController.php b/Controller/CRUDController.php index 37dd19e015..73f0370fb9 100644 --- a/Controller/CRUDController.php +++ b/Controller/CRUDController.php @@ -38,15 +38,17 @@ class CRUDController extends Controller /** * Render JSON. * - * @param mixed $data - * @param int $status - * @param array $headers + * @param mixed $data + * @param int $status + * @param array $headers + * @param Request $request * * @return Response with json encoded data */ protected function renderJson($data, $status = 200, $headers = array(), Request $request = null) { $request = $this->resolveRequest($request); + // fake content-type so browser does not show the download popup when this // response is rendered through an iframe (used by the jquery.form.js plugin) // => don't know yet if it is the best solution @@ -63,6 +65,8 @@ protected function renderJson($data, $status = 200, $headers = array(), Request /** * Returns true if the request is a XMLHttpRequest. * + * @param Reqeust $request + * * @return bool True if the request is an XMLHttpRequest, false otherwise */ protected function isXmlHttpRequest(Request $request = null) @@ -165,6 +169,8 @@ protected function getLogger() * * @param Request $request * + * @param Request $request + * * @return string The template name */ protected function getBaseTemplate(Request $request = null) @@ -214,6 +220,8 @@ private function logModelManagerException($e) * * @param Request $request * + * @param Request $request + * * @return Response * * @throws AccessDeniedException If access is not granted @@ -298,9 +306,9 @@ public function deleteAction($id, Request $request = null) throw new AccessDeniedException(); } - if ($this->getRestMethod() == 'DELETE') { + if ($this->getRestMethod($request) == 'DELETE') { // check the csrf token - $this->validateCsrfToken('sonata.delete'); + $this->validateCsrfToken('sonata.delete', $request); try { $this->admin->delete($object); @@ -379,7 +387,7 @@ public function editAction($id = null, Request $request = null) $form->setData($object); $form->handleRequest($request); - if ($this->getRestMethod() == 'POST') { + if ($this->getRestMethod($request) == 'POST') { $form->submit($request); $isFormValid = $form->isValid(); @@ -490,6 +498,8 @@ protected function redirectTo($object, Request $request = null) * * @param Request $request * + * @param Request $request + * * @return Response|RedirectResponse * * @throws NotFoundHttpException If the HTTP method is not POST @@ -604,6 +614,8 @@ public function batchAction(Request $request = null) * * @param Request $request * + * @param Request $request + * * @return Response * * @throws AccessDeniedException If access is not granted @@ -626,7 +638,7 @@ public function createAction(Request $request = null) $form = $this->admin->getForm(); $form->setData($object); - if ($this->getRestMethod() == 'POST') { + if ($this->getRestMethod($request) == 'POST') { $form->submit($request); $isFormValid = $form->isValid(); @@ -642,8 +654,8 @@ public function createAction(Request $request = null) if ($this->isXmlHttpRequest($request)) { return $this->renderJson(array( - 'result' => 'ok', - 'objectId' => $this->admin->getNormalizedIdentifier($object), + 'result' => 'ok', + 'objectId' => $this->admin->getNormalizedIdentifier($object) ), 200, array(), $request); } @@ -701,6 +713,8 @@ public function createAction(Request $request = null) * * @param Request $request * + * @param Request $request + * * @return bool */ protected function isPreviewRequested(Request $request = null) @@ -715,6 +729,8 @@ protected function isPreviewRequested(Request $request = null) * * @param Request $request * + * @param Request $request + * * @return bool */ protected function isPreviewApproved(Request $request = null) @@ -749,6 +765,8 @@ protected function isInPreviewMode(Request $request = null) * * @param Request $request * + * @param Request $request + * * @return bool */ protected function isPreviewDeclined(Request $request = null) @@ -835,10 +853,10 @@ public function historyAction($id = null, Request $request = null) $revisions = $reader->findRevisions($this->admin->getClass(), $id); return $this->render($this->admin->getTemplate('history'), array( - 'action' => 'history', - 'object' => $object, - 'revisions' => $revisions, - 'currentRevision' => $revisions ? current($revisions) : false, + 'action' => 'history', + 'object' => $object, + 'revisions' => $revisions, + 'currentRevision' => $revisions ? current($revisions) : false, ), null, $request); } @@ -1142,6 +1160,8 @@ protected function validateCsrfToken($intention, Request $request = null) return; } + $request = $this->resolveRequest($request); + if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid( $intention, $request->request->get('_sonata_csrf_token', false) diff --git a/Controller/CoreController.php b/Controller/CoreController.php index 77180efeed..a37ddcb769 100644 --- a/Controller/CoreController.php +++ b/Controller/CoreController.php @@ -37,11 +37,18 @@ protected function getSearchHandler() } /** + * @param Request $request + * * @return string */ - protected function getBaseTemplate() + protected function getBaseTemplate(Request $request = null) { - if ($this->getRequest()->isXmlHttpRequest()) { + // to be BC + if (null === $request) { + $request = $this->getRequest(); + } + + if ($request->isXmlHttpRequest()) { return $this->getAdminPool()->getTemplate('ajax'); } @@ -49,9 +56,11 @@ protected function getBaseTemplate() } /** + * @param Request $request + * * @return Response */ - public function dashboardAction() + public function dashboardAction(Request $request) { $blocks = array( 'top' => array(), @@ -66,7 +75,7 @@ public function dashboardAction() } return $this->render($this->getAdminPool()->getTemplate('dashboard'), array( - 'base_template' => $this->getBaseTemplate(), + 'base_template' => $this->getBaseTemplate($request), 'admin_pool' => $this->container->get('sonata.admin.pool'), 'blocks' => $blocks, )); @@ -120,7 +129,7 @@ public function searchAction(Request $request) } return $this->render($this->container->get('sonata.admin.pool')->getTemplate('search'), array( - 'base_template' => $this->getBaseTemplate(), + 'base_template' => $this->getBaseTemplate($request), 'admin_pool' => $this->container->get('sonata.admin.pool'), 'query' => $request->get('q'), 'groups' => $this->getAdminPool()->getDashboardGroups(), diff --git a/Tests/Controller/CRUDControllerTest.php b/Tests/Controller/CRUDControllerTest.php index 70bebd130e..5c91846658 100644 --- a/Tests/Controller/CRUDControllerTest.php +++ b/Tests/Controller/CRUDControllerTest.php @@ -184,6 +184,7 @@ protected function setUp() ->getMock(); // php 5.3 BC + $request = $this->request; $auditManager = $this->auditManager; $adminObjectAclManipulator = $this->adminObjectAclManipulator; @@ -224,8 +225,8 @@ protected function setUp() ->method('get') ->will($this->returnCallback(function ($id) use ( $pool, - $request, $admin, + $request, $templating, $twig, $session, @@ -239,10 +240,10 @@ protected function setUp() switch ($id) { case 'sonata.admin.pool': return $pool; - case 'request_stack': - return $requestStack; case 'request': return $request; + case 'request_stack': + return $requestStack; case 'foo.admin': return $admin; case 'templating': @@ -382,7 +383,7 @@ public function testRenderJson1() $data = array('example' => '123', 'foo' => 'bar'); $this->request->headers->set('Content-Type', 'application/x-www-form-urlencoded'); - $response = $this->protectedTestedMethods['renderJson']->invoke($this->controller, $data); + $response = $this->protectedTestedMethods['renderJson']->invoke($this->controller, $data, 200, array(), $this->request); $this->assertSame($response->headers->get('Content-Type'), 'application/json'); $this->assertSame(json_encode($data), $response->getContent()); @@ -393,7 +394,7 @@ public function testRenderJson2() $data = array('example' => '123', 'foo' => 'bar'); $this->request->headers->set('Content-Type', 'multipart/form-data'); - $response = $this->protectedTestedMethods['renderJson']->invoke($this->controller, $data); + $response = $this->protectedTestedMethods['renderJson']->invoke($this->controller, $data, 200, array(), $this->request); $this->assertSame($response->headers->get('Content-Type'), 'application/json'); $this->assertSame(json_encode($data), $response->getContent()); @@ -405,7 +406,7 @@ public function testRenderJsonAjax() $this->request->attributes->set('_xml_http_request', true); $this->request->headers->set('Content-Type', 'multipart/form-data'); - $response = $this->protectedTestedMethods['renderJson']->invoke($this->controller, $data); + $response = $this->protectedTestedMethods['renderJson']->invoke($this->controller, $data, 200, array(), $this->request); $this->assertSame($response->headers->get('Content-Type'), 'text/plain'); $this->assertSame(json_encode($data), $response->getContent()); @@ -413,17 +414,17 @@ public function testRenderJsonAjax() public function testIsXmlHttpRequest() { - $this->assertFalse($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller)); + $this->assertFalse($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller, $this->request)); $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); - $this->assertTrue($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller)); + $this->assertTrue($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller, $this->request)); $this->request->headers->remove('X-Requested-With'); - $this->assertFalse($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller)); + $this->assertFalse($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller, $this->request)); $this->request->attributes->set('_xml_http_request', true); - $this->assertTrue($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller)); + $this->assertTrue($this->protectedTestedMethods['isXmlHttpRequest']->invoke($this->controller, $this->request)); } public function testConfigure() @@ -497,25 +498,25 @@ public function testGetBaseTemplate() { $this->assertSame( 'SonataAdminBundle::standard_layout.html.twig', - $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller) + $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller, $this->request) ); $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); $this->assertSame( 'SonataAdminBundle::ajax_layout.html.twig', - $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller) + $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller, $this->request) ); $this->request->headers->remove('X-Requested-With'); $this->assertSame( 'SonataAdminBundle::standard_layout.html.twig', - $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller) + $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller, $this->request) ); $this->request->attributes->set('_xml_http_request', true); $this->assertSame( 'SonataAdminBundle::ajax_layout.html.twig', - $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller) + $this->protectedTestedMethods['getBaseTemplate']->invoke($this->controller, $this->request) ); } @@ -524,7 +525,7 @@ public function testRender() $this->parameters = array(); $this->assertInstanceOf( 'Symfony\Component\HttpFoundation\Response', - $this->controller->render('FooAdminBundle::foo.html.twig', array()) + $this->controller->render('FooAdminBundle::foo.html.twig', array(), null, $this->request) ); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -537,7 +538,7 @@ public function testRenderWithResponse() $this->parameters = array(); $response = $response = new Response(); $response->headers->set('X-foo', 'bar'); - $responseResult = $this->controller->render('FooAdminBundle::foo.html.twig', array(), $response); + $responseResult = $this->controller->render('FooAdminBundle::foo.html.twig', array(), $response, $this->request); $this->assertSame($response, $responseResult); $this->assertSame('bar', $responseResult->headers->get('X-foo')); @@ -553,7 +554,7 @@ public function testRenderCustomParams() $this->assertInstanceOf( 'Symfony\Component\HttpFoundation\Response', $this->controller->render('FooAdminBundle::foo.html.twig', - array('foo' => 'bar')) + array('foo'=>'bar'), null, $this->request) ); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -566,12 +567,12 @@ public function testRenderAjax() { $this->parameters = array(); $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->render('FooAdminBundle::foo.html.twig', array('foo' => 'bar'))); - $this->assertSame($this->admin, $this->parameters['admin']); - $this->assertSame('SonataAdminBundle::ajax_layout.html.twig', $this->parameters['base_template']); - $this->assertSame($this->pool, $this->parameters['admin_pool']); - $this->assertSame('bar', $this->parameters['foo']); - $this->assertSame('FooAdminBundle::foo.html.twig', $this->template); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->render('FooAdminBundle::foo.html.twig', array('foo'=>'bar'), null, $this->request)); + $this->assertEquals($this->admin, $this->parameters['admin']); + $this->assertEquals('SonataAdminBundle::ajax_layout.html.twig', $this->parameters['base_template']); + $this->assertEquals($this->pool, $this->parameters['admin_pool']); + $this->assertEquals('bar', $this->parameters['foo']); + $this->assertEquals('FooAdminBundle::foo.html.twig', $this->template); } public function testListActionAccessDenied() @@ -583,7 +584,7 @@ public function testListActionAccessDenied() ->with($this->equalTo('LIST')) ->will($this->returnValue(false)); - $this->controller->listAction(); + $this->controller->listAction($this->request); } public function testListAction() @@ -612,7 +613,7 @@ public function testListAction() ->will($this->returnValue($form)); $this->parameters = array(); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->listAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->listAction($this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -712,7 +713,7 @@ public function testShowActionNotFoundException() ->method('getObject') ->will($this->returnValue(false)); - $this->controller->showAction(); + $this->controller->showAction(null, $this->request); } public function testShowActionAccessDenied() @@ -728,7 +729,7 @@ public function testShowActionAccessDenied() ->with($this->equalTo('VIEW')) ->will($this->returnValue(false)); - $this->controller->showAction(); + $this->controller->showAction(null, $this->request); } public function testShowAction() @@ -750,7 +751,7 @@ public function testShowAction() ->method('getShow') ->will($this->returnValue($show)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->showAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->showAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -779,7 +780,7 @@ public function testRedirectTo($expected, $queryParams, $hasActiveSubclass) $this->request->query->set($key, $value); } - $response = $this->protectedTestedMethods['redirectTo']->invoke($this->controller, $object); + $response = $this->protectedTestedMethods['redirectTo']->invoke($this->controller, $object, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); $this->assertSame($expected, $response->getTargetUrl()); } @@ -809,7 +810,7 @@ public function testDeleteActionNotFoundException() ->method('getObject') ->will($this->returnValue(false)); - $this->controller->deleteAction(1); + $this->controller->deleteAction(1, $this->request); } public function testDeleteActionAccessDenied() @@ -825,7 +826,7 @@ public function testDeleteActionAccessDenied() ->with($this->equalTo('DELETE')) ->will($this->returnValue(false)); - $this->controller->deleteAction(1); + $this->controller->deleteAction(1, $this->request); } public function testDeleteAction() @@ -841,7 +842,7 @@ public function testDeleteAction() ->with($this->equalTo('DELETE')) ->will($this->returnValue(true)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->deleteAction(1)); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->deleteAction(1, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -870,7 +871,7 @@ public function testDeleteActionNoCsrfToken() ->with($this->equalTo('DELETE')) ->will($this->returnValue(true)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->deleteAction(1)); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->deleteAction(1, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -902,7 +903,7 @@ public function testDeleteActionAjaxSuccess1() $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.delete'); - $response = $this->controller->deleteAction(1); + $response = $this->controller->deleteAction(1, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); $this->assertSame(json_encode(array('result' => 'ok')), $response->getContent()); @@ -928,7 +929,7 @@ public function testDeleteActionAjaxSuccess2() $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); - $response = $this->controller->deleteAction(1); + $response = $this->controller->deleteAction(1, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); $this->assertSame(json_encode(array('result' => 'ok')), $response->getContent()); @@ -955,7 +956,7 @@ public function testDeleteActionAjaxError() $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.delete'); $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); - $response = $this->controller->deleteAction(1); + $response = $this->controller->deleteAction(1, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); $this->assertSame(json_encode(array('result' => 'error')), $response->getContent()); @@ -989,7 +990,7 @@ public function testDeleteActionSuccess1($expectedToStringValue, $toStringValue) $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.delete'); - $response = $this->controller->deleteAction(1); + $response = $this->controller->deleteAction(1, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); $this->assertSame(array('flash_delete_success'), $this->session->getFlashBag()->get('sonata_flash_success')); @@ -1024,7 +1025,7 @@ public function testDeleteActionSuccess2($expectedToStringValue, $toStringValue) $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.delete'); - $response = $this->controller->deleteAction(1); + $response = $this->controller->deleteAction(1, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); $this->assertSame(array('flash_delete_success'), $this->session->getFlashBag()->get('sonata_flash_success')); @@ -1059,7 +1060,7 @@ public function testDeleteActionSuccessNoCsrfTokenProvider($expectedToStringValu $this->request->setMethod('POST'); $this->request->request->set('_method', 'DELETE'); - $response = $this->controller->deleteAction(1); + $response = $this->controller->deleteAction(1, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); $this->assertSame(array('flash_delete_success'), $this->session->getFlashBag()->get('sonata_flash_success')); @@ -1082,7 +1083,7 @@ public function testDeleteActionWrongRequestMethod() //without POST request parameter "_method" should not be used as real REST method $this->request->query->set('_method', 'DELETE'); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->deleteAction(1)); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->deleteAction(1, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -1124,7 +1125,7 @@ public function testDeleteActionError($expectedToStringValue, $toStringValue) $this->request->setMethod('DELETE'); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.delete'); - $response = $this->controller->deleteAction(1); + $response = $this->controller->deleteAction(1, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); $this->assertSame(array('flash_delete_error'), $this->session->getFlashBag()->get('sonata_flash_error')); @@ -1149,7 +1150,7 @@ public function testDeleteActionInvalidCsrfToken() $this->request->request->set('_sonata_csrf_token', 'CSRF-INVALID'); try { - $this->controller->deleteAction(1); + $this->controller->deleteAction(1, $this->request); } catch (HttpException $e) { $this->assertSame('The csrf token is not valid, CSRF attack?', $e->getMessage()); $this->assertSame(400, $e->getStatusCode()); @@ -1164,7 +1165,7 @@ public function testEditActionNotFoundException() ->method('getObject') ->will($this->returnValue(false)); - $this->controller->editAction(); + $this->controller->editAction(null, $this->request); } public function testEditActionAccessDenied() @@ -1180,7 +1181,7 @@ public function testEditActionAccessDenied() ->with($this->equalTo('EDIT')) ->will($this->returnValue(false)); - $this->controller->editAction(); + $this->controller->editAction(null, $this->request); } public function testEditAction() @@ -1210,7 +1211,7 @@ public function testEditAction() ->method('createView') ->will($this->returnValue($formView)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -1264,7 +1265,7 @@ public function testEditActionSuccess($expectedToStringValue, $toStringValue) $this->request->setMethod('POST'); - $response = $this->controller->editAction(); + $response = $this->controller->editAction(null, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); $this->assertSame(array('flash_edit_success'), $this->session->getFlashBag()->get('sonata_flash_success')); @@ -1314,7 +1315,7 @@ public function testEditActionError($expectedToStringValue, $toStringValue) ->method('createView') ->will($this->returnValue($formView)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -1365,7 +1366,7 @@ public function testEditActionAjaxSuccess() $this->request->setMethod('POST'); $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); - $response = $this->controller->editAction(); + $response = $this->controller->editAction(null, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); $this->assertSame(json_encode(array('result' => 'ok', 'objectId' => 'foo_normalized')), $response->getContent()); @@ -1406,7 +1407,7 @@ public function testEditActionAjaxError() ->method('createView') ->will($this->returnValue($formView)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::ajax_layout.html.twig', $this->parameters['base_template']); @@ -1458,7 +1459,7 @@ public function testEditActionWithPreview() $this->request->setMethod('POST'); $this->request->request->set('btn_preview', 'Preview'); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->editAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -1481,7 +1482,7 @@ public function testCreateActionAccessDenied() ->with($this->equalTo('CREATE')) ->will($this->returnValue(false)); - $this->controller->createAction(); + $this->controller->createAction($this->request); } public function testCreateAction() @@ -1511,7 +1512,7 @@ public function testCreateAction() ->method('createView') ->will($this->returnValue($formView)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction($this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -1575,7 +1576,7 @@ public function testCreateActionSuccess($expectedToStringValue, $toStringValue) $this->request->setMethod('POST'); - $response = $this->controller->createAction(); + $response = $this->controller->createAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); $this->assertSame(array('flash_create_success'), $this->session->getFlashBag()->get('sonata_flash_success')); @@ -1619,7 +1620,7 @@ public function testCreateActionAccessDenied2() $this->request->setMethod('POST'); - $this->controller->createAction(); + $this->controller->createAction($this->request); } /** @@ -1665,7 +1666,7 @@ public function testCreateActionError($expectedToStringValue, $toStringValue) ->method('createView') ->will($this->returnValue($formView)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction($this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -1725,7 +1726,7 @@ public function testCreateActionAjaxSuccess() $this->request->setMethod('POST'); $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); - $response = $this->controller->createAction(); + $response = $this->controller->createAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); $this->assertSame(json_encode(array('result' => 'ok', 'objectId' => 'foo_normalized')), $response->getContent()); @@ -1766,7 +1767,7 @@ public function testCreateActionAjaxError() ->method('createView') ->will($this->returnValue($formView)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction($this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::ajax_layout.html.twig', $this->parameters['base_template']); @@ -1818,7 +1819,7 @@ public function testCreateActionWithPreview() $this->request->setMethod('POST'); $this->request->request->set('btn_preview', 'Preview'); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->createAction($this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -1904,7 +1905,7 @@ public function testHistoryActionAccessDenied() ->with($this->equalTo('EDIT')) ->will($this->returnValue(false)); - $this->controller->historyAction(); + $this->controller->historyAction(null, $this->request); } public function testHistoryActionNotFoundException() @@ -1915,7 +1916,7 @@ public function testHistoryActionNotFoundException() ->method('getObject') ->will($this->returnValue(false)); - $this->controller->historyAction(); + $this->controller->historyAction(null, $this->request); } public function testHistoryActionNoReader() @@ -1944,7 +1945,7 @@ public function testHistoryActionNoReader() ->with($this->equalTo('Foo')) ->will($this->returnValue(false)); - $this->controller->historyAction(); + $this->controller->historyAction(null, $this->request); } public function testHistoryAction() @@ -1983,7 +1984,7 @@ public function testHistoryAction() ->with($this->equalTo('Foo'), $this->equalTo(123)) ->will($this->returnValue(array())); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->historyAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->historyAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -2001,7 +2002,7 @@ public function testAclActionAclNotEnabled() { $this->setExpectedException('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', 'ACL are not enabled for this admin'); - $this->controller->aclAction(); + $this->controller->aclAction(null, $this->request); } public function testAclActionNotFoundException() @@ -2016,7 +2017,7 @@ public function testAclActionNotFoundException() ->method('getObject') ->will($this->returnValue(false)); - $this->controller->aclAction(); + $this->controller->aclAction(null, $this->request); } public function testAclActionAccessDenied() @@ -2038,7 +2039,7 @@ public function testAclActionAccessDenied() ->with($this->equalTo('MASTER'), $this->equalTo($object)) ->will($this->returnValue(false)); - $this->controller->aclAction(); + $this->controller->aclAction(null, $this->request); } public function testAclAction() @@ -2088,7 +2089,7 @@ public function testAclAction() ->method('getSecurityHandler') ->will($this->returnValue($aclSecurityHandler)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->aclAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->aclAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -2157,7 +2158,7 @@ public function testAclActionInvalidUpdate() $this->request->setMethod('POST'); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->aclAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->aclAction(null, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -2226,7 +2227,7 @@ public function testAclActionSuccessfulUpdate() $this->request->setMethod('POST'); - $response = $this->controller->aclAction(); + $response = $this->controller->aclAction(null, $this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); @@ -2247,7 +2248,7 @@ public function testHistoryViewRevisionActionAccessDenied() ->with($this->equalTo('EDIT')) ->will($this->returnValue(false)); - $this->controller->historyViewRevisionAction(); + $this->controller->historyViewRevisionAction(null, null, $this->request); } public function testHistoryViewRevisionActionNotFoundException() @@ -2260,7 +2261,7 @@ public function testHistoryViewRevisionActionNotFoundException() ->method('getObject') ->will($this->returnValue(false)); - $this->controller->historyViewRevisionAction(); + $this->controller->historyViewRevisionAction(null, null, $this->request); } public function testHistoryViewRevisionActionNoReader() @@ -2289,7 +2290,7 @@ public function testHistoryViewRevisionActionNoReader() ->with($this->equalTo('Foo')) ->will($this->returnValue(false)); - $this->controller->historyViewRevisionAction(); + $this->controller->historyViewRevisionAction(null, null, $this->request); } public function testHistoryViewRevisionActionNotFoundRevision() @@ -2330,7 +2331,7 @@ public function testHistoryViewRevisionActionNotFoundRevision() ->with($this->equalTo('Foo'), $this->equalTo(123), $this->equalTo(456)) ->will($this->returnValue(null)); - $this->controller->historyViewRevisionAction(123, 456); + $this->controller->historyViewRevisionAction(123, 456, $this->request); } public function testHistoryViewRevisionAction() @@ -2382,7 +2383,7 @@ public function testHistoryViewRevisionAction() ->method('getShow') ->will($this->returnValue($fieldDescriptionCollection)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->historyViewRevisionAction(123, 456)); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->historyViewRevisionAction(123, 456, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -2405,7 +2406,7 @@ public function testhistoryCompareRevisionsActionAccessDenied() ->with($this->equalTo('EDIT')) ->will($this->returnValue(false)); - $this->controller->historyCompareRevisionsAction(); + $this->controller->historyCompareRevisionsAction(null, null, null, $this->request); } public function testhistoryCompareRevisionsActionNotFoundException() @@ -2423,7 +2424,7 @@ public function testhistoryCompareRevisionsActionNotFoundException() ->method('getObject') ->will($this->returnValue(false)); - $this->controller->historyCompareRevisionsAction(); + $this->controller->historyCompareRevisionsAction(null, null, null, $this->request); } public function testhistoryCompareRevisionsActionNoReader() @@ -2452,7 +2453,7 @@ public function testhistoryCompareRevisionsActionNoReader() ->with($this->equalTo('Foo')) ->will($this->returnValue(false)); - $this->controller->historyCompareRevisionsAction(); + $this->controller->historyCompareRevisionsAction(null, null, null, $this->request); } public function testhistoryCompareRevisionsActionNotFoundBaseRevision() @@ -2494,7 +2495,7 @@ public function testhistoryCompareRevisionsActionNotFoundBaseRevision() ->with($this->equalTo('Foo'), $this->equalTo(123), $this->equalTo(456)) ->will($this->returnValue(null)); - $this->controller->historyCompareRevisionsAction(123, 456, 789); + $this->controller->historyCompareRevisionsAction(123, 456, 789, $this->request); } public function testhistoryCompareRevisionsActionNotFoundCompareRevision() @@ -2544,7 +2545,7 @@ public function testhistoryCompareRevisionsActionNotFoundCompareRevision() ->with($this->equalTo('Foo'), $this->equalTo(123), $this->equalTo(789)) ->will($this->returnValue(null)); - $this->controller->historyCompareRevisionsAction(123, 456, 789); + $this->controller->historyCompareRevisionsAction(123, 456, 789, $this->request); } public function testhistoryCompareRevisionsActionAction() @@ -2604,7 +2605,7 @@ public function testhistoryCompareRevisionsActionAction() ->method('getShow') ->will($this->returnValue($fieldDescriptionCollection)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->historyCompareRevisionsAction(123, 456, 789)); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->historyCompareRevisionsAction(123, 456, 789, $this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -2623,7 +2624,7 @@ public function testBatchActionWrongMethod() { $this->setExpectedException('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', 'Invalid request type "GET", POST expected'); - $this->controller->batchAction(); + $this->controller->batchAction($this->request); } public function testBatchActionActionNotDefined() @@ -2640,7 +2641,7 @@ public function testBatchActionActionNotDefined() $this->request->request->set('data', json_encode(array('action' => 'foo', 'idx' => array('123', '456'), 'all_elements' => false))); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $this->controller->batchAction(); + $this->controller->batchAction($this->request); } public function testBatchActionActionInvalidCsrfToken() @@ -2650,7 +2651,7 @@ public function testBatchActionActionInvalidCsrfToken() $this->request->request->set('_sonata_csrf_token', 'CSRF-INVALID'); try { - $this->controller->batchAction(); + $this->controller->batchAction($this->request); } catch (HttpException $e) { $this->assertSame('The csrf token is not valid, CSRF attack?', $e->getMessage()); $this->assertSame(400, $e->getStatusCode()); @@ -2676,7 +2677,7 @@ public function testBatchActionMethodNotExist() $this->request->request->set('data', json_encode(array('action' => 'foo', 'idx' => array('123', '456'), 'all_elements' => false))); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $this->controller->batchAction(); + $this->controller->batchAction($this->request); } public function testBatchActionWithoutConfirmation() @@ -2722,7 +2723,7 @@ public function testBatchActionWithoutConfirmation() $this->request->request->set('data', json_encode(array('action' => 'delete', 'idx' => array('123', '456'), 'all_elements' => false))); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $result = $this->controller->batchAction(); + $result = $this->controller->batchAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $result); $this->assertSame(array('flash_batch_delete_success'), $this->session->getFlashBag()->get('sonata_flash_success')); @@ -2773,7 +2774,7 @@ public function testBatchActionWithoutConfirmation2() $this->request->request->set('idx', array('123', '456')); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $result = $this->controller->batchAction(); + $result = $this->controller->batchAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $result); $this->assertSame(array('flash_batch_delete_success'), $this->session->getFlashBag()->get('sonata_flash_success')); @@ -2812,7 +2813,7 @@ public function testBatchActionWithConfirmation() ->method('getForm') ->will($this->returnValue($form)); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->batchAction()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->batchAction($this->request)); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -2851,7 +2852,7 @@ public function testBatchActionNonRelevantAction() $this->request->request->set('idx', array('789')); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $result = $controller->batchAction(); + $result = $controller->batchAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $result); $this->assertSame(array('flash_batch_empty'), $this->session->getFlashBag()->get('sonata_flash_info')); @@ -2880,7 +2881,7 @@ public function testBatchActionNonRelevantAction2() $this->request->request->set('idx', array('999')); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $result = $controller->batchAction(); + $result = $controller->batchAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $result); $this->assertSame(array('flash_foo_error'), $this->session->getFlashBag()->get('sonata_flash_info')); @@ -2906,7 +2907,7 @@ public function testBatchActionNoItems() $this->request->request->set('idx', array()); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $result = $this->controller->batchAction(); + $result = $this->controller->batchAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $result); $this->assertSame(array('flash_batch_empty'), $this->session->getFlashBag()->get('sonata_flash_info')); @@ -2950,7 +2951,7 @@ public function testBatchActionNoItemsEmptyQuery() $this->request->request->set('idx', array()); $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); - $result = $controller->batchAction(); + $result = $controller->batchAction($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $result); $this->assertSame('batchActionBar executed', $result->getContent()); diff --git a/Tests/Controller/CoreControllerTest.php b/Tests/Controller/CoreControllerTest.php index 42e5718d2f..1b4da185cb 100644 --- a/Tests/Controller/CoreControllerTest.php +++ b/Tests/Controller/CoreControllerTest.php @@ -66,7 +66,7 @@ public function testdashboardActionStandardRequest() $controller = new CoreController(); $controller->setContainer($container); - $response = $controller->dashboardAction(); + $response = $controller->dashboardAction($request); $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response); } @@ -120,7 +120,7 @@ public function testdashboardActionAjaxLayout() $controller = new CoreController(); $controller->setContainer($container); - $response = $controller->dashboardAction(); + $response = $controller->dashboardAction($request); $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response); } From 73d9b831f5b6c6f68ff23e7cf55ee012d84297f3 Mon Sep 17 00:00:00 2001 From: Sullivan SENECHAL Date: Tue, 1 Sep 2015 11:06:20 +0200 Subject: [PATCH 17/21] Better handling of deprecated inline view action --- Datagrid/ListMapper.php | 2 +- Tests/Datagrid/ListMapperTest.php | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Datagrid/ListMapper.php b/Datagrid/ListMapper.php index d035b3221b..990ac105f2 100644 --- a/Datagrid/ListMapper.php +++ b/Datagrid/ListMapper.php @@ -72,7 +72,7 @@ public function add($name, $type = null, array $fieldDescriptionOptions = array( // Change deprecated inline action "view" to "show" if ($name == '_action' && $type == 'actions') { if (isset($fieldDescriptionOptions['actions']['view'])) { - @trigger_error('Inline action "view" is deprecated since version 2.2.4. Use inline action "show" instead.', E_USER_DEPRECATED); + @trigger_error('Inline action "view" is deprecated since version 2.2.4 and will be removed in 3.0. Use inline action "show" instead.', E_USER_DEPRECATED); $fieldDescriptionOptions['actions']['show'] = $fieldDescriptionOptions['actions']['view']; diff --git a/Tests/Datagrid/ListMapperTest.php b/Tests/Datagrid/ListMapperTest.php index 07eb330321..5020e5632b 100644 --- a/Tests/Datagrid/ListMapperTest.php +++ b/Tests/Datagrid/ListMapperTest.php @@ -119,7 +119,10 @@ public function testAdd() $this->assertSame('fooName', $fieldDescription->getOption('label')); } - public function testAddViewInlineAction() + /** + * @group legacy + */ + public function testLegacyAddViewInlineAction() { $this->assertFalse($this->listMapper->has('_action')); $this->listMapper->add('_action', 'actions', array('actions' => array('view' => array()))); @@ -134,6 +137,21 @@ public function testAddViewInlineAction() $this->assertSame(array('show' => array()), $fieldDescription->getOption('actions')); } + public function testAddViewInlineAction() + { + $this->assertFalse($this->listMapper->has('_action')); + $this->listMapper->add('_action', 'actions', array('actions' => array('show' => array()))); + + $this->assertTrue($this->listMapper->has('_action')); + + $fieldDescription = $this->listMapper->get('_action'); + + $this->assertInstanceOf('Sonata\AdminBundle\Admin\FieldDescriptionInterface', $fieldDescription); + $this->assertSame('_action', $fieldDescription->getName()); + $this->assertCount(1, $fieldDescription->getOption('actions')); + $this->assertSame(array('show' => array()), $fieldDescription->getOption('actions')); + } + public function testAddRemove() { $this->assertFalse($this->listMapper->has('fooName')); From 5a71dc975d366245a7e6fcc6e08e4bc68a45e5cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Wed, 16 Mar 2016 21:29:14 +0100 Subject: [PATCH 18/21] add the setUp method to the legacy group It contains BC code that will trigger deprecation notices. --- Tests/Form/DataTransformer/ModelsToArrayTransformerTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Tests/Form/DataTransformer/ModelsToArrayTransformerTest.php b/Tests/Form/DataTransformer/ModelsToArrayTransformerTest.php index fbf828ef1f..0af1d5ed7d 100644 --- a/Tests/Form/DataTransformer/ModelsToArrayTransformerTest.php +++ b/Tests/Form/DataTransformer/ModelsToArrayTransformerTest.php @@ -26,6 +26,9 @@ class ModelsToArrayTransformerTest extends \PHPUnit_Framework_TestCase private $modelManager; + /** + * @group legacy + */ public function setUp() { $this->modelChoiceList = $this->getMockBuilder('Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList') From 20d924b71e419490d42e47274f3439a034eb12b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Wed, 16 Mar 2016 21:44:45 +0100 Subject: [PATCH 19/21] cs --- Controller/CRUDController.php | 18 ++---------------- Tests/Command/ExplainAdminCommandTest.php | 4 ++-- Tests/Controller/CRUDControllerTest.php | 14 +++++++------- 3 files changed, 11 insertions(+), 25 deletions(-) diff --git a/Controller/CRUDController.php b/Controller/CRUDController.php index 73f0370fb9..ab5ecc107c 100644 --- a/Controller/CRUDController.php +++ b/Controller/CRUDController.php @@ -169,8 +169,6 @@ protected function getLogger() * * @param Request $request * - * @param Request $request - * * @return string The template name */ protected function getBaseTemplate(Request $request = null) @@ -220,8 +218,6 @@ private function logModelManagerException($e) * * @param Request $request * - * @param Request $request - * * @return Response * * @throws AccessDeniedException If access is not granted @@ -498,8 +494,6 @@ protected function redirectTo($object, Request $request = null) * * @param Request $request * - * @param Request $request - * * @return Response|RedirectResponse * * @throws NotFoundHttpException If the HTTP method is not POST @@ -614,8 +608,6 @@ public function batchAction(Request $request = null) * * @param Request $request * - * @param Request $request - * * @return Response * * @throws AccessDeniedException If access is not granted @@ -654,8 +646,8 @@ public function createAction(Request $request = null) if ($this->isXmlHttpRequest($request)) { return $this->renderJson(array( - 'result' => 'ok', - 'objectId' => $this->admin->getNormalizedIdentifier($object) + 'result' => 'ok', + 'objectId' => $this->admin->getNormalizedIdentifier($object), ), 200, array(), $request); } @@ -713,8 +705,6 @@ public function createAction(Request $request = null) * * @param Request $request * - * @param Request $request - * * @return bool */ protected function isPreviewRequested(Request $request = null) @@ -729,8 +719,6 @@ protected function isPreviewRequested(Request $request = null) * * @param Request $request * - * @param Request $request - * * @return bool */ protected function isPreviewApproved(Request $request = null) @@ -765,8 +753,6 @@ protected function isInPreviewMode(Request $request = null) * * @param Request $request * - * @param Request $request - * * @return bool */ protected function isPreviewDeclined(Request $request = null) diff --git a/Tests/Command/ExplainAdminCommandTest.php b/Tests/Command/ExplainAdminCommandTest.php index 5d716d3aea..48a747ba07 100644 --- a/Tests/Command/ExplainAdminCommandTest.php +++ b/Tests/Command/ExplainAdminCommandTest.php @@ -171,11 +171,11 @@ public function testExecute() } $propertyMetadata = $this->getMockForAbstractClass('Symfony\Component\Validator\Mapping\\'.$class); - $propertyMetadata->constraints = array(new NotNull(), new Length(array('min' => 2, 'max' => 50, 'groups' => array('create', 'edit'),))); + $propertyMetadata->constraints = array(new NotNull(), new Length(array('min' => 2, 'max' => 50, 'groups' => array('create', 'edit')))); $metadata->properties = array('firstName' => $propertyMetadata); $getterMetadata = $this->getMockForAbstractClass('Symfony\Component\Validator\Mapping\\'.$class); - $getterMetadata->constraints = array(new NotNull(), new Email(array('groups' => array('registration', 'edit'),))); + $getterMetadata->constraints = array(new NotNull(), new Email(array('groups' => array('registration', 'edit')))); $metadata->getters = array('email' => $getterMetadata); $modelManager = $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'); diff --git a/Tests/Controller/CRUDControllerTest.php b/Tests/Controller/CRUDControllerTest.php index 5c91846658..324efe4991 100644 --- a/Tests/Controller/CRUDControllerTest.php +++ b/Tests/Controller/CRUDControllerTest.php @@ -554,7 +554,7 @@ public function testRenderCustomParams() $this->assertInstanceOf( 'Symfony\Component\HttpFoundation\Response', $this->controller->render('FooAdminBundle::foo.html.twig', - array('foo'=>'bar'), null, $this->request) + array('foo' => 'bar'), null, $this->request) ); $this->assertSame($this->admin, $this->parameters['admin']); $this->assertSame('SonataAdminBundle::standard_layout.html.twig', $this->parameters['base_template']); @@ -567,12 +567,12 @@ public function testRenderAjax() { $this->parameters = array(); $this->request->headers->set('X-Requested-With', 'XMLHttpRequest'); - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->render('FooAdminBundle::foo.html.twig', array('foo'=>'bar'), null, $this->request)); - $this->assertEquals($this->admin, $this->parameters['admin']); - $this->assertEquals('SonataAdminBundle::ajax_layout.html.twig', $this->parameters['base_template']); - $this->assertEquals($this->pool, $this->parameters['admin_pool']); - $this->assertEquals('bar', $this->parameters['foo']); - $this->assertEquals('FooAdminBundle::foo.html.twig', $this->template); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $this->controller->render('FooAdminBundle::foo.html.twig', array('foo' => 'bar'), null, $this->request)); + $this->assertSame($this->admin, $this->parameters['admin']); + $this->assertSame('SonataAdminBundle::ajax_layout.html.twig', $this->parameters['base_template']); + $this->assertSame($this->pool, $this->parameters['admin_pool']); + $this->assertSame('bar', $this->parameters['foo']); + $this->assertSame('FooAdminBundle::foo.html.twig', $this->template); } public function testListActionAccessDenied() From dcb47ba227d703059d51e205e5d8f92964707b52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Wed, 16 Mar 2016 21:54:48 +0100 Subject: [PATCH 20/21] drop initRuntime() in favor of needs_environment --- .../Extension/SonataAdminExtensionTest.php | 14 +++--- Twig/Extension/SonataAdminExtension.php | 46 +++++++------------ 2 files changed, 23 insertions(+), 37 deletions(-) diff --git a/Tests/Twig/Extension/SonataAdminExtensionTest.php b/Tests/Twig/Extension/SonataAdminExtensionTest.php index 8bf0f2316a..d68f19f519 100644 --- a/Tests/Twig/Extension/SonataAdminExtensionTest.php +++ b/Tests/Twig/Extension/SonataAdminExtensionTest.php @@ -108,8 +108,6 @@ public function setUp() $this->environment->addExtension(new RoutingExtension($urlGenerator)); $this->environment->addExtension(new \Twig_Extensions_Extension_Text()); - $this->twigExtension->initRuntime($this->environment); - // initialize object $this->object = new \stdClass(); @@ -227,7 +225,7 @@ public function testRenderListElement($expected, $type, $value, array $options) } })); - $this->assertSame($expected, trim(preg_replace('/\s+/', ' ', $this->twigExtension->renderListElement($this->object, $this->fieldDescription)))); + $this->assertSame($expected, trim(preg_replace('/\s+/', ' ', $this->twigExtension->renderListElement($this->environment, $this->object, $this->fieldDescription)))); } public function getRenderListElementTests() @@ -381,7 +379,7 @@ public function testRenderListElementNonExistentTemplate() ->method('warning') ->with(($this->stringStartsWith('An error occured trying to load the template "SonataAdminBundle:CRUD:list_nonexistent_template.html.twig" for the field "Foo_name", the default template "SonataAdminBundle:CRUD:base_list_field.html.twig" was used instead: "Unable to find template "list_nonexistent_template.html.twig'))); - $this->twigExtension->renderListElement($this->object, $this->fieldDescription); + $this->twigExtension->renderListElement($this->environment, $this->object, $this->fieldDescription); } /** @@ -399,7 +397,7 @@ public function testRenderListElementErrorLoadingTemplate() ->method('getTemplate') ->will($this->returnValue('SonataAdminBundle:CRUD:list_nonexistent_template.html.twig')); - $this->twigExtension->renderListElement($this->object, $this->fieldDescription); + $this->twigExtension->renderListElement($this->environment, $this->object, $this->fieldDescription); } /** @@ -460,7 +458,7 @@ public function testRenderViewElement($expected, $type, $value, array $options) } })); - $this->assertSame($expected, trim(preg_replace('/\s+/', ' ', $this->twigExtension->renderViewElement($this->fieldDescription, $this->object)))); + $this->assertSame($expected, trim(preg_replace('/\s+/', ' ', $this->twigExtension->renderViewElement($this->environment, $this->fieldDescription, $this->object)))); } public function getRenderViewElementTests() @@ -675,11 +673,11 @@ public function testOutput() $template = $this->environment->loadTemplate('SonataAdminBundle:CRUD:base_list_field.html.twig'); $this->assertSame(' foo ', - trim(preg_replace('/\s+/', ' ', $this->twigExtension->output($this->fieldDescription, $template, $parameters)))); + trim(preg_replace('/\s+/', ' ', $this->twigExtension->output($this->fieldDescription, $template, $parameters, $this->environment)))); $this->environment->enableDebug(); $this->assertSame(' foo ', - trim(preg_replace('/\s+/', ' ', $this->twigExtension->output($this->fieldDescription, $template, $parameters)))); + trim(preg_replace('/\s+/', ' ', $this->twigExtension->output($this->fieldDescription, $template, $parameters, $this->environment)))); } public function testRenderRelationElementNoObject() diff --git a/Twig/Extension/SonataAdminExtension.php b/Twig/Extension/SonataAdminExtension.php index fda79f7b9f..4d4946b763 100644 --- a/Twig/Extension/SonataAdminExtension.php +++ b/Twig/Extension/SonataAdminExtension.php @@ -17,14 +17,10 @@ use Sonata\AdminBundle\Admin\Pool; use Sonata\AdminBundle\Exception\NoValueException; use Symfony\Component\PropertyAccess\PropertyAccess; +use Twig_Environment; class SonataAdminExtension extends \Twig_Extension { - /** - * @var \Twig_Environment - */ - protected $environment; - /** * @var Pool */ @@ -45,22 +41,14 @@ public function __construct(Pool $pool, LoggerInterface $logger = null) $this->logger = $logger; } - /** - * {@inheritdoc} - */ - public function initRuntime(\Twig_Environment $environment) - { - $this->environment = $environment; - } - /** * {@inheritdoc} */ public function getFilters() { return array( - new \Twig_SimpleFilter('render_list_element', array($this, 'renderListElement'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('render_view_element', array($this, 'renderViewElement'), array('is_safe' => array('html'))), + new \Twig_SimpleFilter('render_list_element', array($this, 'renderListElement'), array('is_safe' => array('html'), 'needs_environment' => true)), + new \Twig_SimpleFilter('render_view_element', array($this, 'renderViewElement'), array('is_safe' => array('html'), 'needs_environment' => true)), new \Twig_SimpleFilter('render_view_element_compare', array($this, 'renderViewElementCompare'), array('is_safe' => array('html'))), new \Twig_SimpleFilter('render_relation_element', array($this, 'renderRelationElement')), new \Twig_SimpleFilter('sonata_urlsafeid', array($this, 'getUrlsafeIdentifier')), @@ -84,14 +72,14 @@ public function getName() * * @return \Twig_Template */ - protected function getTemplate(FieldDescriptionInterface $fieldDescription, $defaultTemplate) + protected function getTemplate(FieldDescriptionInterface $fieldDescription, $defaultTemplate, Twig_Environment $environment) { $templateName = $fieldDescription->getTemplate() ?: $defaultTemplate; try { - $template = $this->environment->loadTemplate($templateName); + $template = $environment->loadTemplate($templateName); } catch (\Twig_Error_Loader $e) { - $template = $this->environment->loadTemplate($defaultTemplate); + $template = $environment->loadTemplate($defaultTemplate); if (null !== $this->logger) { $this->logger->warning(sprintf('An error occured trying to load the template "%s" for the field "%s", the default template "%s" was used instead: "%s". ', $templateName, $fieldDescription->getFieldName(), $defaultTemplate, $e->getMessage())); @@ -110,16 +98,16 @@ protected function getTemplate(FieldDescriptionInterface $fieldDescription, $def * * @return string */ - public function renderListElement($object, FieldDescriptionInterface $fieldDescription, $params = array()) + public function renderListElement(Twig_Environment $environment, $object, FieldDescriptionInterface $fieldDescription, $params = array()) { - $template = $this->getTemplate($fieldDescription, $fieldDescription->getAdmin()->getTemplate('base_list_field')); + $template = $this->getTemplate($fieldDescription, $fieldDescription->getAdmin()->getTemplate('base_list_field'), $environment); return $this->output($fieldDescription, $template, array_merge($params, array( 'admin' => $fieldDescription->getAdmin(), 'object' => $object, 'value' => $this->getValueFromFieldDescription($object, $fieldDescription), 'field_description' => $fieldDescription, - ))); + )), $environment); } /** @@ -129,11 +117,11 @@ public function renderListElement($object, FieldDescriptionInterface $fieldDescr * * @return string */ - public function output(FieldDescriptionInterface $fieldDescription, \Twig_Template $template, array $parameters = array()) + public function output(FieldDescriptionInterface $fieldDescription, \Twig_Template $template, array $parameters = array(), Twig_Environment $environment) { $content = $template->render($parameters); - if ($this->environment->isDebug()) { + if ($environment->isDebug()) { return sprintf("\n\n%s\n", $fieldDescription->getFieldName(), $fieldDescription->getTemplate(), @@ -184,9 +172,9 @@ public function getValueFromFieldDescription($object, FieldDescriptionInterface * * @return string */ - public function renderViewElement(FieldDescriptionInterface $fieldDescription, $object) + public function renderViewElement(Twig_Environment $environment, FieldDescriptionInterface $fieldDescription, $object) { - $template = $this->getTemplate($fieldDescription, 'SonataAdminBundle:CRUD:base_show_field.html.twig'); + $template = $this->getTemplate($fieldDescription, 'SonataAdminBundle:CRUD:base_show_field.html.twig', $environment); try { $value = $fieldDescription->getValue($object); @@ -199,7 +187,7 @@ public function renderViewElement(FieldDescriptionInterface $fieldDescription, $ 'object' => $object, 'value' => $value, 'admin' => $fieldDescription->getAdmin(), - )); + ), $environment); } /** @@ -211,9 +199,9 @@ public function renderViewElement(FieldDescriptionInterface $fieldDescription, $ * * @return string */ - public function renderViewElementCompare(FieldDescriptionInterface $fieldDescription, $baseObject, $compareObject) + public function renderViewElementCompare(Twig_Environment $environment, FieldDescriptionInterface $fieldDescription, $baseObject, $compareObject) { - $template = $this->getTemplate($fieldDescription, 'SonataAdminBundle:CRUD:base_show_field.html.twig'); + $template = $this->getTemplate($fieldDescription, 'SonataAdminBundle:CRUD:base_show_field.html.twig', $environment); try { $baseValue = $fieldDescription->getValue($baseObject); @@ -248,7 +236,7 @@ public function renderViewElementCompare(FieldDescriptionInterface $fieldDescrip 'value_compare' => $compareValue, 'is_diff' => $isDiff, 'admin' => $fieldDescription->getAdmin(), - )); + ), $environment); } /** From ffa8d5db1874da604e46f7cbcf228fcc19f9761f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Vasseur?= Date: Thu, 24 Mar 2016 15:44:29 +0100 Subject: [PATCH 21/21] Remove method expectations These methods do not actually exist on the mock object, which means we will get an error anyway if they are called. Recent versions of phpunit forbid configuring inexistant methods in mocks, which makes tests fail. See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/299 --- Tests/Controller/HelperControllerTest.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Tests/Controller/HelperControllerTest.php b/Tests/Controller/HelperControllerTest.php index 81d9fb8c6b..f0148ecf30 100644 --- a/Tests/Controller/HelperControllerTest.php +++ b/Tests/Controller/HelperControllerTest.php @@ -313,8 +313,6 @@ public function testappendFormFieldElementAction() $formExtension = $this->getMock('Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); $formExtension->expects($this->once())->method('getName')->will($this->returnValue('form')); - $formExtension->expects($this->never())->method('searchAndRenderBlock'); - $formExtension->expects($this->never())->method('setTheme'); $formExtension->renderer = $mockRenderer; $twig = new Twig(); @@ -396,8 +394,6 @@ public function testretrieveFormFieldElementAction() $formExtension = $this->getMock('Twig_ExtensionInterface', array('renderListElement', 'initRuntime', 'getTokenParsers', 'getNodeVisitors', 'getFilters', 'getTests', 'getFunctions', 'getOperators', 'getGlobals', 'getName')); $formExtension->expects($this->once())->method('getName')->will($this->returnValue('form')); - $formExtension->expects($this->never())->method('searchAndRenderBlock'); - $formExtension->expects($this->never())->method('setTheme'); $formExtension->renderer = $mockRenderer; $twig = new Twig();