pcgben
pcgben

Reputation: 756

PhpStorm: Type hinting chained methods

In the code snippet below, I get type hinting on $contactInfo[0], and again on $order.

I would like the same with logger, which is an object of type \Monolog\Logger, accessed as a member of \psr\container\ContainerInterface

I am using PhpStorm which is warning me that Field 'logger' not found in Psr\Container\ContainerInterface

/**
 * @param Order $order
 * @param ContactInfo[] $contactInfo
 * @var Monolog\Logger $this->container->logger
 */
private function buildCreateOrderJSON(Order $order, $contactInfo)
{
    try {
        $currentDate = new DateTime();
    } catch (Exception $e) {
        $this->container->logger->addInfo('Some exception', $e->getMessage());
        return;
    }
    $lastName = $contactInfo[0]->getLastName();
    $order->getInvoiceNumber();
}

Upvotes: 1

Views: 832

Answers (2)

JorgeeFG
JorgeeFG

Reputation: 5981

Interfaces cannot have state in PHP, only methods signatures.

For this error to disappear, you can try assigning $this->container to a variable, and type hint that explicitly with a concrete class.

/** @var $container \Some\ConcreteContainerClass */
$container = $this->container;
$container->logger->addInfo('Some exception', $e->getMessage());

This would work if logger is an actual property of that class and not something accessed through magic getters. In that case, you might have to assign logger to another variable and do the same explicit type hint.

Another option is to supress inpesection for that line. https://www.jetbrains.com/help/webstorm/2017.2/suppressing-inspections.html#d218445e68

Upvotes: 0

e_i_pi
e_i_pi

Reputation: 4820

As LazyOne mentioned in the comments, you can't type hint a 3rd level entity.

What you can do to retain method name refactoring is you can assign your class element to a variable, then type hint that:

/** @var $logger \Monolog\Logger */
$logger = $this->container->logger;
$logger->addInfo('Some exception', $e->getMessage());

Upvotes: 3

Related Questions