Home > Blockchain >  Override class noted "final" in vendor
Override class noted "final" in vendor

Time:11-08

I want to override a class from the JMS/serializer bundle. Unfortunately this class is marked "final" and I can't override it. What would be the best method to circumvent this problem please? I'm on symfony5.4

Here is the class I want to override :

<?php

declare(strict_types=1);

namespace JMS\Serializer\Handler;

use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
use JMS\Serializer\XmlSerializationVisitor;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface as TranslatorContract;

use function get_class;

 final class FormErrorHandler implements SubscribingHandlerInterface
{
    /**
     * @var TranslatorInterface|null
     */
    private $translator;

    /**
     * @var string
     */
    private $translationDomain;

CodePudding user response:

The short answer is that you can not override the final classes as long as the package author does not provide a functionality to replace the final class with a custom implmentation.

by taking a look at the source code of the package, you can do so. the SerializeBuilder constructor is something like:

public function __construct(?HandlerRegistryInterface $handlerRegistry = null, ?EventDispatcherInterface $eventDispatcher = null)

which clearly means that you can add your custom handler.

and due to the documentation you can implement your own handler easily.

$builder
    ->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
        $registry->registerSubscribingHandler(new MyHandler());
    })
;

CodePudding user response:

I finally found a solution. I overridden the FormErrorHandler class from FOS/SerializerbUndle and then I overridden the formErrorHandlere class from JMS which I call in my overload of FOS/FormErrorHandler. it works perfectly

  • Related