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

Sonata Admin does not support proxy naming scheme used by Doctrine MongoDB ODM v.2.0 #7905

Closed antonymous closed 2 years ago

antonymous commented 2 years ago

Environment

Sonata packages

show

``` $ composer show --latest 'sonata-project/*' sonata-project/admin-bundle 4.16.0 4.16.0 The missing Symfony Admin Generator sonata-project/block-bundle 4.16.2 4.16.2 Symfony SonataBlockBundle sonata-project/cache 2.2.0 2.2.0 Cache library Package sonata-project/cache is abandoned, you should avoid using it. No replacement was suggested. sonata-project/doctrine-extensions 2.0.1 2.0.1 Doctrine2 behavioral extensions sonata-project/doctrine-mongodb-admin-bundle 4.5.0 4.5.0 Symfony Sonata / Integrate Doctrine MongoDB ODM into the SonataAdminBundle sonata-project/exporter 3.0.0 3.0.0 Lightweight Exporter library sonata-project/form-extensions 1.18.0 1.18.0 Symfony form extensions sonata-project/twig-extensions 2.0.0 2.0.0 Sonata twig extensions ```

Symfony packages

show

``` $ composer show --latest 'symfony/*' symfony/asset v5.4.7 v6.1.0 Manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files symfony/cache v5.4.11 v6.1.3 Provides an extended PSR-6, PSR-16 (and tags) implementation symfony/cache-contracts v2.5.2 v3.1.1 Generic abstractions related to caching symfony/config v5.4.11 v6.1.3 Helps you find, load, combine, autofill and validate configuration values of any kind symfony/console v5.4.11 v6.1.3 Eases the creation of beautiful and testable command line interfaces symfony/dependency-injection v5.4.11 v6.1.3 Allows you to standardize and centralize the way objects are constructed in your application symfony/deprecation-contracts v3.1.1 v3.1.1 A generic function and convention to trigger deprecation notices symfony/doctrine-bridge v5.4.11 v6.1.3 Provides integration for Doctrine with various Symfony components symfony/dotenv v5.4.5 v6.1.0 Registers environment variables from a .env file symfony/error-handler v5.4.11 v6.1.3 Provides tools to manage errors and ease debugging PHP code symfony/event-dispatcher v5.4.9 v6.1.0 Provides tools that allow your application components to communicate with each other by dispatching events and listening to them symfony/event-dispatcher-contracts v3.1.1 v3.1.1 Generic abstractions related to dispatching event symfony/expression-language v5.4.11 v6.1.3 Provides an engine that can compile and evaluate expressions symfony/filesystem v5.4.11 v6.1.3 Provides basic utilities for the filesystem symfony/finder v5.4.11 v6.1.3 Finds files and directories via an intuitive fluent interface symfony/flex v2.2.3 v2.2.3 Composer plugin for Symfony symfony/form v5.4.11 v6.1.3 Allows to easily create, process and reuse HTML forms symfony/framework-bundle v5.4.11 v6.1.3 Provides a tight integration between Symfony components and the Symfony full-stack framework symfony/http-foundation v5.4.11 v6.1.3 Defines an object-oriented layer for the HTTP specification symfony/http-kernel v5.4.11 v6.1.3 Provides a structured process for converting a Request into a Response symfony/options-resolver v5.4.11 v6.1.0 Provides an improved replacement for the array_replace PHP function symfony/password-hasher v5.4.11 v6.1.3 Provides password hashing utilities symfony/polyfill-intl-grapheme v1.26.0 v1.26.0 Symfony polyfill for intl's grapheme_* functions symfony/polyfill-intl-icu v1.26.0 v1.26.0 Symfony polyfill for intl's ICU-related data and classes symfony/polyfill-intl-normalizer v1.26.0 v1.26.0 Symfony polyfill for intl's Normalizer class and related functions symfony/polyfill-mbstring v1.26.0 v1.26.0 Symfony polyfill for the Mbstring extension symfony/polyfill-php73 v1.26.0 v1.26.0 Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions symfony/polyfill-php80 v1.26.0 v1.26.0 Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions symfony/polyfill-php81 v1.26.0 v1.26.0 Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions symfony/property-access v5.4.11 v6.1.3 Provides functions to read and write from/to an object or array using a simple string notation symfony/property-info v5.4.11 v6.1.3 Extracts information about PHP class' properties using metadata of popular sources symfony/routing v5.4.11 v6.1.3 Maps an HTTP request to a set of configuration variables symfony/runtime v5.4.11 v6.1.3 Enables decoupling PHP applications from global state symfony/security-acl v3.3.1 v3.3.1 Symfony Security Component - ACL (Access Control List) symfony/security-bundle v5.4.11 v6.1.3 Provides a tight integration of the Security component into the Symfony full-stack framework symfony/security-core v5.4.11 v6.1.3 Symfony Security Component - Core Library symfony/security-csrf v5.4.11 v6.1.0 Symfony Security Component - CSRF Library symfony/security-guard v5.4.9 v5.4.9 Symfony Security Component - Guard symfony/security-http v5.4.11 v6.1.3 Symfony Security Component - HTTP Integration symfony/service-contracts v2.5.2 v3.1.1 Generic abstractions related to writing services symfony/string v5.4.11 v6.1.3 Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way symfony/translation v5.4.11 v6.1.3 Provides tools to internationalize your application symfony/translation-contracts v2.5.2 v3.1.1 Generic abstractions related to translation symfony/twig-bridge v5.4.11 v6.1.3 Provides integration for Twig with various Symfony components symfony/twig-bundle v5.4.8 v6.1.1 Provides a tight integration of Twig into the Symfony full-stack framework symfony/validator v5.4.11 v6.1.3 Provides tools to validate values symfony/var-dumper v5.4.11 v6.1.3 Provides mechanisms for walking through any arbitrary PHP variable symfony/var-exporter v5.4.10 v6.1.3 Allows exporting any serializable PHP data structure to plain PHP code symfony/yaml v5.4.11 v6.1.3 Loads and dumps YAML files ```

