sonata-project / SonataAdminBundle

The missing Symfony Admin Generator
https://docs.sonata-project.org/projects/SonataAdminBundle
MIT License
2.11k stars 1.26k forks source link

Error when trying to extend the ModelType using the getParent method #7268

Closed tifabien closed 3 years ago

tifabien commented 3 years ago

Environment

Sonata packages

show

``` $ composer show --latest 'sonata-project/*' sonata-project/admin-bundle 3.101.0 3.101.0 The missing Symfony... sonata-project/block-bundle 3.23.1 4.6.0 Symfony SonataBlock... sonata-project/cache 2.0.1 2.1.1 Cache library sonata-project/datagrid-bundle 3.3.0 3.3.0 Symfony SonataDatag... sonata-project/doctrine-extensions 1.13.0 1.13.0 Doctrine2 behaviora... sonata-project/doctrine-orm-admin-bundle 3.34.3 3.34.3 Integrate Doctrine ... sonata-project/exporter 2.6.2 2.6.2 Lightweight Exporte... sonata-project/form-extensions 1.9.0 1.9.0 Symfony form extens... sonata-project/media-bundle 3.32.0 3.32.0 Symfony SonataMedia... sonata-project/twig-extensions 1.6.0 1.6.0 Sonata twig extensions sonata-project/user-bundle 4.11.1 4.11.1 Symfony SonataUserB... ```

Symfony packages

show

