Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ivangrozni/fe3c520149e999fb358548707bbde9f5 to your computer and use it in GitHub Desktop.
Save ivangrozni/fe3c520149e999fb358548707bbde9f5 to your computer and use it in GitHub Desktop.
dev-2034-ohdear_integration-maintenance-window.patch
diff --git a/README.md b/README.md
index 72a201b1d63c2c4ccfa7dfbc1a2780d2389a4c97..c5f1f4194c9378c0bff0a60a79e6b2d80673d378 100644
--- a/README.md
+++ b/README.md
@@ -1,14 +1,14 @@
-# Oh Dear Integration
+# OhDear Integration
-Integrates your drupal website with the [Oh Dear](https://ohdear.app) monitoring app.
+Integrates your drupal website with the [OhDear](https://ohdear.app) monitoring app.
-Provides `json/oh-dear-health-check-results` endpoint for oh dear healthchecks.
+Provides `json/oh-dear-health-check-results` endpoint for OhDear healthchecks.
These are converted sensor results from [Monitoring module](https://drupal.org/project/monitoring).
Endpoint requires configuraton of OhDear Healthcheck Secret that enables
access of OhDear service to the endpoint.
-With configuring the Oh dear cron uri, website will start to send data on cron
-runs to Oh Dear service. Ping uri is first obtained on OhDear under Scheduled
+With configuring the OhDear cron uri, website will start to send data on cron
+runs to OhDear service. Ping uri is first obtained on OhDear under Scheduled
tasks tab.
## Configuration
@@ -26,7 +26,7 @@ hook (called RequirementsRecap). We recommend using it.
### Cron
-Obtain the ping uri under Scheduled tasks tab on Oh Dear app
+Obtain the ping uri under Scheduled tasks tab on OhDear app
(`https://ohdear.app/sites/<site-id>/check/scheduled-tasks`) and set it in
settings form. OhDear integration module will start to notify OhDear service
about cron runs. Currently only default drupal cron is supported.
diff --git a/composer.json b/composer.json
index cc37c302c88f3837bb4126c898acc0f42b70f939..cd88d7a9c6728a5a32acb4409f4f8b5cd4a5d5ae 100644
--- a/composer.json
+++ b/composer.json
@@ -1,6 +1,6 @@
{
"name": "drupal/ohdear_integration",
- "description": "Provides endpoint for Oh Dear monitoring app to check drupal's health.",
+ "description": "Provides endpoint for OhDear monitoring app to check drupal's health.",
"type": "drupal-module",
"minimum-stability": "dev",
"prefer-stable": true,
@@ -8,6 +8,7 @@
"require": {
"drupal/core": "^8.8 || ^9.0 || ^10.0",
"ohdearapp/health-check-results": "^1.0",
+ "ohdearapp/ohdear-php-sdk": "^3.4",
"drupal/monitoring": "^1.11"
},
"support": {
@@ -22,6 +23,13 @@
"healthcheck"
],
"license": "GPL-2.0-or-later",
+ "extra": {
+ "drush": {
+ "services": {
+ "drush.services.yml": "^9 || ^10"
+ }
+ }
+ },
"authors": [
{
"name": "Lio Novelli",
diff --git a/config/schema/ohdear_integration.schema.yml b/config/schema/ohdear_integration.schema.yml
index aeeba5ed09b9107e28d123bccc764f2ae60aef42..6f76b610bc0e599f4d127419e3b2c0f58515ecd7 100644
--- a/config/schema/ohdear_integration.schema.yml
+++ b/config/schema/ohdear_integration.schema.yml
@@ -5,7 +5,13 @@ ohdear_integration.settings:
mapping:
ohdear_healthcheck_secret:
type: string
- label: 'Oh Dear Healthcheck Secret'
+ label: 'OhDear Healthcheck Secret'
ohdear_cron_uri:
type: string
- label: 'Oh Dear Scheduled tasks monitoring'
+ label: 'OhDear Scheduled tasks monitoring'
+ ohdear_api_key:
+ type: string
+ label: 'OhDear Api Key'
+ ohdear_site_id:
+ type: integer
+ label: 'OhDear Site ID'
diff --git a/drush.services.yml b/drush.services.yml
new file mode 100644
index 0000000000000000000000000000000000000000..c1100f6c1280f0c424844ee2b3cd77cd0e7b34aa
--- /dev/null
+++ b/drush.services.yml
@@ -0,0 +1,9 @@
+services:
+ ohdear_integration.commands:
+ class: \Drupal\ohdear_integration\Commands\OhDearIntegrationCommands
+ arguments:
+ - '@ohdear_sdk'
+ - '@ohdear_integration.settings'
+ - '@state'
+ tags:
+ - { name: drush.command }
diff --git a/ohdear_integration.info.yml b/ohdear_integration.info.yml
index e200c23faa0b3897c0caeb786c98aa677ba95eb5..4fa313b64c953562bac2baaced8d495d700b68af 100644
--- a/ohdear_integration.info.yml
+++ b/ohdear_integration.info.yml
@@ -1,6 +1,6 @@
-name: Oh Dear Integration
+name: OhDear Integration
type: module
-description: Provides endpoint for Oh Dear monitoring app to check drupal&#039;s health.
+description: Provides endpoint for OhDear monitoring app to check drupal&#039;s health.
package: Monitor
core_version_requirement: ^8 || ^9 || ^10
dependencies:
diff --git a/ohdear_integration.links.menu.yml b/ohdear_integration.links.menu.yml
index dd752645325c547e1a06373f1cf684632139c532..edf0cfd8e4d4e1097397ae0c75c1ba1ff9ef262e 100644
--- a/ohdear_integration.links.menu.yml
+++ b/ohdear_integration.links.menu.yml
@@ -1,6 +1,6 @@
ohdear_integration.settings:
- title: Oh Dear Settings
- description: Configure Oh Dear Integration
+ title: OhDear Settings
+ description: Configure OhDear Integration
parent: system.admin_config_system
route_name: ohdear_integration.settings
weight: 10
diff --git a/ohdear_integration.module b/ohdear_integration.module
index f7c9cefef1210dd0dfcb03c9288ba84ebfbdcad9..7a1355aa46e88f5f5a30f5e35f2aec029ed0a8b7 100644
--- a/ohdear_integration.module
+++ b/ohdear_integration.module
@@ -2,7 +2,7 @@
/**
* @file
- * Primary module hooks for Oh Dear Integration module.
+ * Primary module hooks for OhDear Integration module.
*/
/**
diff --git a/ohdear_integration.routing.yml b/ohdear_integration.routing.yml
index d3fa6075ade7b89d1bde7accdc6d5619da3c805e..52800933736a3b44bd6b234f193b914f96b5fc43 100644
--- a/ohdear_integration.routing.yml
+++ b/ohdear_integration.routing.yml
@@ -2,16 +2,16 @@ ohdear_integration.healthcheck:
path: '/json/oh-dear-health-check-results'
defaults:
_title: 'Healthcheck'
- _controller: '\Drupal\ohdear_integration\Controller\OhdearIntegrationController::buildJson'
+ _controller: '\Drupal\ohdear_integration\Controller\OhDearIntegrationController::buildJson'
requirements:
- _custom_access: '\Drupal\ohdear_integration\Controller\OhdearIntegrationController::access'
+ _custom_access: '\Drupal\ohdear_integration\Controller\OhDearIntegrationController::access'
options:
no_cache: 'TRUE'
ohdear_integration.settings:
path: '/admin/config/system/ohdear-settings'
defaults:
- _title: 'Oh Dear Settings'
+ _title: 'OhDear Settings'
_form: 'Drupal\ohdear_integration\Form\SettingsForm'
requirements:
_permission: 'administer site configuration'
diff --git a/ohdear_integration.services.yml b/ohdear_integration.services.yml
index f9cbc64c2a75e67bc1a6d91042b02f48ef34b41c..ae40c777b51348dd4543b205e6b7d8fad2782b46 100644
--- a/ohdear_integration.services.yml
+++ b/ohdear_integration.services.yml
@@ -3,8 +3,16 @@ services:
class: Drupal\Core\Logger\LoggerChannel
factory: logger.factory:get
arguments: [ 'ohdear_integration' ]
+ ohdear_integration.settings:
+ class: Drupal\Core\Config\ImmutableConfig
+ factory: config.factory:get
+ arguments:
+ - ohdear_integration.settings
ohdear_healthcheck.generator:
- class: Drupal\ohdear_integration\OhdearHealthcheckGenerator
+ class: Drupal\ohdear_integration\OhDearHealthcheckGenerator
arguments:
- '@logger.channel.ohdear_integration'
- '@monitoring.sensor_runner'
+ ohdear_sdk:
+ class: Drupal\ohdear_integration\OhDearSdkService
+ arguments: ['@ohdear_integration.settings', '@logger.channel.ohdear_integration']
diff --git a/src/Commands/OhDearIntegrationCommands.php b/src/Commands/OhDearIntegrationCommands.php
new file mode 100644
index 0000000000000000000000000000000000000000..616731d53ca65a171a79148a73e467668e623492
--- /dev/null
+++ b/src/Commands/OhDearIntegrationCommands.php
@@ -0,0 +1,220 @@
+<?php
+
+namespace Drupal\ohdear_integration\Commands;
+
+use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
+use Drupal\Core\Config\ImmutableConfig;
+use Drupal\Core\State\StateInterface;
+use Drupal\ohdear_integration\OhDearSdkService;
+use Drupal\shs\StringTranslationTrait;
+use Drush\Commands\DrushCommands;
+
+/**
+ * A Drush command file.
+ */
+class OhDearIntegrationCommands extends DrushCommands {
+
+ use StringTranslationTrait;
+
+ /**
+ * OhDear sdk object.
+ *
+ * @var \OhDear\PhpSdk\OhDear
+ */
+ protected $ohDear;
+
+ /**
+ * Configuration of OhDear integration settings.
+ *
+ * @var \Drupal\Core\Config\ImmutableConfig
+ */
+ protected $ohDearIntegrationSettings;
+
+ /**
+ * The ohdear site id.
+ *
+ * @var int
+ */
+ protected $siteId;
+
+ /**
+ * The state service.
+ *
+ * @var \Drupal\Core\State\StateInterface
+ */
+ protected $state;
+
+ /**
+ * Constructs a OhDear Integration commands object.
+ *
+ * @param \Drupal\ohdear_integration\OhDearSdkService $ohdear_sdk_service
+ * The ohdear integration sdk service.
+ * @param \Drupal\Core\Config\ImmutableConfig $ohdear_integration_settings
+ * OhDear Integration settings.
+ * @param \Drupal\Core\State\StateInterface $state
+ * The state service.
+ */
+ public function __construct(OhDearSdkService $ohdear_sdk_service, ImmutableConfig $ohdear_integration_settings, StateInterface $state) {
+ parent::__construct();
+ $this->ohDear = $ohdear_sdk_service->getOhDear();
+ $this->siteId = $ohdear_sdk_service->getSiteId();
+ $this->ohDearIntegrationSettings = $ohdear_integration_settings;
+ $this->state = $state;
+ }
+
+ /**
+ * Prints the current maintenance status or starts/stops maintenance.
+ *
+ * @param array $options
+ * An associative array of options.
+ *
+ * @option start
+ * Starts the maintenance window in OhDear app.
+ * @option stop
+ * Stops the maintenance window in OhDear app.
+ * @option with-drupal
+ * Puts drupal in or out of maintenance mode.
+ * @option time-length
+ * Time length for the maintenance period in seconds (default: 1 hour).
+ * @option number
+ * Number of maintenance windows to show (default: 5).
+ * @usage ohdear-maintenance
+ * drush ohdear:maintenance --start --time-length=7200
+ *
+ * @command ohdear:maintenance
+ * @aliases ohdear-maintenance
+ * @field-labels
+ * id: Id
+ * site_id: Site Id
+ * starts_at: Starts at
+ * ends_at: Ends at
+ * @default-fields id,site_id,starts_at,ends_at
+ *
+ * @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
+ * A list of OhDear maintenance windows or activity description.
+ */
+ public function maintenance(array $options = [
+ 'start' => NULL,
+ 'stop' => NULL,
+ 'with-drupal' => NULL,
+ 'time-length' => 3600,
+ 'number' => 5,
+ ]) {
+ $site = $this->ohDear->site($this->siteId);
+ // @see https://ohdear.app/docs/integrations/the-oh-dear-php-sdk#maintenance-windows
+ if (!$options['start'] && !$options['stop']) {
+ // Just print out current maintenance window status.
+ $maintenanceWindows = $this->getMaintenancePeriods($this->siteId, $options['number']);
+ return new RowsOfFields($maintenanceWindows);
+ }
+ elseif ($options['start'] && $options['stop']) {
+ $this->logger->warning('Only one of --start or --stop flags can be used.');
+ $maintenanceWindows = $this->getMaintenancePeriods($this->siteId, $options['number']);
+ return new RowsOfFields($maintenanceWindows);
+ }
+ elseif ($options['start']) {
+ $time_length = $options['time-length'] ?? 3600;
+ $maintenance_window = $this->ohDear->startSiteMaintenance($this->siteId, $time_length);
+ if ($options['with-drupal']) {
+ $this->state->set('system.maintenance_mode', 1);
+ }
+ $this->output()->writeln($this->t('Maintenance period @id started for @site. It ends at @date.', [
+ '@id' => $maintenance_window->id,
+ '@site' => $site->url,
+ '@date' => $maintenance_window->endsAt ?? '',
+ ]));
+ return NULL;
+ }
+ elseif ($options['stop']) {
+ $this->ohDear->stopSiteMaintenance($this->siteId);
+ if ($options['with-drupal']) {
+ $this->state->set('system.maintenance_mode', 0);
+ }
+ $this->output()->writeln($this->t('Maintenance period stopped for @site.', [
+ '@site' => $site->url,
+ ]));
+ return NULL;
+ }
+
+ $this->logger->error('Something went wrong. No condition was met.');
+ return NULL;
+ }
+
+ /**
+ * Gets maintenance period for specific site.
+ *
+ * @param int|null $siteId
+ * Site id.
+ * @param int $num
+ * Number of maintenance windows.
+ *
+ * @return array
+ * Array of last maintenance periods.
+ *
+ * @throws \Exception
+ */
+ protected function getMaintenancePeriods(?int $siteId = NULL, int $num = 5) {
+ if (!$siteId) {
+ $siteId = $this->siteId;
+ }
+ $maintenanceWindows = array_slice(array_reverse($this->ohDear->maintenancePeriods($siteId)), 0, $num, TRUE);
+ if (empty($maintenanceWindows)) {
+ $this->logger->warning('No maintence window found.');
+ }
+ $rows = [];
+ foreach ($maintenanceWindows as $window) {
+ // @todo Add a check if a maintenance is currently active.
+ $rows[] = [
+ 'id' => $window->id,
+ 'site_id' => $window->siteId,
+ 'starts_at' => $window->startsAt,
+ 'ends_at' => $window->endsAt ?? '',
+ ];
+ }
+ return $rows;
+ }
+
+ /**
+ * Prints current site id and url.
+ *
+ * @usage ohdear:info
+ *
+ * @command ohdear:info
+ * @aliases ohdear-info
+ * @field-labels
+ * id: Id
+ * type: Type
+ * label: Label
+ * enabled: Enabled
+ * latest_run_ended_at: Latest run ended at
+ * latest_run_result: Latest run result
+ * summary: Summary
+ * @default-fields label,latest_run_ended_at,latest_run_result,summary,enabled
+ *
+ * @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
+ * A list of OhDear checks.
+ */
+ public function siteInfo(array $options = [
+ 'checks' => NULL,
+ ]) {
+ $site = $this->ohDear->site($this->siteId);
+ $this->output()->writeln($this->t('Site ID: @id, Url: @url', [
+ '@id' => (string) $site->id,
+ '@url' => $site->url,
+ ]));
+ $this->output()->writeln($this->t('Summarized check results: @results (@date).', [
+ '@results' => $site->attributes['summarized_check_result'] ?? 'unknown',
+ '@date' => $site->attributes['latest_run_date'] ?? '',
+ ]));
+ if (isset($options['checks'])) {
+ $checks = [];
+ foreach ($site->attributes['checks'] as $check) {
+ $check['enabled'] = $check['enabled'] ? 'On' : 'Off';
+ $checks[] = $check;
+ }
+ return new RowsOfFields($checks);
+ }
+ return NULL;
+ }
+
+}
diff --git a/src/Controller/OhdearIntegrationController.php b/src/Controller/OhDearIntegrationController.php
similarity index 70%
rename from src/Controller/OhdearIntegrationController.php
rename to src/Controller/OhDearIntegrationController.php
index 70fbe1fafa96ae156bd53c120d2dd6d650edc091..ed4aa832771f360c812845b6d3a01eb42dd6e4f8 100644
--- a/src/Controller/OhdearIntegrationController.php
+++ b/src/Controller/OhDearIntegrationController.php
@@ -7,29 +7,29 @@ use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Http\RequestStack;
use Drupal\Core\Session\AccountInterface;
-use Drupal\ohdear_integration\OhdearHealthcheckGenerator;
+use Drupal\ohdear_integration\OhDearHealthcheckGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Logger\LoggerChannelInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
- * Returns responses for Oh Dear Integration routes.
+ * Returns responses for OhDear Integration routes.
*/
-class OhdearIntegrationController extends ControllerBase {
+class OhDearIntegrationController extends ControllerBase {
/**
- * Oh dear integration configuration.
+ * OhDear integration configuration.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
- protected $ohdearSettings;
+ protected $ohDearSettings;
/**
* Healthcheck generator service.
*
- * @var \Drupal\ohdear_integration\OhdearHealthcheckGenerator
+ * @var \Drupal\ohdear_integration\OhDearHealthcheckGenerator
*/
- protected $ohdearGenerator;
+ protected $ohDearGenerator;
/**
* The logger service.
@@ -39,20 +39,27 @@ class OhdearIntegrationController extends ControllerBase {
protected $logger;
/**
- * Constructs oh dear integration controller.
+ * The current request.
+ *
+ * @var \Symfony\Component\HttpFoundation\Request|null
+ */
+ protected $currentRequest;
+
+ /**
+ * Constructs OhDear integration controller.
*
* @param \Drupal\Core\Config\ImmutableConfig $ohdear_settings
* The immutable config.
- * @param \Drupal\ohdear_integration\OhdearHealthcheckGenerator $ohdear_generator
+ * @param \Drupal\ohdear_integration\OhDearHealthcheckGenerator $ohdear_generator
* The ohdear helper objects factory service.
* @param \Drupal\Core\Logger\LoggerChannelInterface $logger
* The simple sitemap extensions logger service.
* @param \Drupal\Core\Http\RequestStack $request_stack
* The request stack service.
*/
- public function __construct(ImmutableConfig $ohdear_settings, OhdearHealthcheckGenerator $ohdear_generator, LoggerChannelInterface $logger, RequestStack $request_stack) {
- $this->ohdearSettings = $ohdear_settings;
- $this->ohdearGenerator = $ohdear_generator;
+ public function __construct(ImmutableConfig $ohdear_settings, OhDearHealthcheckGenerator $ohdear_generator, LoggerChannelInterface $logger, RequestStack $request_stack) {
+ $this->ohDearSettings = $ohdear_settings;
+ $this->ohDearGenerator = $ohdear_generator;
$this->logger = $logger;
$this->currentRequest = $request_stack->getCurrentRequest();
}
@@ -60,9 +67,9 @@ class OhdearIntegrationController extends ControllerBase {
/**
* {@inheritdoc}
*/
- public static function create(ContainerInterface $container): OhdearIntegrationController {
+ public static function create(ContainerInterface $container): OhDearIntegrationController {
return new static(
- $container->get('config.factory')->get('ohdear_integration.settings'),
+ $container->get('ohdear_integration.settings'),
$container->get('ohdear_healthcheck.generator'),
$container->get('logger.channel.ohdear_integration'),
$container->get('request_stack')
@@ -76,7 +83,7 @@ class OhdearIntegrationController extends ControllerBase {
* Response.
*/
public function buildJson() {
- return new JsonResponse($this->ohdearGenerator->getData(), 200, [], TRUE);
+ return new JsonResponse($this->ohDearGenerator->getData(), 200, [], TRUE);
}
/**
@@ -88,7 +95,7 @@ class OhdearIntegrationController extends ControllerBase {
public function access(AccountInterface $account) {
$has_permission = $account->hasPermission('monitoring reports');
$ohdear_header = $this->currentRequest->headers->get('oh-dear-health-check-secret') ?? NULL;
- if ($ohdear_header === $this->ohdearSettings->get('ohdear_healthcheck_secret') || $has_permission) {
+ if ($ohdear_header === $this->ohDearSettings->get('ohdear_healthcheck_secret') || $has_permission) {
return AccessResult::allowed();
}
return AccessResult::forbidden();
diff --git a/src/Form/SettingsForm.php b/src/Form/SettingsForm.php
index 1ab80f11f8ba6952d0baaf7d2ce0f1da69b62e2c..a1d8bdebebcdc9e06f5916aaa81e71c52cfc7d90 100644
--- a/src/Form/SettingsForm.php
+++ b/src/Form/SettingsForm.php
@@ -6,7 +6,7 @@ use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
- * Configure Ohdear integration settings for this site.
+ * Configure OhDear integration settings for this site.
*/
class SettingsForm extends ConfigFormBase {
@@ -31,8 +31,8 @@ class SettingsForm extends ConfigFormBase {
$ohdear_settings = $this->config('ohdear_integration.settings');
$form['ohdear_healthcheck_secret'] = [
'#type' => 'textfield',
- '#title' => $this->t('Secret provided by Oh Dear App'),
- '#description' => $this->t('Enables access of Oh Dear App to the healthcheck endpoint. Healthcheck secret is obtained from the OhDear service.'),
+ '#title' => $this->t('Secret provided by OhDear App'),
+ '#description' => $this->t('Enables access of OhDear App to the <a href="/json/oh-dear-health-check-results" target="_blank">healthcheck endpoint</a>. Healthcheck secret is obtained from the OhDear service.'),
'#default_value' => $ohdear_settings->get('ohdear_healthcheck_secret'),
'#attributes' => [
'placeholder' => '4zcke2vxfETABM8h',
@@ -47,6 +47,26 @@ class SettingsForm extends ConfigFormBase {
'placeholder' => 'https://ping.ohdear.app/db4a0676-f25e-3328-b325-0d8a5c58fac1',
],
];
+ $form['ohdear_api_key'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Api key for the OhDear App'),
+ '#description' => $this->t('Enables access of OhDear App api. Api key is obtained from the OhDear service. For more info read the <a href="https://ohdear.app/docs/integrations/the-oh-dear-api#get-your-api-token" target="_blank">OhDear api docs</a>. If api key is not provided, some features of this module will not work.'),
+ '#default_value' => $ohdear_settings->get('ohdear_api_key'),
+ '#attributes' => [
+ 'placeholder' => '',
+ ],
+ ];
+ $form['ohdear_site_id'] = [
+ '#type' => 'number',
+ '#title' => $this->t('OhDear Site id'),
+ '#description' => $this->t('Site ID is obtained from the OhDear service. For more info read the <a href="https://ohdear.app/docs/integrations/the-oh-dear-api#sites" target="_blank">OhDear api docs</a>. If site id is wrong, maintenance window drush command will not work!'),
+ '#default_value' => $ohdear_settings->get('ohdear_site_id'),
+ '#attributes' => [
+ 'placeholder' => '30556',
+ ],
+ ];
+ // @todo Add validation check for users to check if api key provides
+ // authentication and site id links to correct site.
return parent::buildForm($form, $form_state);
}
@@ -57,6 +77,8 @@ class SettingsForm extends ConfigFormBase {
$this->config('ohdear_integration.settings')
->set('ohdear_healthcheck_secret', $form_state->getValue('ohdear_healthcheck_secret'))
->set('ohdear_cron_uri', $form_state->getValue('ohdear_cron_uri'))
+ ->set('ohdear_api_key', $form_state->getValue('ohdear_api_key'))
+ ->set('ohdear_site_id', $form_state->getValue('ohdear_site_id'))
->save();
parent::submitForm($form, $form_state);
}
diff --git a/src/OhdearHealthcheckGenerator.php b/src/OhDearHealthcheckGenerator.php
similarity index 90%
rename from src/OhdearHealthcheckGenerator.php
rename to src/OhDearHealthcheckGenerator.php
index 69d5ffca8366ae1adc427e5af93639256c65c306..22b648d5db4ffe510dd5f24473affb46f19712fe 100644
--- a/src/OhdearHealthcheckGenerator.php
+++ b/src/OhDearHealthcheckGenerator.php
@@ -11,9 +11,9 @@ use OhDear\HealthCheckResults\CheckResult;
use OhDear\HealthCheckResults\CheckResults;
/**
- * Converts monitoring sensor result objects oh dear healtchecks.
+ * Converts monitoring sensor result objects OhDear healtchecks.
*/
-class OhdearHealthcheckGenerator {
+class OhDearHealthcheckGenerator {
const STATUS_MAPPING = [
SensorResultDataInterface::STATUS_OK => CheckResult::STATUS_OK,
@@ -30,6 +30,20 @@ class OhdearHealthcheckGenerator {
*/
protected $logger;
+ /**
+ * The sensor runner service.
+ *
+ * @var \Drupal\monitoring\SensorRunner
+ */
+ protected $sensorRunner;
+
+ /**
+ * Check results.
+ *
+ * @var \OhDear\HealthCheckResults\CheckResults
+ */
+ protected $checkResults;
+
/**
* Constructs an OhdearHealthcheckGenerator object.
*
@@ -108,7 +122,7 @@ class OhdearHealthcheckGenerator {
}
/**
- * Runs all enabled sensors and converts them to oh dear healthchecks.
+ * Runs all enabled sensors and converts them to OhDear healthchecks.
*
* @return string
* Json data of all monitoring sensor results converted to healthchecks.
diff --git a/src/OhDearSdkService.php b/src/OhDearSdkService.php
new file mode 100644
index 0000000000000000000000000000000000000000..8b45e19d5a4fc26a6588ad04a9c6fb017a6baf30
--- /dev/null
+++ b/src/OhDearSdkService.php
@@ -0,0 +1,123 @@
+<?php
+
+namespace Drupal\ohdear_integration;
+
+use Drupal\Core\Config\ImmutableConfig;
+use Drupal\Core\Logger\LoggerChannelInterface;
+use OhDear\PhpSdk\OhDear;
+
+/**
+ * Service for easier handling of OhDear php sdk.
+ */
+class OhDearSdkService {
+
+ /**
+ * The ohDear integration config.
+ *
+ * @var \Drupal\Core\Config\ImmutableConfig
+ */
+ protected $ohDearIntegrationSettings;
+
+ /**
+ * The logger.channel.ohdear_integration service.
+ *
+ * @var \Drupal\Core\Logger\LoggerChannelInterface
+ */
+ protected $logger;
+
+
+ /**
+ * The OhDear Sdk object.
+ *
+ * @var \OhDear\PhpSdk\OhDear
+ */
+ protected $ohdear;
+
+ /**
+ * The ohdear site id.
+ *
+ * @var int
+ */
+ protected $siteId;
+
+ /**
+ * The ohdear site.
+ *
+ * @var \OhDear\PhpSdk\Resources\Site
+ */
+ protected $ohDearSite;
+
+ /**
+ * Constructs an OhDearSdkService object.
+ *
+ * @param \Drupal\Core\Config\ImmutableConfig $ohdear_integration_settings
+ * The config factory.
+ * @param \Drupal\Core\Logger\LoggerChannelInterface $ohdear_integration_logger
+ * The logger.channel.ohdear_integration service.
+ */
+ public function __construct(ImmutableConfig $ohdear_integration_settings, LoggerChannelInterface $ohdear_integration_logger) {
+ $this->ohDearIntegrationSettings = $ohdear_integration_settings;
+ $this->logger = $ohdear_integration_logger;
+ }
+
+ /**
+ * Creates OhDear sdk object.
+ *
+ * @return \OhDear\PhpSdk\OhDear
+ * The OhDear php sdk object.
+ */
+ public function getOhDear() {
+ $apiKey = $this->ohDearIntegrationSettings->get('ohdear_api_key');
+ if (!$apiKey) {
+ $this->logger->error('OhDear api key is missing!');
+ throw new \Exception('OhDear api key is missing.');
+ }
+ if (!isset($this->ohdear)) {
+ $this->ohdear = new OhDear($apiKey);
+ }
+ return $this->ohdear;
+ }
+
+ /**
+ * Reads site id from the configuration.
+ *
+ * @return int
+ * The site id.
+ *
+ * @throws \Exception
+ */
+ public function getSiteId() {
+ if (isset($this->siteId)) {
+ return $this->siteId;
+ }
+ $siteId = (int) $this->ohDearIntegrationSettings->get('ohdear_site_id');
+ if (!$siteId) {
+ $this->logger->error('OhDear site id is missing! Fix it at <a href="/admin/config/system/ohdear-settings">OhDear Integration configuration form</a>.');
+ throw new \Exception('OhDear site id is missing.');
+ }
+ $this->siteId = (int) $siteId;
+ return $this->siteId;
+ }
+
+ /**
+ * Returns the OhDear php sdk site object.
+ *
+ * @return \OhDear\PhpSdk\Resources\Site
+ * The OhDear site for current site id.
+ *
+ * @throws \Exception
+ */
+ public function getSite() {
+ if (isset($this->ohDearSite)) {
+ return $this->ohDearSite;
+ }
+ $site = $this->ohdear->site($this->getSiteId());
+ if (!$site) {
+ $this->logger->error('OhDear site not found! Fix it at <a href="/admin/config/system/ohdear-settings">OhDear Integration configuration form</a>.');
+ throw new \Exception('OhDear site not found.');
+ }
+ $this->ohDearSite = $site;
+ return $this->ohDearSite;
+ }
+
+}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment