oncall/update_redmine.php

125 lines
2.8 KiB
PHP

<?php
declare(strict_types = 1);
require_once 'vendor/autoload.php';
/* Update Redmine script */
$u = new update_redmine($_GET['action']);
$u->prepareAction();
$u->sendAction();
/**
* The class that does all the magic.
*/
class update_redmine {
/**
* Are we in debug mode?
* @var bool
*/
private $debugMode = FALSE;
/**
* The URL of the Redmine install.
* @var string
*/
private $baseUrl;
/**
* Full URL to send the request to.
* @var string
*/
private $fullUrl;
/**
* JSON-formatted body of the HTTP request to Redmine.
* @var string
*/
private $json;
/**
* The Redmine API key.
* @var string
*/
private $apiKey;
/**
* The action we want to perform. Must appear on a greenlist (in $this->setAction)
* @var string
*/
private $action;
/**
* The HTTP method we want to use: GET, POST, PUT, DELETE.
* @var string
*/
private $httpMethod;
public function __construct($action = NULL) {
// Load the .env file
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
// Debug Mode will show more information.
$this->debugMode = (bool) getenv('DEBUG_MODE');
$this->baseUrl = getenv('REDMINE_URL');
$this->apiKey = getenv('REDMINE_API_KEY');
$this->setAction($_GET['action']);
}
public function setAction($action) {
$validActions = [
'do_not_alert' => 'PUT',
];
if ($validActions[$action] ?? FALSE) {
$this->action = $action;
$this->httpMethod = $validActions[$action];
}
}
/**
* Takes the arguments received from $_GET and prepares the values to send to Redmine.
*/
public function prepareAction() {
if ($this->action === 'do_not_alert') {
$this->json = '{"issue": {"custom_fields": [{"id": 4, "value": "1"}]}}';
if (is_numeric($_GET['issue'])) {
$issue = $_GET['issue'];
}
$this->fullUrl = $this->baseUrl . "/issues/$issue.json";
}
if ($this->action === 'get_issue') {
$this->prepareRetrieveIssue();
}
}
private function prepareRetrieveIssue() {
$this->fullUrl = $this->baseUrl . "/issues/$issue.json";
}
public function sendAction() {
if ($this->action) {
$this->sendToRedmine($this->httpMethod, $this->json);
}
}
public function sendToRedmine(string $method = 'GET', string $json) {
$context = NULL;
if ($method !== 'GET') {
// use key 'http' even if you send the request to https://...
$options = [
'http' => [
'header' => "Content-type: application/json\r\nX-Redmine-API-Key: $this->apiKey\r\n",
'method' => $method,
'content' => $json,
],
];
$context = stream_context_create($options);
}
$result = file_get_contents($this->fullUrl, FALSE, $context);
if ($result === FALSE) {
print_r($result);
}
}
}