98 lines
2.5 KiB
PHP
98 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Clients;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class JenkinsClient
|
|
{
|
|
private ?string $host;
|
|
private ?string $username;
|
|
private ?string $apiToken;
|
|
private int $timeout;
|
|
|
|
public function __construct()
|
|
{
|
|
$config = config('jenkins', []);
|
|
$this->host = rtrim($config['host'] ?? '', '/');
|
|
$this->username = $config['username'] ?? null;
|
|
$this->apiToken = $config['api_token'] ?? null;
|
|
$this->timeout = $config['timeout'] ?? 30;
|
|
}
|
|
|
|
public function isConfigured(): bool
|
|
{
|
|
return !empty($this->host) && !empty($this->username) && !empty($this->apiToken);
|
|
}
|
|
|
|
public function getJobInfo(string $jobName): ?array
|
|
{
|
|
return $this->request("/job/{$jobName}/api/json");
|
|
}
|
|
|
|
public function getBuildInfo(string $jobName, int $buildNumber): ?array
|
|
{
|
|
return $this->request("/job/{$jobName}/{$buildNumber}/api/json");
|
|
}
|
|
|
|
public function getLastBuild(string $jobName): ?array
|
|
{
|
|
return $this->request("/job/{$jobName}/lastBuild/api/json");
|
|
}
|
|
|
|
public function getBuilds(string $jobName, int $limit = 10): array
|
|
{
|
|
$jobInfo = $this->getJobInfo($jobName);
|
|
if (!$jobInfo || empty($jobInfo['builds'])) {
|
|
return [];
|
|
}
|
|
|
|
$builds = array_slice($jobInfo['builds'], 0, $limit);
|
|
$result = [];
|
|
|
|
foreach ($builds as $build) {
|
|
$buildInfo = $this->getBuildInfo($jobName, $build['number']);
|
|
if ($buildInfo) {
|
|
$result[] = $buildInfo;
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function request(string $path): ?array
|
|
{
|
|
if (!$this->isConfigured()) {
|
|
Log::warning('Jenkins client is not configured');
|
|
return null;
|
|
}
|
|
|
|
$url = $this->host . $path;
|
|
|
|
try {
|
|
$response = Http::timeout($this->timeout)
|
|
->withBasicAuth($this->username, $this->apiToken)
|
|
->get($url);
|
|
|
|
if ($response->successful()) {
|
|
return $response->json();
|
|
}
|
|
|
|
Log::warning('Jenkins API request failed', [
|
|
'url' => $url,
|
|
'status' => $response->status(),
|
|
]);
|
|
|
|
return null;
|
|
} catch (\Throwable $e) {
|
|
Log::error('Jenkins API request error', [
|
|
'url' => $url,
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
|
|
return null;
|
|
}
|
|
}
|
|
}
|