예제 #1
0
 /**
  * Map an API request to a resource
  *
  * @since  0.1.0
  * @access public
  * @param  Gdn_Dispatcher $sender
  * @return void
  */
 public function Gdn_Dispatcher_beforeDispatch_handler($sender)
 {
     $path = APIEngine::getRequestURI();
     // Set the call and resource paths if they exist
     $call = val(0, $path);
     $resource = val(1, $path);
     // Abandon the dispatch if this isn't an API call with a valid resource
     if ($call != "api" || !$resource) {
         return;
     }
     APIEngine::setRequestHeaders();
     try {
         // Mark the dispatch with the API version
         $sender->API = c("API.Version", "Undefined");
         // Attempt dispatching the API request
         APIEngine::dispatchRequest();
     } catch (Exception $exception) {
         // As we can"t pass an object to WithControllerMethod(), we extract
         // the values we need manually before passing them on. The exception
         // message is Base64 encoded as WithControllerMethod() mangles
         // the formatting.
         $code = $exception->getCode();
         $message = base64_encode($exception->getMessage());
         $arguments = [$code, $message];
         // Call the Exception method if an exception is thrown
         Gdn::request()->withControllerMethod("API", "Exception", $arguments);
     }
 }
예제 #2
0
 function callApiFunction()
 {
     $jsonResult = $this->createDefaultJson();
     //Создаем JSON  ответа
     $apiName = strtolower($this->apiFunctionName[0]);
     //название API проиводим к нижнему регистру
     if (file_exists($apiName . '.php')) {
         $apiClass = APIEngine::getApiEngineByName($apiName, $this->db);
         //Получаем объект API
         $apiReflection = new ReflectionClass($apiName);
         //Через рефлексию получем информацию о классе объекта
         try {
             $functionName = $this->apiFunctionName[1];
             //Название метода для вызова
             $apiReflection->getMethod($functionName);
             //Провераем наличие метода
             $response = APIConstants::$RESPONSE;
             $jsonParams = json_decode($this->apiFunctionParams);
             //Декодируем параметры запроса в JSON объект
             if ($jsonParams) {
                 $jsonResult->{$response} = $apiClass->{$functionName}($jsonParams);
                 //Вызыаем метод в API который вернет JSON обект
             } else {
                 //Если ошибка декодирования JSON параметров запроса
                 $jsonResult->response->result = false;
                 $jsonResult->response->errno = APIConstants::$ERROR_ENGINE_PARAMS;
                 $jsonResult->response->error = APIConstants::$ERROR_ENGINE_PARAMS_TEXT;
             }
         } catch (Exception $ex) {
             //Непредвиденное исключение
             $jsonResult->response->result = false;
             $jsonResult->response->errno = APIConstants::$ERROR_ENGINE_UNINTENDED;
             $jsonResult->response->error = $ex->getMessage();
         }
     } else {
         //Если запрашиваемый API не найден
         $jsonResult->result = false;
         $jsonResult->errno = APIConstants::$ERROR_ENGINE_ROUTE;
         $jsonResult->error = APIConstants::$ERROR_ENGINE_ROUTE_TEXT;
     }
     return json_encode($jsonResult);
 }
예제 #3
0
<?php

require_once 'BaseAPI.php';
require_once 'APIEngine.php';
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
    $API = new APIEngine($_REQUEST['request']);
    echo $API->processAPI();
} catch (Exception $e) {
    echo json_encode(array('error' => $e->getMessage()));
}
예제 #4
0
<?php

header('Content-type: text/html; charset=UTF-8');
error_reporting(0);
require_once 'apiEngine.php';
if (count($_REQUEST) > 0) {
    $db = DBEngine::getInstance(APIConstants::$DB_NAME, APIConstants::$DB_HOST, APIConstants::$DB_USER, APIConstants::$DB_PASSWORD);
    if (!is_null($db)) {
        foreach ($_REQUEST as $apiFunctionName => $apiFunctionParams) {
            $APIEngine = new APIEngine($apiFunctionName, $apiFunctionParams, $db);
            // http://[адрес сервера]/[путь к папке api]/?[название_api].[название_метода]=[JSON вида {«Hello»:«Hello world»}]
            //?company.getList={"id_ca":5}
            echo $APIEngine->callApiFunction();
            unset($apiEngin);
            break;
        }
    } else {
        $jsonResult = json_decode('{}');
        $jsonResult->response = json_decode('{}');
        $jsonResult->response->result = false;
        $jsonResult->response->error = APIConstants::$ERROR_DB_CONNECT_TEXT;
        $jsonResult->response->errorno = APIConstants::$ERROR_DB_CONNECT;
        echo json_encode($jsonResult);
    }
} else {
    $jsonResult = json_decode('{}');
    $jsonResult->response = json_decode('{}');
    $jsonResult->response->result = false;
    $jsonResult->response->error = APIConstants::$ERROR_ENGINE_ROUTE_TEXT;
    $jsonResult->response->errorno = APIConstants::$ERROR_ENGINE_ROUTE;
    echo json_encode($jsonResult);