function doCall($method, $parameters, $instance, $serverKey)
{
    $callParameters = validateCallParameters($method, $parameters, $instance);
    $reflectedClass = new ReflectionClass(get_class($instance));
    $reflectedMethod = $reflectedClass->getMethod($method->getName());
    $result;
    $result = $reflectedMethod->invokeArgs($instance, $callParameters);
    $resultJson = "";
    //Print custom errors
    $reflectedErrorMethod = $reflectedClass->getMethod("getErrors");
    $reflectedErrors = $reflectedErrorMethod->invoke($instance);
    if (!empty($reflectedErrors)) {
        $resultJson .= "[";
        foreach ($reflectedErrors as $reflectedError) {
            $reflectedErrorClass = new ReflectionClass(get_class($reflectedError));
            $code = $reflectedErrorClass->getMethod("getCode")->invoke($reflectedError);
            $message = $reflectedErrorClass->getMethod("getMessage")->invoke($reflectedError);
            $resultJson .= '{"code":' . JsonUtils::encodeToJson($code) . ',"message":' . JsonUtils::encodeToJson($message) . '},';
        }
        $resultJson = JsonUtils::removeLastChar($reflectedErrors, $resultJson);
        $resultJson .= "]";
    } else {
        $resultJson .= serializeMethodResult($method, $result, $instance, $serverKey);
    }
    return $resultJson;
}
function serializeArray($result, $instance, $isSimpleResult, $serverKey)
{
    $json = "";
    if (is_array($result)) {
        if (ArrayUtils::isAssociative($result)) {
            $json .= "{";
            foreach ($result as $key => $value) {
                $json .= '"' . $key . '":';
                if (is_object($value)) {
                    $json .= serializeObject($value, $instance, false, $serverKey);
                } else {
                    if (is_array($value)) {
                        $json .= serializeArray($value, $instance, $isSimpleResult, $serverKey);
                    } else {
                        $json .= serializeObject($value, $instance, !is_object($value), $serverKey);
                    }
                }
                $json .= ",";
            }
        } else {
            $json .= "[";
            for ($i = 0; $i < count($result); $i++) {
                $json .= serializeObject($result[$i], $instance, $isSimpleResult, $serverKey) . ",";
            }
        }
        $json = JsonUtils::removeLastChar($result, $json);
        if (ArrayUtils::isAssociative($result)) {
            $json .= "}";
        } else {
            $json .= "]";
        }
    }
    return $json;
}
 function testSerializeError()
 {
     $this->assertEquals('[{"message":"this is an error","code":2}]', JsonUtils::serializeError("this is an error", 2));
     $this->assertEquals('[{"message":"this is an error","code":null}]', JsonUtils::serializeError("this is an error", null));
     $this->assertEquals('[{"message":null,"code":null}]', JsonUtils::serializeError(null, null));
     $this->assertEquals('[{"message":"this is a \\"great\\" error","code":2}]', JsonUtils::serializeError('this is a "great" error', 2));
 }
 static function Instance()
 {
     if (!isset(self::$mInstance)) {
         self::$mInstance = new JsonUtils();
     }
     return self::$mInstance;
 }
Beispiel #5
0
 /** Convertit un tableau en chaine Json
  *
  * @param $array tableau à Convertir Json
  * @return La représentation Json de ce tableau
  */
 public static function array2JString($array)
 {
     $jString = json_encode($array, JSON_UNESCAPED_UNICODE);
     if ($jString === false) {
         JsonUtils::throwLastJsonError("Can't encode array to Json String. {$array}");
     }
     return $jString;
 }
Beispiel #6
0
 /**
  * Encodes an Iterator into a json string
  *
  * @param $aIterator Iterator            
  *
  * @return string the encoded array
  */
 public static function encodeIterator(\Iterator $aIterator)
 {
     $result = array();
     foreach ($aIterator as $item) {
         if ($item instanceof \SplFileInfo) {
             if ($item->getFilename() === '.' || $item->getFilename() === '..') {
                 continue;
             }
             $result[] = JsonUtils::fileToModel($item);
         } else {
             $result[] = $item;
         }
     }
     return self::encode($result);
 }
