Skip to content

ServiceSubscriberTrait #321

Open
Open
@specdrum-agc

Description

@specdrum-agc

I have an issue with ServiceSubscriberTrait (https://symfony.com/doc/5.4/service_container/service_subscribers_locators.html#service-subscriber-trait) on symfony 5.4 and PHP 7.4. Error message is like Service "App\Service\MyService::router" is not registered in the container.

How to reproduce:

  1. Install this extesion
  2. Add config as described in https://github.com/phpstan/phpstan-symfony#configuration
// phpstan.neon
    symfony:
        containerXmlPath: var/cache/dev/App_KernelDevDebugContainer.xml
  1. Create class MyService and copy code from symfony docs.
// src/Service/MyService.php
<?php

declare(strict_types=1);

namespace App\Service;

use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Service\Attribute\SubscribedService;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Contracts\Service\ServiceSubscriberTrait;

class MyService implements ServiceSubscriberInterface
{
    use ServiceSubscriberTrait;

    public function doSomething()
    {
        // $this->router() ...
        // $this->logger() ...
    }

    #[SubscribedService]
    private function router(): RouterInterface
    {
        return $this->container->get(__METHOD__);
    }

    #[SubscribedService]
    private function logger(): LoggerInterface
    {
        return $this->container->get(__METHOD__);
    }
}
  1. Run phpstan

The output will be:

 ------ ------------------------------------------------------------------
  Line   src/Service/MyService.php
 ------ ------------------------------------------------------------------
  17     Method App\Service\MyService::doSomething() has no return type
         specified.
  24     Method App\Service\MyService::router() is unused.
  26     Service "App\Service\MyService::router" is not registered in the
         container.
  30     Method App\Service\MyService::logger() is unused.
  32     Service "App\Service\MyService::logger" is not registered in the
         container.
 ------ ------------------------------------------------------------------

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions