4

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();
}
gremo
  • 47,186
  • 75
  • 257
  • 421
  • http://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s – Mun Mun Das Dec 22 '12 at 16:52

1 Answers1

8

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.

Community
  • 1
  • 1
Crozin
  • 43,890
  • 13
  • 88
  • 135