Disable elements in the Symfony developer toolbar with CompilerPass

One of the comments of the "Disable elements in the Symfony developer toolbar" post was the question to do the same thing with a compiler pass instead of overwriting the definitions with the services.yml

Wouldn't it be a cleaner approach to have a compiler pass that would just override the service tag priority? That way, we wouldn't need to figure out the classes and arguments for the service.

Which is a valid point, so I looked into it and found a solution.

Within my custom CompilerPass I remove the tags responsible for the data collectors being shown in the toolbar. I now only need a list of the data collector ids and don't need to know about the construction arguments of the specific collectors.

class DataCollectorCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $collectorsToRemove = [
            'data_collector.form',
            'data_collector.translation',
            'data_collector.logger',
            'data_collector.ajax',
            'data_collector.twig'
        ];

        foreach($collectorsToRemove as $dataCollector) {

            if (!$container->hasDefinition($dataCollector)) {
                continue;
            }
            $definition = $container->getDefinition($dataCollector);

            $definition->clearTags();
        }
    }
}

The CompilerPass is then being added as part of the bundle class.

class LiplexBackendBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new DataCollectorCompilerPass());
    }
}

Very important:

You have to put your bundle before the FrameworkBundle within your AppKernel:registerBundles function. Otherwise the data collectors are already added as part of the ProfilerPass before your CompilerPass is run and your changes are just ignored.