0 follower

Final Class Yiisoft\Hydrator\Attribute\Parameter\DiResolver

InheritanceYiisoft\Hydrator\Attribute\Parameter\DiResolver
ImplementsYiisoft\Hydrator\Attribute\Parameter\ParameterAttributeResolverInterface

Resolver for {@see Di} attribute. Obtains dependency from container by ID specified or auto-resolved ID by PHP type.

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( \Psr\Container\ContainerInterface $container )
$container \Psr\Container\ContainerInterface

Container to obtain dependency from.

                public function __construct(
    private ContainerInterface $container,
) {
}

            
getParameterValue() public method

public Yiisoft\Hydrator\Result getParameterValue ( Yiisoft\Hydrator\Attribute\Parameter\ParameterAttributeInterface $attribute, Yiisoft\Hydrator\AttributeHandling\ParameterAttributeResolveContext $context )
$attribute Yiisoft\Hydrator\Attribute\Parameter\ParameterAttributeInterface
$context Yiisoft\Hydrator\AttributeHandling\ParameterAttributeResolveContext
throws \Psr\Container\ContainerExceptionInterface
throws Yiisoft\Hydrator\Attribute\Parameter\DiNotFoundException

When an object is not found in a container or object ID auto-resolving fails.

                public function getParameterValue(ParameterAttributeInterface $attribute, ParameterAttributeResolveContext $context): Result
{
    if (!$attribute instanceof Di) {
        throw new UnexpectedAttributeException(Di::class, $attribute);
    }
    $parameter = $context->getParameter();
    $id = $attribute->getId();
    if ($id !== null) {
        try {
            return Result::success(
                $this->container->get($id)
            );
        } catch (NotFoundExceptionInterface $e) {
            throw new DiNotFoundException($parameter, $e);
        }
    }
    $type = $parameter->getType();
    if ($type instanceof ReflectionNamedType) {
        if (!$type->isBuiltin()) {
            try {
                return Result::success(
                    $this->container->get($type->getName())
                );
            } catch (NotFoundExceptionInterface $e) {
                throw new DiNotFoundException($parameter, $e);
            }
        }
    } elseif ($type instanceof ReflectionUnionType) {
        foreach ($type->getTypes() as $type) {
            /** @psalm-suppress RedundantConditionGivenDocblockType Needed for PHP less than 8.2 */
            if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) {
                try {
                    return Result::success(
                        $this->container->get($type->getName())
                    );
                } catch (NotFoundExceptionInterface) {
                }
            }
        }
    }
    throw new DiNotFoundException($parameter);
}