GiteaBot/Gitea.php
2019-06-25 08:17:52 +01:00

87 lines
2.3 KiB
PHP

<?php
class Gitea{
public function __construct($url,$user,$pass){
$this->url=$url;
$this->user=$user;
$this->pass=$pass;
}
public function forIssues($user,$repo,$callback,$args=null){
$page=1;
while(1){
$url="repos/$user/$repo/issues?page=$page";
if($args){
$url.='&'.http_build_query($args);
}
$issues=$this->request($url);
if(!$issues) break;
foreach($issues as $issue){
call_user_func($callback,$issue);
}
$page++;
}
}
public function editIssue($issue,$args){
return $this->request($issue->url,'PATCH',$args);
}
public function addLabelsToIssue($issue,$labels){
$args=['labels'=>$labels];
return $this->request($issue->url.'/labels','POST',$args);
}
public function removeLabelFromIssue($issue,$id){
return $this->request($issue->url."/labels/$id",'DELETE');
}
public function addComment($issue,$body){
$args=['body'=>$body];
return $this->request($issue->url.'/comments','POST',$args);
}
public function issueHasLabel($issue,$id){
foreach($issue->labels as $label){
if($label->id==$id){
return true;
}
}
return false;
}
public function request($url, $type='GET', $postFields = null){
if(substr($url,0,4)!='http'){
$url=$this->url.$url;
}
echo ">> $type $url ".json_encode($postFields)." <<\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'james/GiteaBot');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($type!='GET'){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
}
if (!is_null($postFields)) {
$postFields = json_encode($postFields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json',
'Content-Length: '.strlen($postFields), ]);
}
if($this->user) {
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->user.':'.$this->pass);
}
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
}