Search code examples
phpexceptionphpstormphpdoc

PHPDoc for throwing exceptions in closures


Is there any smart way to document that a Closure throws an exception? I'm using PhpStorm and I would like to get rid off from annoying warning, that an exception is never thrown in the given block.

The method createFromState() is throwing and AbstractEntityRepositoryException exception, and I would like to let the IDE know about it.

    /**
     * Closure used to create an object from repository.
     * The default implementation is using the method {@link EntityRepositoryInterface::createFromState()}
     *
     * @var Closure|null
     * @throws AbstractEntityRepositoryException
     */
    private ?Closure $create = null;

    public function __construct(ControllerInteface $controller, string $id, ?Closure $create = null)
    {
        parent::__construct($controller, $id);
        if ($create === null) {
            $this->create = static function (EntityRepositoryInterface $repository, FormModelInterface $model): Entity {
                return $repository->createFromState($model->toState());
            };
        } 
        else {
          $this->create = $create;
        }

    }

    /**
     * @param FormModelInterface $model
     * @return Entity
     * @throws CreateActionException
     */
    public function saveModel(FormModelInterface $model): Entity
    {
        try {
            $create = $this->create;
            return $create($this->repository, $model);
        } catch (AbstractEntityRepositoryException $e) {
            throw new CreateActionException($e->getMessage(), $e->getErrors());
        }
    }

Solution

  • It seems that PHP Storm doesn't support that annotation correctly yet. This issue https://youtrack.jetbrains.com/issue/WI-52095 is exactly my case. Thanks for a help! I've added my case into aforementioned ticket.