From 72e16d63c84ca5a2a3db740d6493dcb58a6db79b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steffen=20Schro=CC=88der?= Date: Mon, 25 Aug 2014 15:20:14 +0200 Subject: [PATCH] web reader coding improvements by extracting method --- application/core/Utils/WebReader.php | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/application/core/Utils/WebReader.php b/application/core/Utils/WebReader.php index 690b7780..eb78e62e 100644 --- a/application/core/Utils/WebReader.php +++ b/application/core/Utils/WebReader.php @@ -25,10 +25,8 @@ abstract class WebReader { public static function loadUrl($url, callable $function = null) { $request = static::newRequest($url); $response = $request->send(); - if (!is_null($function)) { - $content = $response->getContent(); - $error = $response->getError()->getMessage(); - call_user_func($function, $content, $error); + if ($function) { + static::performCallback($response, $function); } return $response; } @@ -41,7 +39,9 @@ abstract class WebReader { */ protected static function newRequest($url) { $request = new Request($url); - $request->getOptions()->set(CURLOPT_TIMEOUT, 10)->set(CURLOPT_HEADER, false) // don't display response header + $options = $request->getOptions(); + $options->set(CURLOPT_TIMEOUT, 5) // timeout + ->set(CURLOPT_HEADER, false) // don't display response header ->set(CURLOPT_CRLF, true) // linux line feed ->set(CURLOPT_ENCODING, '') // accept encoding ->set(CURLOPT_USERAGENT, 'ManiaControl v' . ManiaControl::VERSION) // user-agent @@ -50,6 +50,18 @@ abstract class WebReader { return $request; } + /** + * Perform the given callback function with the response + * + * @param Response $response + * @param callable $function + */ + protected static function performCallback(Response $response, callable $function) { + $content = $response->getContent(); + $error = $response->getError()->getMessage(); + call_user_func($function, $content, $error); + } + /** * Load a URL via POST * @@ -65,10 +77,8 @@ abstract class WebReader { $request->getOptions()->set(CURLOPT_POSTFIELDS, $content); // post content field } $response = $request->send(); - if (!is_null($function)) { - $content = $response->getContent(); - $error = $response->getError()->getMessage(); - call_user_func($function, $content, $error); + if ($function) { + static::performCallback($response, $function); } return $response; }