3 namespace Zumba\GastonJS\Browser;
5 use Zumba\GastonJS\Exception\BrowserError;
6 use Zumba\GastonJS\Exception\DeadClient;
8 use GuzzleHttp\Exception\ConnectException;
9 use GuzzleHttp\Exception\ServerException;
13 * @package Zumba\GastonJS\Browser
21 protected $phantomJSHost;
26 * Creates an http client to consume the phantomjs API
28 protected function createApiClient() {
29 // Provide a BC switch between guzzle 5 and guzzle 6.
30 if (class_exists('GuzzleHttp\Psr7\Response')) {
31 $this->apiClient = new Client(array("base_uri" => $this->getPhantomJSHost()));
34 $this->apiClient = new Client(array("base_url" => $this->getPhantomJSHost()));
39 * TODO: not sure how to do the normalizeKeys stuff fix when needed
43 protected function normalizeKeys($keys) {
50 public function getApiClient() {
51 return $this->apiClient;
57 public function getPhantomJSHost() {
58 return $this->phantomJSHost;
64 public function getLogger() {
69 * Restarts the browser
71 public function restart() {
72 //TODO: Do we really need to do this?, we are just a client
76 * Sends a command to the browser
77 * @throws BrowserError
81 public function command() {
83 $args = func_get_args();
84 $commandName = $args[0];
86 $messageToSend = json_encode(array('name' => $commandName, 'args' => $args));
87 /** @var $commandResponse \GuzzleHttp\Psr7\Response|\GuzzleHttp\Message\Response */
88 $commandResponse = $this->getApiClient()->post("/api", array("body" => $messageToSend));
89 $jsonResponse = json_decode($commandResponse->getBody(), TRUE);
90 } catch (ServerException $e) {
91 $jsonResponse = json_decode($e->getResponse()->getBody()->getContents(), true);
92 } catch (ConnectException $e) {
93 throw new DeadClient($e->getMessage(), $e->getCode(), $e);
94 } catch (\Exception $e) {
98 if (isset($jsonResponse['error'])) {
99 throw $this->getErrorClass($jsonResponse);
102 return $jsonResponse['response'];
107 * @return BrowserError
109 protected function getErrorClass($error) {
110 $errorClassMap = array(
111 'Poltergeist.JavascriptError' => "Zumba\\GastonJS\\Exception\\JavascriptError",
112 'Poltergeist.FrameNotFound' => "Zumba\\GastonJS\\Exception\\FrameNotFound",
113 'Poltergeist.InvalidSelector' => "Zumba\\GastonJS\\Exception\\InvalidSelector",
114 'Poltergeist.StatusFailError' => "Zumba\\GastonJS\\Exception\\StatusFailError",
115 'Poltergeist.NoSuchWindowError' => "Zumba\\GastonJS\\Exception\\NoSuchWindowError",
116 'Poltergeist.ObsoleteNode' => "Zumba\\GastonJS\\Exception\\ObsoleteNode"
118 if (isset($error['error']['name']) && isset($errorClassMap[$error["error"]["name"]])) {
119 return new $errorClassMap[$error["error"]["name"]]($error);
122 return new BrowserError($error);