Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if request service is accessible in Symfony 2?

Function getCurrentOrDefaultLocale(), defined in my service, may be invoked from a controller or through a command line script.

Accessing request service from CLI throws an exception, and I'm using it to detect the CLI invocation. However catching an exception only for this purpose seems so bad to me.

Is there any reliable way to check if request is accessible in the currenct context (of execution, browser vs CLI)?

/**
 * @return string
 */
protected function getCurrentOrDefaultLocale()
{
    try {
        $request = $this->container->get('request');
    }
    catch(InactiveScopeException $exception) {
        return $this->container->getParameter('kernel.default_locale');
    }

    // With Symfony < 2.1.0 current locale is stored in the session
    if(version_compare($this->sfVersion, '2.1.0', '<')) {
        return $this->container->get('session')->getLocale();
    }

    // Symfony >= 2.1.0 current locale from the request
    return $request->getLocale();
}
like image 886
gremo Avatar asked Feb 19 '23 02:02

gremo


1 Answers

You could simply check whether current container instance has request service/scope using ContainerInterface::has()/ContainerInterface::hasScope().

EDIT:

My mistake. You have to use ContainerInterface::isScopeActive(), to determine whether request service is fully functional:

public function __construct(ContainerInterface $container, RouterInterface $router) {
    if ($container->isScopeActive('request')) {
        $this->request = $container->get('request');
        $this->router = $router;
    }
}

This code snipped is from my own project, where I've experienced a very similar issue.

like image 70
Crozin Avatar answered Mar 04 '23 22:03

Crozin