``` $ composer show --latest 'symfony/*' symfony/amqp-messenger v5.2.10 v5.3.2 Symfony AMQP extension Messenger Bridge symfony/asset v4.4.25 v5.3.2 Manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files symfony/browser-kit v4.4.25 v5.3.0 Simulates the behavior of a web browser, allowing you to make requests, click on links and submit forms programmatically symfony/cache v5.3.0 v5.3.0 Provides an extended PSR-6, PSR-16 (and tags) implementation symfony/cache-contracts v2.4.0 v2.4.0 Generic abstractions related to caching symfony/config v4.4.25 v5.3.2 Helps you find, load, combine, autofill and validate configuration values of any kind symfony/console v4.4.25 v5.3.2 Eases the creation of beautiful and testable command line interfaces symfony/css-selector v5.3.0 v5.3.0 Converts CSS selectors to XPath expressions symfony/debug v4.4.25 v4.4.25 Provides tools to ease debugging PHP code symfony/debug-bundle v5.1.11 v5.3.0 Provides a tight integration of the Symfony Debug component into the Symfony full-stack framework symfony/dependency-injection v4.4.25 v5.3.2 Allows you to standardize and centralize the way objects are constructed in your application symfony/deprecation-contracts v2.4.0 v2.4.0 A generic function and convention to trigger deprecation notices symfony/doctrine-bridge v4.4.25 v5.3.1 Provides integration for Doctrine with various Symfony components symfony/doctrine-messenger v5.3.0 v5.3.2 Symfony Doctrine Messenger Bridge symfony/dom-crawler v4.4.25 v5.3.0 Eases DOM navigation for HTML and XML documents symfony/dotenv v5.3.0 v5.3.0 Registers environment variables from a .env file symfony/error-handler v4.4.25 v5.3.0 Provides tools to manage errors and ease debugging PHP code symfony/event-dispatcher v4.4.25 v5.3.0 Provides tools that allow your application components to communicate with each other by dispatching events and listening to them symfony/event-dispatcher-contracts v1.1.9 v2.4.0 Generic abstractions related to dispatching event symfony/expression-language v5.3.0 v5.3.0 Provides an engine that can compile and evaluate expressions symfony/filesystem v5.3.0 v5.3.0 Provides basic utilities for the filesystem symfony/finder v5.3.0 v5.3.0 Finds files and directories via an intuitive fluent interface symfony/flex v1.13.3 v1.13.3 Composer plugin for Symfony symfony/form v4.4.25 v5.3.2 Allows to easily create, process and reuse HTML forms symfony/framework-bundle v4.4.25 v5.3.2 Provides a tight integration between Symfony components and the Symfony full-stack framework symfony/http-client v4.4.25 v5.3.2 Provides powerful methods to fetch HTTP resources synchronously or asynchronously symfony/http-client-contracts v2.4.0 v2.4.0 Generic abstractions related to HTTP clients symfony/http-foundation v4.4.25 v5.3.2 Defines an object-oriented layer for the HTTP specification symfony/http-kernel v4.4.25 v5.3.2 Provides a structured process for converting a Request into a Response symfony/intl v5.3.0 v5.3.0 Provides a PHP replacement layer for the C intl extension that includes additional data from the ICU library symfony/mailer v5.3.0 v5.3.0 Helps sending emails symfony/maker-bundle v1.31.1 v1.31.1 Symfony Maker helps you create empty commands, controllers, form classes, tests and more so you can forget about writing boilerplate code. symfony/messenger v5.2.10 v5.3.2 Helps applications send and receive messages to/from other applications or via message queues symfony/mime v5.3.0 v5.3.2 Allows manipulating MIME messages symfony/monolog-bridge v5.2.10 v5.3.0 Provides integration for Monolog with various Symfony components symfony/monolog-bundle v3.7.0 v3.7.0 Symfony MonologBundle symfony/options-resolver v5.3.0 v5.3.0 Provides an improved replacement for the array_replace PHP function symfony/phpunit-bridge v5.3.0 v5.3.0 Provides utilities for PHPUnit, especially user deprecation notices management symfony/polyfill-ctype v1.23.0 v1.23.0 Symfony polyfill for ctype functions symfony/polyfill-intl-grapheme v1.23.0 v1.23.0 Symfony polyfill for intl's grapheme_* functions symfony/polyfill-intl-icu v1.23.0 v1.23.0 Symfony polyfill for intl's ICU-related data and classes symfony/polyfill-intl-idn v1.23.0 v1.23.0 Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions symfony/polyfill-intl-normalizer v1.23.0 v1.23.0 Symfony polyfill for intl's Normalizer class and related functions symfony/polyfill-mbstring v1.23.0 v1.23.0 Symfony polyfill for the Mbstring extension symfony/polyfill-php72 v1.23.0 v1.23.0 Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions symfony/polyfill-php73 v1.23.0 v1.23.0 Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions symfony/polyfill-php80 v1.23.0 v1.23.0 Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions symfony/polyfill-php81 v1.23.0 v1.23.0 Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions symfony/process v5.3.0 v5.3.2 Executes commands in sub-processes symfony/property-access v5.3.0 v5.3.0 Provides functions to read and write from/to an object or array using a simple string notation symfony/property-info v5.3.1 v5.3.1 Extracts information about PHP class' properties using metadata of popular sources symfony/proxy-manager-bridge v4.4.25 v5.3.0 Provides integration for ProxyManager with various Symfony components symfony/redis-messenger v5.3.0 v5.3.2 Symfony Redis extension Messenger Bridge symfony/routing v4.4.25 v5.3.0 Maps an HTTP request to a set of configuration variables symfony/security-acl v3.1.2 v3.1.2 Symfony Security Component - ACL (Access Control List) symfony/security-bundle v4.4.25 v5.3.2 Provides a tight integration of the Security component into the Symfony full-stack framework symfony/security-core v4.4.25 v5.3.2 Symfony Security Component - Core Library symfony/security-csrf v5.2.10 v5.3.0 Symfony Security Component - CSRF Library symfony/security-guard v4.4.25 v5.3.0 Symfony Security Component - Guard symfony/security-http v4.4.25 v5.3.2 Symfony Security Component - HTTP Integration symfony/serializer v5.3.1 v5.3.2 Handles serializing and deserializing data structures, including object graphs, into array structures or other formats like XML and JSON. symfony/service-contracts v2.4.0 v2.4.0 Generic abstractions related to writing services symfony/stopwatch v5.3.0 v5.3.0 Provides a way to profile code symfony/string v5.3.0 v5.3.2 Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way symfony/templating v4.4.25 v5.3.0 Provides all the tools needed to build any kind of template system symfony/translation v4.4.25 v5.3.2 Provides tools to internationalize your application symfony/translation-contracts v2.4.0 v2.4.0 Generic abstractions related to translation symfony/twig-bridge v4.4.25 v5.3.0 Provides integration for Twig with various Symfony components symfony/twig-bundle v4.4.25 v5.3.0 Provides a tight integration of Twig into the Symfony full-stack framework symfony/validator v4.4.25 v5.3.2 Provides tools to validate values symfony/var-dumper v5.3.0 v5.3.2 Provides mechanisms for walking through any arbitrary PHP variable symfony/var-exporter v5.3.0 v5.3.2 Allows exporting any serializable PHP data structure to plain PHP code symfony/web-link v5.2.10 v5.3.0 Manages links between resources symfony/web-profiler-bundle v4.4.25 v5.3.2 Provides a development tool that gives detailed information about the execution of any request symfony/yaml v5.3.0 v5.3.2 Loads and dumps YAML files ```