PHP version

$ php -v
PHP 8.1.8 (cli) (built: Jul 11 2022 08:29:57) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.8, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.8, Copyright (c), by Zend Technologies
    with Xdebug v3.1.2, Copyright (c) 2002-2021, by Derick Rethans

Subject

Since v.2.0 Doctrine MongoDB ODM delegates proxy class generation to friendsofphp/proxy-manager-lts (from here):

The proxy implementation no longer relies on Doctrine proxies but rather the Proxy Manager library by ocramius.

Proxy Manager (by default) names proxy classes differently from \Doctrine\Common\Util\ClassUtils, which Sonata Admin still relies on to get a real class name from a proxy. As a result \Sonata\AdminBundle\Admin\AbstractAdmin::setSubject won't accept a proxy object, created by Proxy Manager. In my case the issue manifested itself while trying to add another element to non-empty collection.

Minimal repository with the bug

Documents:

<?php

namespace App\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\Document
 */
class RootDoc
{
    /**
     * @ODM\Id
     */
    private $id;

    /**
     * @ODM\Field
     */
    private $name;

    /**
     * @ODM\ReferenceMany( targetDocument="App\Document\NestedDoc", cascade={"all"})
     */
    private $nestedDocs;

    public function __construct()
    {
        $this->nestedDocs = new ArrayCollection();
    }

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getNestedDocs()
    {
        return $this->nestedDocs;
    }

    public function setNestedDocs($nestedDocs)
    {
        $this->nestedDocs = $nestedDocs;
    }

    public function addNestedDoc(NestedDoc $nestedDoc)
    {
        $this->nestedDocs->add($nestedDoc);
    }
}
<?php

namespace App\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\Document
 */
class NestedDoc
{
    /**
     * @ODM\Id
     */
    private $id;

    /**
     * @ODM\Field
     */
    private $name;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

Admin classes:

<?php

namespace App\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\Form\Type\CollectionType;

class RootDocAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $form): void
    {
        $form->add('name');
        $form->add('nestedDocs', CollectionType::class, [], [
            'edit' => 'inline',
            'inline' => 'table',
        ]);
    }

    protected function configureListFields(ListMapper $list): void
    {
        $list->addIdentifier('name', null, [
            'route' => ['name' => 'edit'],
        ]);
    }
}
<?php

namespace App\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Form\FormMapper;

class NestedDocAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $form): void
    {
        $form->add('name');
    }
}

services.yaml:

services:
    admin.root_doc:
        class: App\Admin\RootDocAdmin
        tags:
            -
                name: sonata.admin
                model_class: App\Document\RootDoc
                manager_type: doctrine_mongodb
                label: RootDoc

    admin.nested_doc:
        class: App\Admin\NestedDocAdmin
        tags:
            -
                name: sonata.admin
                model_class: App\Document\NestedDoc
                manager_type: doctrine_mongodb
                label: NestedDoc
                show_in_dashboard: false

Steps to reproduce

  1. Open Sonata Admin.
  2. Add new RootDoc with one NestedDoc, save.
  3. Go to edit previously saved RootDoc, press "Add new" to add another NestedDoc.

Expected results

New line in Nested Docs table appears.

Actual results

New line does not appear as XHR request to /admin/core/append-form-field-element fails with exception