function discoverObjects($configuration, $objectsFound)
{
    $result = "";
    $objects = $configuration->getObjects();
    $objectsDone = array();
    foreach ($objects as $object) {
        $result .= "\t<object ";
        $className = $object->getClassName();
        $result .= "name=\"" . $className . "\" >\n";
        foreach ($object->getFields() as $field) {
            $result .= "\t\t<field";
            $objectName = $field->getObject();
            if ($objectName != null) {
                if (!in_array($objectName, $objectsFound) && !in_array($objectName, $objectsDone)) {
                    array_push($objectsFound, $objectName);
                }
            }
            if (!empty($objectName)) {
                $result .= " object=\"" . $objectName . "\"";
            }
            $result .= " array=\"" . ($field->isArray() ? "true" : "false") . "\"";
            $result .= " optional=\"" . ($field->isOptional() ? "true" : "false") . "\"";
            $fieldName = $field->getName();
            $result .= ">" . $fieldName . "</field>\n";
        }
        $result .= "\t</object>\n";
        array_push($objectsDone, $className);
        $objectsFound = array_diff($objectsFound, array($className));
    }
    $result .= "\t<object name=\"StandardMashapeError\">\n\t\t<field>code</field>\n\t\t<field>message</field>\n\t</object>\n";
    // Check that all objects exist
    if (!empty($objectsFound)) {
        $missingObjects = "";
        foreach ($objectsFound as $requiredObject) {
            $missingObjects .= $requiredObject . ",";
        }
        $missingObjects = JsonUtils::removeLastChar($objectsFound, $missingObjects);
        throw new MashapeException(sprintf(EXCEPTION_MISSING_OBJECTS, $missingObjects), EXCEPTION_XML_CODE);
    }
    return $result;
}
 protected function returnJSON($value)
 {
     $result = JsonUtils::Instance()->VarToJSON($value);
     //echo "returnJSON: $result";
     return $result;
 }
