CircleCiManager.php in Build Hooks 8.2
File
modules/build_hooks_circleci/src/CircleCiManager.php
View source
<?php
namespace Drupal\build_hooks_circleci;
use Drupal\build_hooks\BuildHookDetails;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use GuzzleHttp\ClientInterface;
class CircleCiManager implements CircleCiManagerInterface {
const CIRCLE_CI_BASE_PATH = 'https://circleci.com/api/v1.1';
const CIRCLE_CI_HOSTED_PLATFORM = 'github';
const CIRCLE_CI_DATE_FORMAT = 'Y-m-d\\TH:i:s+';
protected $configFactory;
protected $httpClient;
protected $dateFormatter;
public function __construct(ConfigFactoryInterface $config_factory, ClientInterface $http_client, DateFormatterInterface $date_formatter) {
$this->configFactory = $config_factory;
$this->httpClient = $http_client;
$this->dateFormatter = $date_formatter;
}
private function buildCircleCiApiBuildUrlForEnvironment(array $config) {
$circleCiConf = $this->configFactory
->get('build_hooks_circleci.settings');
$apiKey = $circleCiConf
->get('circleci_api_key');
return $this
->buildCircleciApiBasePathForEnvironment($config) . "build?circle-token={$apiKey}";
}
private function buildCircleCiApiBasePathForEnvironment(array $config) {
$basePath = self::CIRCLE_CI_BASE_PATH;
$platform = self::CIRCLE_CI_HOSTED_PLATFORM;
$project = $config['project'];
return "{$basePath}/project/{$platform}/{$project}/";
}
public function getBuildHookDetailsForPluginConfiguration(array $config) {
$buildHookDetails = new BuildHookDetails();
$buildHookDetails
->setUrl($this
->buildCircleCiApiBuildUrlForEnvironment($config));
$buildHookDetails
->setMethod('POST');
$buildHookDetails
->setOptions([
'json' => [
'branch' => $config['branch'],
],
]);
return $buildHookDetails;
}
public function retrieveLatestBuildsFromCircleciForEnvironment(array $settings, $limit = 1) {
$url = $this
->buildCircleCiApiRetrieveBuildsUrl($settings, $limit);
$options = [
'headers' => [
'Accept' => 'application/json',
],
];
$response = $this->httpClient
->request('GET', $url, $options);
$payload = json_decode($response
->getBody()
->getContents(), TRUE);
return $payload;
}
private function buildCircleCiApiRetrieveBuildsUrl(array $config, $limit) {
$circleCiConf = $this->configFactory
->get('build_hooks_circleci.settings');
$apiKey = $circleCiConf
->get('circleci_api_key');
$branch = $config['branch'];
return $this
->buildCircleCiApiBasePathForEnvironment($config) . "tree/{$branch}?circle-token={$apiKey}&limit={$limit}";
}
public function formatCircleCiDateTime($datetime) {
$timezone = new \DateTimeZone('UTC');
$date = \DateTime::createFromFormat(self::CIRCLE_CI_DATE_FORMAT, $datetime, $timezone);
return $this->dateFormatter
->format($date
->getTimestamp(), 'long');
}
}