LogicException:
Admin "App\Admin\NestedDocAdmin" does not allow this subject: App\Document\NestedDoc, use the one register with this admin class MongoDBODMProxies\__PM__\App\Document\NestedDoc\Generateddc8c9737b6be26e4aa48de3658b3c37e

  at vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php:1055
  at Sonata\AdminBundle\Admin\AbstractAdmin->setSubject()
     (vendor/sonata-project/admin-bundle/src/Form/Type/AdminType.php:102)
  at Sonata\AdminBundle\Form\Type\AdminType->buildForm()
     (vendor/symfony/form/ResolvedFormType.php:131)
  at Symfony\Component\Form\ResolvedFormType->buildForm()
     (vendor/symfony/form/FormFactory.php:73)
  at Symfony\Component\Form\FormFactory->createNamedBuilder()
     (vendor/symfony/form/FormFactory.php:39)
  at Symfony\Component\Form\FormFactory->createNamed()
     (vendor/symfony/form/Form.php:884)
  at Symfony\Component\Form\Form->add()
     (vendor/sonata-project/form-extensions/src/EventListener/ResizeFormListener.php:106)
  at Sonata\Form\EventListener\ResizeFormListener->preSetData()
     (vendor/symfony/event-dispatcher/EventDispatcher.php:230)
  at Symfony\Component\EventDispatcher\EventDispatcher->callListeners()
     (vendor/symfony/event-dispatcher/EventDispatcher.php:59)
  at Symfony\Component\EventDispatcher\EventDispatcher->dispatch()
     (vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php:33)
  at Symfony\Component\EventDispatcher\ImmutableEventDispatcher->dispatch()
     (vendor/symfony/form/Form.php:354)
  at Symfony\Component\Form\Form->setData()
     (vendor/symfony/form/Extension/Core/DataMapper/DataMapper.php:57)
  at Symfony\Component\Form\Extension\Core\DataMapper\DataMapper->mapDataToForms()
     (vendor/symfony/form/Form.php:388)
  at Symfony\Component\Form\Form->setData()
     (vendor/sonata-project/admin-bundle/src/Admin/AdminHelper.php:192)
  at Sonata\AdminBundle\Admin\AdminHelper->appendFormFieldElement()
     (vendor/sonata-project/admin-bundle/src/Action/AppendFormFieldElementAction.php:74)
  at Sonata\AdminBundle\Action\AppendFormFieldElementAction->__invoke()
     (vendor/symfony/http-kernel/HttpKernel.php:152)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw()
     (vendor/symfony/http-kernel/HttpKernel.php:74)
  at Symfony\Component\HttpKernel\HttpKernel->handle()
     (vendor/symfony/http-kernel/Kernel.php:202)
  at Symfony\Component\HttpKernel\Kernel->handle()
     (vendor/symfony/runtime/Runner/Symfony/HttpKernelRunner.php:35)
  at Symfony\Component\Runtime\Runner\Symfony\HttpKernelRunner->run()
     (vendor/autoload_runtime.php:35)
  at require_once('/var/www/testcase/vendor/autoload_runtime.php')
     (public/index.php:5)
VincentLanglet commented 2 years ago

Since you're using Mongo, you never got the issue @franmomu ?

I don't like the fact that

$class = ClassUtils::getClass($this->subject);

is used in SonataAdmin code. This is too much persistence-bundle related and this issue is proving the fact.

IMHO we should

WDYT @jordisala1991 ?

antonymous commented 2 years ago

@VincentLanglet Wow! That was fast!

Or... \Sonata\DoctrineMongoDBAdminBundle\Model\ModelManager::getMetadata() could be part of ModelManagerInterface to allow calling getName() where needed?

https://github.com/doctrine/mongodb-odm/blob/2.4.x/UPGRADE-2.3.md#proxy-class-name-resolution:

To retrieve the mapped class name for any object or class string, fetch metadata for the class and read the class using $metadata->getName(). The metadata layer is aware of these proxy namespace changes and how to resolve them, so users should always go through the metadata layer to retrieve mapped class names.

(Just in case... I also managed to set Proxy Manager up to rely on my own \ProxyManager\Inflector\ClassNameInflectorInterface implementation, that would be a wrapper to ClassUtils. No need to change Sonata Admin (yet?), then. I guess, this could be done by SonataDoctrineMongoDBAdminBundle.)

VincentLanglet commented 2 years ago

https://github.com/sonata-project/SonataAdminBundle/pull/7906 is a quick example of what I had in mind.

@VincentLanglet Wow! That was fast!

Or... \Sonata\DoctrineMongoDBAdminBundle\Model\ModelManager::getMetadata() could be part of ModelManagerInterface to allow calling getName() where needed?

Although a getMetadata class is also implemented in Sonata\DoctrineORM, I don't think it's a good idea. The goal is to provide a ModelManagerInterface which is not related to any specific persistence bundle.

In a dream world, someone could implement his own ModelManager which wouldn't be doctrine-related at all. So you can't ask him to return a Metadata class ; which is a class from Doctrine.

And now I'm think about it, I'm pretty sure the MedataClass from ORM and Mondo are not the same.

VincentLanglet commented 2 years ago

Can you provide a PR similar to https://github.com/sonata-project/SonataDoctrineORMAdminBundle/pull/1685 on https://github.com/sonata-project/SonataDoctrineMongoDBAdminBundle @antonymous ?

antonymous commented 2 years ago

@VincentLanglet Done!