function serializeObject($result, $instance, $isSimpleResult, $serverKey)
{
    $json = "";
    if ($isSimpleResult) {
        // It's a simple result, just serialize it
        $json = JsonUtils::encodeToJson($result);
    } else {
        // It's a custom object, let's serialize recursively every field
        $className = get_class($result);
        $reflectedClass = new ReflectionClass($className);
        $xmlObject = RESTConfigurationLoader::getObject($className, $serverKey);
        if (empty($xmlObject)) {
            throw new MashapeException(sprintf(EXCEPTION_UNKNOWN_OBJECT, $className), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
        }
        // Start element
        $json .= "{";
        // Serialize fields
        $fields = $xmlObject->getFields();
        for ($i = 0; $i < count($fields); $i++) {
            $field = $fields[$i];
            $fieldName = $field->getName();
            $fieldMethod = $field->getMethod();
            $fieldValue = null;
            if (empty($fieldMethod)) {
                if ($reflectedClass->hasProperty($fieldName)) {
                    $reflectedProperty = $reflectedClass->getProperty($fieldName);
                    if ($reflectedProperty->isPublic()) {
                        $fieldValue = $reflectedProperty->getValue($result);
                    } else {
                        // Try using the __get magic method
                        $fieldValue = $reflectedClass->getMethod("__get")->invokeArgs($result, array($fieldName));
                    }
                } else {
                    if (ArrayUtils::existKey($fieldName, get_object_vars($result))) {
                        $fieldValue = $result->{$fieldName};
                    } else {
                        throw new MashapeException(sprintf(EXCEPTION_FIELD_NOTFOUND, $fieldName), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
                    }
                }
            } else {
                $fieldValue = $reflectedClass->getMethod($fieldMethod)->invoke($result);
            }
            if ($fieldValue === null && $field->isOptional()) {
                // Don't serialize the field
                continue;
            }
            $json .= '"' . $fieldName . '":';
            if ($fieldValue === null) {
                $json .= JsonUtils::encodeToJson($fieldValue);
            } else {
                $isSimpleField = isSimpleField($field);
                if ($field->isArray()) {
                    if (is_array($fieldValue)) {
                        $json .= serializeArray($fieldValue, $instance, isSimpleField($field), $serverKey);
                    } else {
                        // The result it's not an array although it was described IT WAS an array
                        throw new MashapeException(sprintf(EXCEPTION_EXPECTED_ARRAY_RESULT, $fieldName, $className), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
                    }
                } else {
                    if (is_array($fieldValue)) {
                        // The result it's an array although it was described IT WAS NOT an array
                        throw new MashapeException(sprintf(EXCEPTION_UNEXPECTED_ARRAY_RESULT, $fieldName, $className), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
                    } else {
                        $json .= serializeObject($fieldValue, $instance, $isSimpleField, $serverKey);
                    }
                }
            }
            $json .= ",";
        }
        if (substr($json, strlen($json) - 1, 1) != "{") {
            $json = JsonUtils::removeLastChar($fields, $json);
        }
        // Close element
        $json .= "}";
    }
    return $json;
}
Beispiel #10
0
 public function toJson($pretty, $tabs = false)
 {
     $json = JsonUtils::dataToJson($this->data, $pretty);
     if ($tabs && $pretty) {
         $json = preg_replace_callback('/^( +)/m', function ($m) {
             return str_repeat("\t", (int) strlen($m[1]) / 4);
         }, $json);
     }
     return $json;
 }
Beispiel #11
0
 /** Obtenir le contenue complet des voicekey au format Json */
 public function setAllVoicekeyFromJsonStr($dataStr)
 {
     JsonUtils::jString2JFile($dataStr, CONF_FILE_VOICEKEY);
 }
Beispiel #12
0
 public static function dataOrder($data, $schema)
 {
     if (is_object($data) && ($properties = JsonUtils::get($schema, 'properties'))) {
         $result = array();
         foreach ($properties as $key => $value) {
             if (isset($data->{$key})) {
                 $result[$key] = static::dataOrder($data->{$key}, $properties->{$key});
                 unset($data->{$key});
             }
         }
         $result = (object) array_merge($result, (array) $data);
     } elseif (is_array($data) && ($items = JsonUtils::get($schema, 'items'))) {
         $objSchema = is_object($schema->items) ? $schema->items : null;
         foreach ($data as $item) {
             $itemSchema = $objSchema ?: (next($schema->items) ?: null);
             $result[] = static::dataOrder($item, $itemSchema);
         }
     } else {
         $result = $data;
     }
     return $result;
 }
Beispiel #13
0
 public static function handleAPI($instance, $serverKey)
 {
     header("Content-type: application/json");
     try {
         if ($instance == null) {
             throw new MashapeException(EXCEPTION_INSTANCE_NULL, EXCEPTION_SYSTEM_ERROR_CODE);
         }
         $requestMethod = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : null;
         $params;
         if ($requestMethod == 'post') {
             $params = array_merge(self::getAllParams($_GET), self::getAllParams($_POST));
         } else {
             if ($requestMethod == 'get') {
                 $params = self::getAllParams($_GET);
             } else {
                 if ($requestMethod == 'put' || $requestMethod == 'delete') {
                     $params = HttpUtils::parseQueryString(file_get_contents("php://input"));
                 } else {
                     throw new MashapeException(EXCEPTION_NOTSUPPORTED_HTTPMETHOD, EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE);
                 }
             }
         }
         $operation = isset($params[OPERATION]) ? $params[OPERATION] : null;
         unset($params[OPERATION]);
         // remove the operation parameter
         if (empty($operation)) {
             $operation = "call";
         }
         if ($operation != null) {
             $result;
             switch (strtolower($operation)) {
                 case "discover":
                     header("Content-type: application/xml");
                     $discover = new Discover();
                     $result = $discover->handle($instance, $serverKey, $params, $requestMethod);
                     break;
                 case "call":
                     $call = new Call();
                     $result = $call->handle($instance, $serverKey, $params, $requestMethod);
                     break;
                 default:
                     throw new MashapeException(EXCEPTION_NOTSUPPORTED_OPERATION, EXCEPTION_NOTSUPPORTED_OPERATION_CODE);
             }
             $jsonpCallback = isset($params[CALLBACK]) ? $params[CALLBACK] : null;
             if (empty($jsonpCallback)) {
                 // Print the output
                 echo $result;
             } else {
                 if (self::validateCallback($jsonpCallback)) {
                     echo $jsonpCallback . '(' . $result . ')';
                 } else {
                     throw new MashapeException(EXCEPTION_INVALID_CALLBACK, EXCEPTION_SYSTEM_ERROR_CODE);
                 }
             }
         } else {
             // Operation not supported
             throw new MashapeException(EXCEPTION_NOTSUPPORTED_OPERATION, EXCEPTION_NOTSUPPORTED_OPERATION_CODE);
         }
     } catch (Exception $e) {
         //If it's an ApizatorException then print the specific code
         if ($e instanceof MashapeException) {
             header("Content-type: application/json");
             $code = $e->getCode();
             switch ($code) {
                 case EXCEPTION_XML_CODE:
                     header("HTTP/1.0 500 Internal Server Error");
                     break;
                 case EXCEPTION_INVALID_HTTPMETHOD_CODE:
                     header("HTTP/1.0 405 Method Not Allowed");
                     break;
                 case EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE:
                     header("HTTP/1.0 405 Method Not Allowed");
                     break;
                 case EXCEPTION_NOTSUPPORTED_OPERATION_CODE:
                     header("HTTP/1.0 501 Not Implemented");
                     break;
                 case EXCEPTION_METHOD_NOTFOUND_CODE:
                     header("HTTP/1.0 404 Not Found");
                     break;
                 case EXCEPTION_AUTH_INVALID_CODE:
                     self::setUnauthorizedResponse();
                     break;
                 case EXCEPTION_AUTH_INVALID_SERVERKEY_CODE:
                     self::setUnauthorizedResponse();
                     break;
                 case EXCEPTION_REQUIRED_PARAMETERS_CODE:
                     header("HTTP/1.0 200 OK");
                     break;
                 case EXCEPTION_GENERIC_LIBRARY_ERROR_CODE:
                     header("HTTP/1.0 500 Internal Server Error");
                     break;
                 case EXCEPTION_INVALID_APIKEY_CODE:
                     self::setUnauthorizedResponse();
                     break;
                 case EXCEPTION_EXCEEDED_LIMIT_CODE:
                     self::setUnauthorizedResponse();
                     break;
                 case EXCEPTION_SYSTEM_ERROR_CODE:
                     header("HTTP/1.0 500 Internal Server Error");
                     break;
             }
             echo JsonUtils::serializeError($e->getMessage(), $code);
         } else {
             //Otherwise print a "generic exception" code
             header("HTTP/1.0 500 Internal Server Error");
             echo JsonUtils::serializeError($e->getMessage(), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
         }
     }
 }
function serializeParametersQueryString($method, $instance, $routeParameters = null)
{
    $reflectedClass = new ReflectionClass(get_class($instance));
    $reflectedMethod = $reflectedClass->getMethod($method->getName());
    $reflectedParameters = $reflectedMethod->getParameters();
    $result = "";
    for ($i = 0; $i < count($reflectedParameters); $i++) {
        $param = $reflectedParameters[$i];
        if (!empty($routeParameters)) {
            if (in_array($param->name, $routeParameters)) {
                continue;
            }
        }
        if ($i == 0) {
            $result .= "&";
        }
        $result .= $param->name . "={" . $param->name . "}&";
    }
    $result = JsonUtils::removeLastChar($reflectedParameters, $result);
    return $result;
}