PHP version

$ php -v
PHP 7.4.3 (cli) (built: Oct  6 2020 15:47:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

Subject

As Sonata 4 marked FormType classes as final, we can't extend them anymore using the extends keyword. By the way, we can create our own FormType and use the getParent() method for the same result. When using this method, we face an error when trying to extend the ModelType (I think other FormTypes are impacted). It seems related to the fact that AbstractFormContractor class injects the model_manager option only if the FormType is instance of ModelType. This was OK with our cutom FormType when extending the ModelType but doesn't work anymore with the getParent() method.

Steps to reproduce

Create a simple class like

<?php
namespace App\Form\Admin\Type;

use Sonata\AdminBundle\Form\Type\ModelType;
use Symfony\Component\Form\AbstractType;

class TerminalGroupModelType extends AbstractType
{
    public function getParent(): ?string
    {
        return ModelType::class;
    }
}

Expected results

The TerminalGroupModelType loads as a ModelType

Actual results

TypeError:
Argument 1 passed to Sonata\AdminBundle\Form\ChoiceList\ModelChoiceLoader::__construct() must implement interface Sonata\AdminBundle\Model\ModelManagerInterface, null given, called in /application/vendor/sonata-project/admin-bundle/src/Form/Type/ModelType.php on line 89

  at vendor/sonata-project/admin-bundle/src/Form/ChoiceList/ModelChoiceLoader.php:86
  at Sonata\AdminBundle\Form\ChoiceList\ModelChoiceLoader->__construct(null, null, null, null, null, object(PropertyAccessor))
     (vendor/sonata-project/admin-bundle/src/Form/Type/ModelType.php:89)
  at Sonata\AdminBundle\Form\Type\ModelType::Sonata\AdminBundle\Form\Type\{closure}(object(OptionsResolver), null)
     (vendor/symfony/options-resolver/OptionsResolver.php:1052)
  at Symfony\Component\OptionsResolver\OptionsResolver->offsetGet('choice_loader')
     (vendor/symfony/options-resolver/OptionsResolver.php:947)
  at Symfony\Component\OptionsResolver\OptionsResolver->resolve(array('sonata_field_description' => object(FieldDescription), 'multiple' => true, 'property_path' => 'terminalGroups', 'label_render' => false, 'label' => 'terminal_groups'))
     (vendor/symfony/form/ResolvedFormType.php:97)
  at Symfony\Component\Form\ResolvedFormType->createBuilder(object(FormFactory), 'terminalGroups', array('sonata_field_description' => object(FieldDescription), 'multiple' => true, 'property_path' => 'terminalGroups', 'label_render' => false, 'label' => 'terminal_groups'))
     (vendor/symfony/form/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php:74)
  at Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeDataCollectorProxy->createBuilder(object(FormFactory), 'terminalGroups', array('sonata_field_description' => object(FieldDescription), 'multiple' => true, 'property_path' => 'terminalGroups', 'label_render' => false, 'label' => 'terminal_groups'))
     (vendor/symfony/form/FormFactory.php:76)
  at Symfony\Component\Form\FormFactory->createNamedBuilder('terminalGroups', object(ResolvedTypeDataCollectorProxy), null, array('sonata_field_description' => object(FieldDescription), 'multiple' => true, 'property_path' => 'terminalGroups', 'label_render' => false, 'label' => 'terminal_groups'))
     (vendor/symfony/form/FormBuilder.php:94)
  at Symfony\Component\Form\FormBuilder->create('terminalGroups', 'App\\Form\\Admin\\Type\\TerminalGroupModelType', array('sonata_field_description' => object(FieldDescription), 'multiple' => true, 'property_path' => 'terminalGroups', 'label_render' => false, 'label' => 'terminal_groups'))
     (vendor/symfony/form/FormBuilder.php:244)
  at Symfony\Component\Form\FormBuilder->resolveChildren()
     (vendor/symfony/form/FormBuilder.php:195)
  at Symfony\Component\Form\FormBuilder->getForm()
     (vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php:3411)
  at Sonata\AdminBundle\Admin\AbstractAdmin->buildForm('sonata_deprecation_mute')
     (vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php:1417)
  at Sonata\AdminBundle\Admin\AbstractAdmin->getForm()
     (vendor/sonata-project/admin-bundle/src/Controller/CRUDController.php:327)
  at Sonata\AdminBundle\Controller\CRUDController->editAction(null)
     (vendor/symfony/http-kernel/HttpKernel.php:158)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (vendor/symfony/http-kernel/HttpKernel.php:80)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor/symfony/http-kernel/Kernel.php:201)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (public/index.php:36)                
