Skip to content

Instantly share code, notes, and snippets.

@linxlad
Created July 8, 2015 14:05
Show Gist options
  • Save linxlad/49d408f08bc5e37f6ec0 to your computer and use it in GitHub Desktop.
Save linxlad/49d408f08bc5e37f6ec0 to your computer and use it in GitHub Desktop.
Buzz Browser Service in Symfony2
<?php
namespace AppBundle\Util;
use Buzz\Browser;
use Buzz\Exception\RequestException;
/**
* Class Buzz
* @package AppBundle\Util
* @author: Nathan Daly <justlikephp@gmail.com>
*/
class Buzz
{
/**
* @var Browser
*/
protected $buzz;
/**
* @var int
*/
protected $statusCode;
/**
* @var string
*/
protected $statusString;
/**
* @var mixed
*/
public $data;
public function __construct(Browser $buzz)
{
$this->buzz = $buzz;
}
/**
* @param $url
* @param array $headers
* @return mixed
*/
public function get($url, array $headers = [])
{
try {
$response = $this->buzz->get($url, $headers);
if ($this->processResponse($response)) {
return $this->getData();
}
} catch (RequestException $e) {
} catch (\Exception $e) {
}
// Return an empty object
return [];
}
/**
* @param $url
* @param array $headers
* @return mixed
*/
public function post($url, array $headers = [])
{
try {
$response = $this->buzz->post($url, $headers);
if ($this->processResponse($response)) {
return $this->getData();
}
} catch (RequestException $e) {
} catch (\Exception $e) {
}
// Return an empty object
return [];
}
/**
* @param $response
* @return bool
*/
protected function processResponse($response)
{
$result = json_decode($response->getContent());
$this->setStatusCode($result->status_code);
$this->setStatusString($result->status_txt);
$this->setData($result->data);
return $this->getSuccess();
}
/**
* @param $code
* @return $this
*/
protected function setStatusCode($code)
{
$this->statusCode = $code;
return $this;
}
/**
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* @param $string
* @return $this
*/
protected function setStatusString($string)
{
$this->statusString = $$string;
return $this;
}
/**
* @return string
*/
public function getStatusString()
{
return $this->statusString;
}
/**
* @return bool
*/
public function getSuccess()
{
if (200 == $this->getStatusCode()) {
return true;
}
return false;
}
/**
* @param $data
* @return $this
*/
protected function setData($data)
{
$this->data = $data;
return $this;
}
/**
* @return mixed
*/
public function getData()
{
return $this->data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment