Search code examples
phpsymfonybuzz

Change defaults for kriswallsmith/Buzz browser


How can i change the request options for a call with a Buzz Browser instance?

I would like to add a longer timeout to the call. Right now it triggers and exception if the legacy server takes longer then x seconds. I would like to prolong this timeout, since the legacy server always returns results, but it can take up to 40 seconds sometimes.

I'm using inside a Symfony2 controller, here's my code:

try {
    $buzz = new Browser();
    $legacyUrl = self::URL_LEGACY_SERVER . $urlSuffix .'?'. http_build_query($request->query->all());
    $legacyResponse = $buzz->get($legacyUrl, array());
} catch (\Exception $e) {
    return $this->sendError('Request to legacy server failed.', 500);
}

Solution

  • Learn to read source code. On that GitHub page search for "timeout".

    It will show you that AbstractClient has a timeout property and a setTimeout() method:

    abstract class AbstractClient implements ClientInterface {
        // [...]
        protected $timeout = 5;
        // [...]
        public function setTimeout($timeout) {
            $this->timeout = $timeout;
        }
        // [...]
    }
    

    Now you should be thinking, "how can I get to that object?". Since you are using the Browser class, that is where you should start.

    Looking at Browser's constructor, you can see that it sets the client property to a class that implements ClientInterface:

    public function __construct(ClientInterface $client = null, FactoryInterface $factory = null) {
        $this->client = $client ?: new FileGetContents();
        $this->factory = $factory ?: new Factory();
    }
    

    Since you are not passing any arguments to the constructor it will set the client to an instance of FileGetContents, which extends AbstractStream, which in turn extends AbstractClient (go through the files and see for yourself).

    Since the client property, set in Browser's constructor, is set to private you will have to find a way of getting to it. Looking through the class you will find this:

    public function getClient() { /* ... */ }
    

    Okay. We now know that we can get the client by calling getClient(). We also know that the client has a setTimeout() method:

    $buzz->getClient()->setTimeout(40);
    

    Voilà.