VincentLanglet commented 3 years ago

Can you try to modify https://github.com/sonata-project/SonataAdminBundle/blob/master/src/Builder/AbstractFormContractor.php#L141 ?

Maybe using a reflection method to execute the getParent could be a solution ?

But a recursion should be done, cause the form could be a parent of a parent of the ModelType (and so on).

jordisala1991 commented 3 years ago

Maybe Sf already has something to check for parents?

dmaicher commented 3 years ago

Maybe Sf already has something to check for parents?

Maybe Symfony\Component\Form\FormRegistryInterface::getType(...) could be useful for this

franmomu commented 3 years ago

Maybe we could move code from AbstractFromContractor to some Form type extensions and I guess the FormTypeExtensionInterface::getExtendedTypes would affect also types that extend from the type defined by us.

VincentLanglet commented 3 years ago

When extending the ModelType, it's still possible to override the configureOptions method and to not define a model_manager option for instance.

Which means, the fact our AbstractFormContractor were adding the option to any form extending the ModelType could throw an error. This won't happen now the form is final.

With the getParent method both configureOptions will be called I think, so I would say it's the right solution.

Changing

private function isAnyInstanceOf(?string $type, array $classes): bool
    {
        if (null === $type) {
            return false;
        }

        foreach ($classes as $class) {
            if (is_a($type, $class, true)) {
                return true;
            }
        }

        return false;
    }

to something like

private function isAnyInstanceOf(?string $type, array $classes): bool
    {
        if (null === $type) {
            return false;
        }

        foreach ($classes as $class) {
            if (is_a($type, $class, true)) {
                return true;
            }
        }

        $getParent = new ReflectionMethod($type, 'getParent');

        return isAnyInstanceOf($getParent->invoke(), $classes);
    }

could solve the issue.

dmaicher commented 3 years ago

Had a quick look and this is working as well and can also handle multiple parent layers:

diff --git a/src/Builder/AbstractFormContractor.php b/src/Builder/AbstractFormContractor.php
index 456fc6c02..8e27675a0 100644
--- a/src/Builder/AbstractFormContractor.php
+++ b/src/Builder/AbstractFormContractor.php
@@ -25,6 +25,7 @@ use Sonata\AdminBundle\Form\Type\ModelTypeList;
 use Sonata\Form\Type\CollectionType;
 use Symfony\Component\Form\Extension\Core\Type\FormType;
 use Symfony\Component\Form\FormFactoryInterface;
+use Symfony\Component\Form\FormRegistryInterface;

 abstract class AbstractFormContractor implements FormContractorInterface
 {
@@ -33,9 +34,15 @@ abstract class AbstractFormContractor implements FormContractorInterface
      */
     protected $formFactory;

-    public function __construct(FormFactoryInterface $formFactory)
+    /**
+     * @var FormRegistryInterface|null
+     */
+    protected $formRegistry;
+
+    public function __construct(FormFactoryInterface $formFactory, ?FormRegistryInterface $formRegistry = null)
     {
         $this->formFactory = $formFactory;
+        $this->formRegistry = $formRegistry;
     }

     /**
@@ -191,6 +198,22 @@ abstract class AbstractFormContractor implements FormContractorInterface
             }
         }

+        // NEXT_MAJOR: remove if condition
+        if (null !== $this->formRegistry) {
+            // handle form type inheritance and check all parent types
+            $resolvedType = $this->formRegistry->getType($type);
+            while ($resolvedType->getParent() !== null) {
+                $resolvedType = $resolvedType->getParent();
+                $parentType = get_class($resolvedType->getInnerType());
+
+                foreach ($classes as $class) {
+                    if (is_a($parentType, $class, true)) {
+                        return true;
+                    }
+                }
+            }
+        }
+
         return false;
     }

We could also use reflection but I think using Symfony's FormRegistry for resolving the parents is cleaner, or?

dmaicher commented 3 years ago

Maybe we could move code from AbstractFromContractor to some Form type extensions and I guess the FormTypeExtensionInterface::getExtendedTypes would affect also types that extend from the type defined by us.

@franmomu I feel this would indeed be a better longterm solution but its a bigger change and I don't think we should do it for 4.0

VincentLanglet commented 3 years ago

We could also use reflection but I think using Symfony's FormRegistry for resolving the parents is cleaner, or?

Yes sure ! Far better than reflection.

We'll just need to add the dependency in the service declaration of the persistence bundles