Is it possible to detect if a HTTPRequest is available?

Silverstripe Version: 4.2

I have a custom AssetAdapter that makes some changes to the filesystem based on the current request. I am using injector to get the request:

$request = Injector::inst()->get(HTTPRequest::class);

For the most part this works fine, but in a couple of isolated instances, I get the error:

ERROR [Emergency]: Uncaught ArgumentCountError: Too few arguments to function SilverStripe\Control\HTTPRequest::__construct(), 0 passed and at least 2 expected
IN GET /ecms-client/public/markseen
Line 157 in /project/path/vendor/silverstripe/framework/src/Control/HTTPRequest.php

This appears to be an issue/conflict with GraphQL and Assets (GraphQL doesn’t always seem to have the current request available). I was wondering if there was a way to check if the current HTTPRequest is available/setup before trying to get it via Injector?

You can use Injector::inst()->has(HTTPRequest::class).

The problem with calling Injector::inst()->get(HTTPRequest::class) is that it will instantiate a new HTTPRequest if one is not already registered with Injector as a service - this is where your error comes from, since you aren’t providing any constructor arguments when you call this.

Another option is to check whether Controller::has_curr() && Controller::curr()->getRequest() is truthy.


$request = Controller::curr()->request;

Have tried that, unfortunately I get the error:

ERROR [User Warning]: No current controller available

If you can’t find controller, it means: Your code kicks in before the Controller object is instantiated.

Now you may want to take a look of the HTTPRequest class, and see how it’s created, or do a bit detour, which is to use the variables from $_SERVER directly