BitbucketManager.php in Build Hooks 8.2
File
modules/build_hooks_bitbucket/src/BitbucketManager.php
View source
<?php
namespace Drupal\build_hooks_bitbucket;
use Drupal\build_hooks\BuildHookDetails;
use Drupal\Core\Config\ConfigFactoryInterface;
use GuzzleHttp\ClientInterface;
class BitbucketManager {
protected $config;
protected $httpClient;
const API_PREFIX = "https://api.bitbucket.org/2.0/repositories/";
const PIPELINES_PATH = "/pipelines/";
public function __construct(ConfigFactoryInterface $config_factory, ClientInterface $http_client) {
$this->config = $config_factory
->get('build_hooks_bitbucket.settings');
$this->httpClient = $http_client;
}
protected function getPipelinesApiPath(array $settings) {
return self::API_PREFIX . $settings['repo']['workspace'] . '/' . $settings['repo']['slug'] . self::PIPELINES_PATH;
}
protected function getAuth() {
return [
$this->config
->get('username'),
$this->config
->get('password'),
];
}
public function getBuildHookDetailsForPluginConfiguration($settings) {
$buildHookDetails = new BuildHookDetails();
$buildHookDetails
->setUrl($this
->getPipelinesApiPath($settings));
$buildHookDetails
->setMethod('POST');
$body = [
'target' => [
"type" => "pipeline_ref_target",
"ref_name" => $settings['ref']['name'],
"ref_type" => $settings['ref']['type'],
"selector" => [
"type" => $settings['selector']['type'],
"pattern" => $settings['selector']['name'],
],
],
];
$buildHookDetails
->setOptions([
'json' => $body,
'auth' => $this
->getAuth(),
]);
return $buildHookDetails;
}
public function retrieveLatestBuilds(array $settings, $limit = 10) {
$url = $this
->getPipelinesApiPath($settings);
$url .= '?sort=' . urlencode('-created_on') . '&pagelen=' . (int) $limit;
if ($settings['ref']['type'] == 'branch') {
$url .= '&target.branch=' . urlencode($settings['ref']['name']);
}
elseif ($settings['ref']['type'] == 'tag') {
$url .= '&target.tag=' . urlencode($settings['ref']['name']);
}
$options = [
'auth' => $this
->getAuth(),
];
$response = $this->httpClient
->request('GET', $url, $options);
return json_decode($response
->getBody()
->getContents(), TRUE);
}
}