Permalink
Browse files

Common functional moved to iron_core_php

  • Loading branch information...
1 parent a4e352e commit 9a15218da52e8118681b1cf6cc5bda1ceca367e3 @thousandsofthem thousandsofthem committed May 1, 2012
Showing with 91 additions and 306 deletions.
  1. +8 −301 IronWorker.class.php
  2. +32 −2 README.md
  3. +32 −0 build.php
  4. BIN iron_worker.phar
  5. +19 −3 test/run_all.php
View
@@ -6,100 +6,33 @@
* @link https://github.com/iron-io/iron_worker_php
* @link http://www.iron.io/
* @link http://dev.iron.io/
- * @version 1.2.1
+ * @version 1.3.0
* @package IronWorkerPHP
* @copyright Feel free to copy, steal, take credit for, or whatever you feel like doing with this code. ;)
*/
/**
- * The Http_Exception class represents an HTTP response status that is not 200 OK.
+ * IronWorker internal exceptions representation
*/
-class Http_Exception extends Exception{
- const NOT_MODIFIED = 304;
- const BAD_REQUEST = 400;
- const NOT_FOUND = 404;
- const NOT_ALLOWED = 405;
- const CONFLICT = 409;
- const PRECONDITION_FAILED = 412;
- const INTERNAL_ERROR = 500;
- const SERVICE_UNAVAILABLE = 503;
-}
-
-/**
- * The JSON_Exception class represents an failures of decoding json strings.
- */
-class JSON_Exception extends Exception {
- public $error = null;
- public $error_code = JSON_ERROR_NONE;
-
- function __construct($error_code) {
- $this->error_code = $error_code;
- switch($error_code) {
- case JSON_ERROR_DEPTH:
- $this->error = 'Maximum stack depth exceeded.';
- break;
- case JSON_ERROR_CTRL_CHAR:
- $this->error = "Unexpected control characted found.";
- break;
- case JSON_ERROR_SYNTAX:
- $this->error = "Syntax error, malformed JSON";
- break;
- default:
- $this->error = $error_code;
- break;
-
- }
- parent::__construct();
- }
-
- function __toString() {
- return $this->error;
- }
-}
-
-
class IronWorker_Exception extends Exception{
}
-
/**
* Class that wraps IronWorker API calls.
*/
-class IronWorker{
-
- //Header Constants
- const header_user_agent = "iron_worker_php-1.2.1";
- const header_accept = "application/json";
- const header_accept_encoding = "gzip, deflate";
- const HTTP_OK = 200;
- const HTTP_CREATED = 201;
- const HTTP_ACCEPTED = 202;
+class IronWorker extends IronCore{
- const POST = 'POST';
- const GET = 'GET';
- const DELETE = 'DELETE';
-
- public $max_retries = 5;
- public $debug_enabled = false;
- public $ssl_verifypeer = true;
-
- private $default_values = array(
+ protected $client_version = '1.2.1';
+ protected $client_name = 'iron_worker_php';
+ protected $product_name = 'iron_worker';
+ protected $default_values = array(
'protocol' => 'https',
'host' => 'worker-aws-us-east-1.iron.io',
'port' => '443',
'api_version' => '2',
);
- private $url;
- private $token;
- private $api_version;
- private $version;
- private $project_id;
- private $headers;
- private $protocol;
- private $host;
-
/**
* @param string|array|null $config_file_or_options
* Array of options or name of config file.
@@ -322,7 +255,7 @@ public function deleteSchedule($schedule_id){
'schedule_id' => $schedule_id
);
- return $this->apiCall(self::POST, $url, $request);
+ return self::json_decode($this->apiCall(self::POST, $url, $request));
}
/**
@@ -543,20 +476,6 @@ private function postSchedule($name, $options, $payload = array()){
return $shedules->schedules[0]->id;
}
- private function compiledHeaders(){
-
- # Set default headers if no headers set.
- if ($this->headers == null){
- $this->setCommonHeaders();
- }
-
- $headers = array();
- foreach ($this->headers as $k => $v){
- $headers[] = "$k: $v";
- }
- return $headers;
- }
-
private function runtimeFileType($name) {
if(empty($name)){
return false;
@@ -576,193 +495,10 @@ private function runtimeFileType($name) {
}
}
- private function apiCall($type, $url, $params = array(), $raw_post_data = null){
- $url = "{$this->url}$url";
-
- $s = curl_init();
- if (! isset($params['oauth'])) {
- $params['oauth'] = $this->token;
- }
- switch ($type) {
- case self::DELETE:
- $fullUrl = $url . '?' . http_build_query($params);
- $this->debug('apiCall fullUrl', $fullUrl);
- curl_setopt($s, CURLOPT_URL, $fullUrl);
- curl_setopt($s, CURLOPT_CUSTOMREQUEST, self::DELETE);
- break;
- case self::POST:
- $this->debug('apiCall url', $url);
- curl_setopt($s, CURLOPT_URL, $url);
- curl_setopt($s, CURLOPT_POST, true);
- if ($raw_post_data){
- curl_setopt($s, CURLOPT_POSTFIELDS, $raw_post_data);
- }else{
- curl_setopt($s, CURLOPT_POSTFIELDS, json_encode($params));
- }
- break;
- case self::GET:
- $fullUrl = $url . '?' . http_build_query($params);
- $this->debug('apiCall fullUrl', $fullUrl);
- curl_setopt($s, CURLOPT_URL, $fullUrl);
- break;
- }
- curl_setopt($s, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
- curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($s, CURLOPT_HTTPHEADER, $this->compiledHeaders());
- return $this->callWithRetries($s);
- }
-
- private function callWithRetries($s){
- for ($retry = 0; $retry < $this->max_retries; $retry++){
- $_out = curl_exec($s);
- $status = curl_getinfo($s, CURLINFO_HTTP_CODE);
- switch ($status) {
- case self::HTTP_OK:
- case self::HTTP_CREATED:
- case self::HTTP_ACCEPTED:
- curl_close($s);
- return $_out;
- case Http_Exception::INTERNAL_ERROR:
- if (strpos($_out, "EOF") !== false){
- self::waitRandomInterval($retry);
- }else{
- curl_close($s);
- $this->reportHttpError($status, $_out);
- }
- break;
- case Http_Exception::SERVICE_UNAVAILABLE:
- self::waitRandomInterval($retry);
- break;
- default:
- curl_close($s);
- $this->reportHttpError($status, $_out);
- }
- }
- curl_close($s);
- return $this->reportHttpError(503, "Service unavailable");
- }
-
- private function reportHttpError($status, $text){
- throw new Http_Exception("http error: {$status} | {$text}", $status);
- }
-
-
- /**
- * Wait for a random delay between 0 and (4^currentRetry * 100) milliseconds
- *
- * @static
- * @param int $retry currentRetry
- */
- private static function waitRandomInterval($retry){
- $max_delay = pow(4, $retry)*100*1000;
- usleep(rand(0, $max_delay));
- }
-
-
- /**
- * @param array|string|null $config_file_or_options
- * array of options or name of config file
- * @return array
- * @throws InvalidArgumentException
- */
- private function getConfigData($config_file_or_options){
- if(is_string($config_file_or_options)){
- if (!file_exists($config_file_or_options)){
- throw new InvalidArgumentException("Config file $config_file_or_options not found");
- }
- $this->loadConfigFile($config_file_or_options);
- }elseif(is_array($config_file_or_options)){
- $this->loadFromHash($config_file_or_options);
- }
-
- $this->loadConfigFile('iron.ini');
- $this->loadConfigFile('iron.json');
-
- $this->loadFromEnv('IRON_WORKER');
- $this->loadFromEnv('IRON');
-
- $this->loadConfigFile(self::homeDir() . '.iron.ini');
- $this->loadConfigFile(self::homeDir() . '.iron.json');
-
- $this->loadFromHash($this->default_values);
-
- if (empty($this->token) || empty($this->project_id)){
- throw new InvalidArgumentException("token or project_id not found in any of the available sources");
- }
- }
-
-
- private function loadFromHash($options){
- if (empty($options)) return;
- $this->setVarIfValue('token', $options);
- $this->setVarIfValue('project_id', $options);
- $this->setVarIfValue('protocol', $options);
- $this->setVarIfValue('host', $options);
- $this->setVarIfValue('port', $options);
- $this->setVarIfValue('api_version', $options);
- }
-
- private function loadFromEnv($prefix){
- $this->setVarIfValue('token', getenv($prefix. "_TOKEN"));
- $this->setVarIfValue('project_id', getenv($prefix. "_PROJECT_ID"));
- $this->setVarIfValue('protocol', getenv($prefix. "_SCHEME"));
- $this->setVarIfValue('host', getenv($prefix. "_HOST"));
- $this->setVarIfValue('port', getenv($prefix. "_PORT"));
- $this->setVarIfValue('api_version', getenv($prefix. "_API_VERSION"));
- }
-
- private function setVarIfValue($key, $options_or_value){
- if (!empty($this->$key)) return;
- if (is_array($options_or_value)){
- if (!empty($options_or_value[$key])){
- $this->$key = $options_or_value[$key];
- }
- }else{
- if (!empty($options_or_value)){
- $this->$key = $options_or_value;
- }
- }
- }
-
- private function loadConfigFile($file){
- if (!file_exists($file)) return;
- $data = @parse_ini_file($file, true);
- if ($data === false){
- $data = json_decode(file_get_contents($file), true);
- }
- if (!is_array($data)){
- throw new InvalidArgumentException("Config file $file not parsed");
- };
-
- if (!empty($data['iron_worker'])) $this->loadFromHash($data['iron_worker']);
- if (!empty($data['iron'])) $this->loadFromHash($data['iron']);
- $this->loadFromHash($data);
- }
-
- private static function homeDir(){
- if ($home_dir = getenv('HOME')){
- // *NIX
- return $home_dir.DIRECTORY_SEPARATOR;
- }else{
- // Windows
- return getenv('HOMEDRIVE').getenv('HOMEPATH').DIRECTORY_SEPARATOR;
- }
- }
-
private function getFileContent($filename){
return file_get_contents($filename);
}
- private function setCommonHeaders(){
- $this->headers = array(
- 'Authorization' => "OAuth {$this->token}",
- 'User-Agent' => self::header_user_agent,
- 'Content-Type' => 'application/json',
- 'Accept' => self::header_accept,
- 'Accept-Encoding' => self::header_accept_encoding
- );
- }
-
private function setJsonHeaders(){
$this->setCommonHeaders();
}
@@ -772,12 +508,6 @@ private function setPostHeaders(){
$this->headers['Content-Type'] ='multipart/form-data';
}
- private function debug($var_name, $variable){
- if ($this->debug_enabled){
- echo "{$var_name}: ".var_export($variable,true)."\n";
- }
- }
-
private static function fileNamesRecursive($dir, $base_dir = ''){
$dir .= DIRECTORY_SEPARATOR;
$files = scandir($dir);
@@ -797,29 +527,6 @@ private static function fileNamesRecursive($dir, $base_dir = ''){
return $names;
}
- private static function dateRfc3339($timestamp = 0) {
- if ($timestamp instanceof DateTime) {
- $timestamp = $timestamp->getTimestamp();
- }
- if (!$timestamp) {
- $timestamp = time();
- }
- return gmdate('c', $timestamp);
- }
-
- private static function json_decode($response){
- $data = json_decode($response);
- if (function_exists('json_last_error')){
- $json_error = json_last_error();
- if($json_error != JSON_ERROR_NONE) {
- throw new JSON_Exception($json_error);
- }
- }elseif($data === null){
- throw new JSON_Exception("Common JSON error");
- }
- return $data;
- }
-
/**
* Contain php code that adds to worker before upload
Oops, something went wrong.

0 comments on commit 9a15218

Please sign in to comment.