Skip to content

Instantly share code, notes, and snippets.

@motin
Last active December 20, 2015 04:49
Show Gist options
  • Save motin/6073501 to your computer and use it in GitHub Desktop.
Save motin/6073501 to your computer and use it in GitHub Desktop.
Preparation: Set the path to phantomjs and casperjs executables as Yii app params and then put the casperjs script(s) to run in a path specified by the alias root.casperjs. The casperjs script should be written to only output JSON.
<?php
class CasperJS
{
static public function request($script, stdClass $params = null)
{
if (is_null($params)) {
$params = new stdClass();
}
putenv("PHANTOMJS_EXECUTABLE=" . Yii::app()->params["phantomjs"]);
chdir(Yii::getPathOfAlias("root.casperjs"));
$jsonParams = json_encode($params);
$cmd = Yii::app()->params["casperjs"] . " ./" . $script . " --params=" . escapeshellarg($jsonParams) . " 2>&1";
$response = shell_exec($cmd);
$parsed = json_decode($response);
if ($parsed->status !== "ok")
throw new Exception("CasperJS response without status ok. Raw response: $response");
return $parsed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment