2017-12-29 11 views
0

여기 Redmine에서 curl을 사용하여 모든 문제를 가져 오려고합니다. 아래 phl은 내가 사용하는 코드입니다.redmine 응용 프로그램에서 curl을 사용하여 모든 문제를 가져 오는 방법 PHP

내 CURL.php

: 레드 마인에 flie 클래스 파일/redmine_curl.php 여기

<?php # Redmine Api 

class class_redmine{  
function get_upload_token($filecontent){ 
global $redmine_url , $redmine_key; 
$upload_url = $redmine_url.'uploads.json?key='.$redmine_key; 
$request['type'] = 'post'; 
$request['content_type'] = 'application/octet-stream'; 
//$filecontent = file_get_contents('test.php');   
return $token = $this->curl_redmine($upload_url,$request,$filecontent); 
//$token->upload->token; 
} 
#Issue 
function create_issue($post_data){ 
global $redmine_url , $redmine_key; 
$issue_url = $redmine_url.'issues.json?key='.$redmine_key; 
$request['type'] = 'post'; 
$request['content_type'] = 'application/json'; 
return $this->curl_redmine($issue_url,$request,$post_data); 
} 
function get_issue($issue_id='',$project_id=''){ 
global $redmine_url , $redmine_key; 
if($project_id!=''){ 
$issue_url = $redmine_url.'issues.json?key='.$redmine_key.'&project_id='.$project_id; 
}else{ $issue_url = ($issue_id=='')?$redmine_url.'issues.json?key='.$redmine_key : $redmine_url.'issues/'.$issue_id.'.json?key='.$redmine_key; 
} 
return $this->curl_redmine($issue_url,'',''); 
} 
#Projects 
function get_projects($project_id=''){ 
global $redmine_url , $redmine_key; 
$proj_url = ($project_id=='')?$redmine_url.'projects.json?key='.$redmine_key : $redmine_url.'projects/'.$project_id.'.json?key='.$redmine_key;   
return $this->curl_redmine($proj_url,'',''); 
} 
#Curl 
function curl_redmine($redmine_url,$request='',$post_data=''){ 
if(!isset($request['type'])){ $request['type']=null; } 
if(!isset($request['content_type'])){ $request['content_type']=null; } 
//Create a curl object 
$ch = curl_init(); 
//Set the useragent 
$agent = $_SERVER["HTTP_USER_AGENT"]; 
curl_setopt($ch, CURLOPT_USERAGENT, $agent); 

//Set the URL 
curl_setopt($ch, CURLOPT_URL, $redmine_url); 
if($request['type'] == 'post'){ 
//This is a POST query 
curl_setopt($ch, CURLOPT_POST,1); 
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
//Set the post data 
curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                   
'Content-Type: '.$request['content_type'],                    
'Content-Length: ' . strlen($post_data))                  
); 
} 
//We want the content after the query 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);         

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

//Follow Location redirects 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 

/* 
Set the cookie storing files 
Cookie files are necessary since we are logging and session data needs to be saved 
*/ 

//curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); 
//curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); 

//Execute the action to login 
$postResult = curl_exec($ch); 
//if($postResult == false){ return $info = curl_getinfo($ch);} 
$response = json_decode($postResult); 
//echo '<pre>'; print_r($response); echo '</pre>'; 
return $response; 
} 

}//class_redmine 

?> 

이 코드는 25 records.at을주고 내 example.php

<?php 
function get_redmine($methodName='',$data=''){ 
global $redmine_url , $redmine_key; 

$redmine_url = 'http://192.168.12.231:80/'; 
$redmine_key = 'API KEY'; 
include_once('curlcall.php'); 
$obj_redmine = new class_redmine(); 

#check Auth 
$res = $obj_redmine->get_projects(); 
if(!isset($res->projects) || (isset($res->total_count) && ($res->total_count)==0)){ return -1; } 

switch($methodName){ 
case 'check_status' : return $login_integrate; 
##check redmine integration in vision break; 

##Project 
case 'projectAll' : return $obj_redmine->get_projects(); #used 
break; 
case 'projectById' : return $obj_redmine->get_projects($data['project_id']); 
break; 

##Issues 
case 'issueAll' : return $obj_redmine->get_issue(); 
break; 
case 'issueByProjectId' : return $obj_redmine->get_issue('',$data['project_id']); 
break; 
case 'uploadFileToIssue' : return $obj_redmine->get_upload_token($data); 
break; 
default: return 0; 
} 
} 

#get all issue 
$res = get_redmine('issueAll'); 

echo '<pre>';print_r($res); 
?> 

입니다 내 출력의 끝은 총계 : 201 오프셋 : 0 제한 : 25 나는 모든 문제를 해결하는 방법을 이해할 수 없다. ase 도움 사람, 나는 PHP에 대한 새로운 오전.

답변

0

대답을 모두 읽으려면 the API docs입니다. 더 많은 결과를 얻을 수있는 한계 매개 변수를 사용하고, 오프셋 매개 변수는 그래서 더

/issues.json?offset=0&limit=100 다음 100 문제를 가져올 것이다 처음 100 문제

/issues.json?offset=100&limit=100를 가져올 것이다로드,하고.

...하지만 가장 먼저해야 할 일은 형식이 지정되지 않은 것은 읽기가 매우 짜증나기 때문에 코드를 포맷하는 것입니다. curl이 자동으로 그 헤더를 추가하기 때문에 curl이 오타를 만들지 않을 것이고, 우리와 달리 progammers (curl은 모든 커밋에 대해 자동 테스트가 실행됩니다.)와는 달리 길이를 잘못 계산하지 않기 때문에이 라인을 제거하십시오. 'Content-Length: ' . strlen ($post_data) 이 널 (null) 일 수 없습니다 때문에 반드시 내용 길이가 올바른지 확인하기 위해, 내가 그 테스트 스위트의 일부)하지 내기,이

if (! isset ($request ['content_type'])) { 
    $request ['content_type'] = null; 
} 

제거. 나중에 참조 할 수 있도록 글자 그대로 생각하지 못한다면 application/octet-stream으로 설정하십시오. 그러나이 경우에도 API 문서에 application/jsonapplication/xml 만 지원되는 POST 인코딩이 있으므로 올바른 경우는 잘못되었습니다. 것 여기에서 :

모든 문제를 가져 오는 경우와
if (isset ($request ['content_type']) && $request ['content_type'] !== 'application/json' && $request ['content_type'] !== 'application/xml') { 
    throw new \InvalidArgumentException ('invalid content-type specified. supported types are "application/json" and "application/xml"'); 
} 
if($request ['type'] === 'post' && !isset($request ['content_type'])){ 
    throw new \LogicException('no content-type was specified for this POST request, which is required. supported types are "application/json" and "application/xml"'); 
} 

if (! $issue_id) { 
    // first we check how many issues there are (OPTIMIZEME: there is probably a more efficient way to do this, for example limit=0 ?) 
    $issues_url .= '&limit=1'; 
    $number_of_issues = $this->curl_redmine ($issue_url, '', '') ['total_count']; 
    $issue_url = substr ($issues_url, 0, - 1) . $number_of_issues; 
} 

처럼, 다음 제한 = NUMBER_OF_ISSUES와 두 번째 요청을, 얼마나 많은 문제를보고 먼저 요청을 이 모든 것을 합치면 이걸 얻을 수있다.

(그런데, 나의 부분에 완전히 테스트되지 않은 것입니다.)
<?php 
// Redmine Api 
class class_redmine { 
    function get_upload_token($filecontent) { 
     global $redmine_url, $redmine_key; 
     $upload_url = $redmine_url . 'uploads.json?key=' . $redmine_key; 
     $request ['type'] = 'post'; 
     $request ['content_type'] = 'application/octet-stream'; 
     // $filecontent = file_get_contents('test.php'); 
     return $token = $this->curl_redmine ($upload_url, $request, $filecontent); 
     // $token->upload->token; 
    } 
    // Issue 
    function create_issue($post_data) { 
     global $redmine_url, $redmine_key; 
     $issue_url = $redmine_url . 'issues.json?key=' . $redmine_key; 
     $request ['type'] = 'post'; 
     $request ['content_type'] = 'application/json'; 
     return $this->curl_redmine ($issue_url, $request, $post_data); 
    } 
    function get_issue($issue_id = '', $project_id = '') { 
     global $redmine_url, $redmine_key; 
     if ($project_id != '') { 
      $issue_url = $redmine_url . 'issues.json?key=' . $redmine_key . '&project_id=' . $project_id; 
     } else { 
      $issue_url = ($issue_id == '') ? $redmine_url . 'issues.json?key=' . $redmine_key : $redmine_url . 'issues/' . $issue_id . '.json?key=' . $redmine_key; 
     } 
     if (! $issue_id) { 
      // first we check how many issues there are (OPTIMIZEME: there is probably a more efficient way to do this, for example limit=0 ?) 
      $issues_url .= '&limit=1'; 
      $number_of_issues = $this->curl_redmine ($issue_url, '', '') ['total_count']; 
      $issue_url = substr ($issues_url, 0, - 1) . $number_of_issues; 
     } 
     return $this->curl_redmine ($issue_url, '', ''); 
    } 
    // Projects 
    function get_projects($project_id = '') { 
     global $redmine_url, $redmine_key; 
     $proj_url = ($project_id == '') ? $redmine_url . 'projects.json?key=' . $redmine_key : $redmine_url . 'projects/' . $project_id . '.json?key=' . $redmine_key; 
     return $this->curl_redmine ($proj_url, '', ''); 
    } 
    // Curl 
    function curl_redmine($redmine_url, $request = '', $post_data = '') { 
     if (! isset ($request ['type'])) { 
      $request ['type'] = null; 
     } 
     if (isset ($request ['content_type']) && $request ['content_type'] !== 'application/json' && $request ['content_type'] !== 'application/xml') { 
      throw new \InvalidArgumentException ('invalid content-type specified. supported types are "application/json" and "application/xml"'); 
     } 
     if ($request ['type'] === 'post' && ! isset ($request ['content_type'])) { 
      throw new \LogicException ('no content-type was specified for this POST request, which is required. supported types are "application/json" and "application/xml"'); 
     } 
     // Create a curl object 
     $ch = curl_init(); 
     // Set the useragent 
     $agent = $_SERVER ["HTTP_USER_AGENT"]; 
     curl_setopt ($ch, CURLOPT_USERAGENT, $agent); 

     // Set the URL 
     curl_setopt ($ch, CURLOPT_URL, $redmine_url); 
     if ($request ['type'] == 'post') { 
      // This is a POST query 
      curl_setopt ($ch, CURLOPT_POST, 1); 
      // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
      // Set the post data 
      curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data); 

      curl_setopt ($ch, CURLOPT_HTTPHEADER, array (
        'Content-Type: ' . $request ['content_type'] 
      )); 
     } 
     // We want the content after the query 
     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); 

     curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false); 

     // Follow Location redirects 
     curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); 

     /* 
     * Set the cookie storing files 
     * Cookie files are necessary since we are logging and session data needs to be saved 
     */ 

     // curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); 
     // curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); 

     // Execute the action to login 
     $postResult = curl_exec ($ch); 
     // if($postResult == false){ return $info = curl_getinfo($ch);} 
     $response = json_decode ($postResult); 
     // echo '<pre>'; print_r($response); echo '</pre>'; 
     return $response; 
    } 
}//class_redmine 

당신은 수정해야 또 다른 문제는 당신의 컬 코드 오류 검출하지 않고 완벽하게 실행되는 것입니다. 예를 들어, curl_setopt는 옵션을 설정하는 데 문제가 있으면 bool (false)을 반환하고, 전송 중에 문제가 발생하면 curl_exec()가 bool (false)을 반환하고 오류 감지를 추가합니다.

function ecurl_setopt (/*resource*/$ch , int $option , /*mixed*/ $value):bool{ 
    $ret=curl_setopt($ch,$option,$value); 
    if($ret!==true){ 
     //option should be obvious by stack trace 
     throw new RuntimeException ('curl_setopt() failed. curl_errno: ' . return_var_dump (curl_errno ($ch)).'. curl_error: '.curl_error($ch)); 
    } 
    return true; 
} 
function ecurl_exec (/*resource*/$ch):bool{ 
    $ret=curl_exec($ch); 
    if($ret===false){ 
     throw new RuntimeException ('curl_exec() failed. curl_errno: ' . return_var_dump (curl_errno ($ch)).'. curl_error: '.curl_error($ch)); 
    } 
    return $ret; 
} 


function return_var_dump(/*...*/){ 
    $args = func_get_args(); 
    ob_start(); 
    call_user_func_array ('var_dump', $args); 
    return ob_get_clean(); 
} 

에 관계없이 컬 기능을 던졌습니다있는, 항상 호출 될 것입니다 당신이 어떤 메모리를 누출하지 않는, 확실 curl_close을하는 try{...curl...}finally{curl_close($ch);} 주위에 모든 것을 포장 할 수 있는지 확인하는 것이 :이 기능은 오히려 쉽게한다 예외.(이것은 메모리 누출을 방지합니다)

+0

예, API에 있습니다.하지만 코드를 어디에서 사용해야하는지 명확하지 않습니다. 제안을 해주십시오. – mani

+0

@mani ok 그런 다음 내 답변을 업데이트했습니다. – hanshenrik

관련 문제