You are here

class EndpointAccessibilityRequirement in Acquia Content Hub 8

Defines an endpoint accessibility requirement.

Plugin annotation


@ContentHubRequirement(
  id = "endpoint_accessibility",
  title = @Translation("Endpoint accessibility"),
)

Hierarchy

Expanded class hierarchy of EndpointAccessibilityRequirement

File

acquia_contenthub_diagnostic/src/Plugin/ContentHubRequirement/EndpointAccessibilityRequirement.php, line 17

Namespace

Drupal\acquia_contenthub_diagnostic\Plugin\ContentHubRequirement
View source
class EndpointAccessibilityRequirement extends ContentHubRequirementBase {

  /**
   * The request options required to ensure an appropriate request.
   */
  const REQUEST_OPTIONS = [
    'verify' => FALSE,
    'cookies' => FALSE,
    'allow_redirects' => FALSE,
    'http_errors' => FALSE,
  ];

  /**
   * The description to be shown to the user.
   *
   * @var string
   */
  protected $description = '';

  /**
   * The domain which will be calculated and used for requests.
   *
   * @var string
   */
  protected $domain = '';

  /**
   * The Content Hub Client Manager.
   *
   * @var \Drupal\acquia_contenthub\Client\ClientManagerInterface
   */
  protected $clientManager;

  /**
   * Verify the accessibility of the content hub endpoints.
   */
  public function verify() {

    // If Content Hub is not installed there is no reason to run this test.
    if (!$this->moduleHandler
      ->moduleExists('acquia_contenthub')) {
      return REQUIREMENT_OK;
    }
    $this->clientManager = \Drupal::service('acquia_contenthub.client_manager');
    if (!$this->clientManager
      ->isConnected()) {
      $this
        ->setValue($this
        ->t('Endpoint validation failed'));
      $this
        ->setDescription($this
        ->t('Client Manager not connected. Configure Content Hub and try again.'));
      return REQUIREMENT_ERROR;
    }
    $this->domain = $this
      ->getDomain();
    try {
      $this
        ->testWebhookEndpoint();
      $this
        ->testContentViewEndpoint();
      if ($this->description) {
        $this
          ->setValue($this
          ->t('Endpoint validation failed'));
        $this
          ->setDescription($this->description);
        return REQUIREMENT_ERROR;
      }
    } catch (\Exception $e) {
      $this
        ->setValue($this
        ->t('Cannot validate endpoints'));
      $this
        ->setDescription($this
        ->t('Verify your server and site configuration and try again. Error: @error', [
        '@error' => $e
          ->getMessage(),
      ]));
      return REQUIREMENT_ERROR;
    }
    return REQUIREMENT_OK;
  }

  /**
   * Test the webhook endpoint.
   */
  protected function testWebhookEndpoint() {
    $endpoint_name = 'Webhook Endpoint';
    $endpoint_url = '/acquia-contenthub/webhook';
    $client = \Drupal::httpClient();
    $response = $client
      ->get($this->domain . $endpoint_url, static::REQUEST_OPTIONS);
    $status_code = $response
      ->getStatusCode();
    $this->description .= $this
      ->parseStatusCode($status_code, $endpoint_name, $endpoint_url);
  }

  /**
   * Test the content view endpoint.
   */
  protected function testContentViewEndpoint() {
    $endpoint_name = 'Content View Endpoint';
    $test_nid = $this
      ->getTestNid();
    if ($test_nid) {
      $endpoint_url = $this->domain . '/acquia-contenthub/display/node/' . $test_nid . '/default';
      $authorization = $this
        ->getAuthorizationHeader($endpoint_url);

      // HTTP Client only accepts Guzzle Requests.
      $request = new GuzzleRequest('GET', $endpoint_url, [
        'authorization' => $authorization,
      ]);
      $client = \Drupal::httpClient();
      $response = $client
        ->send($request, static::REQUEST_OPTIONS);
      $status_code = $response
        ->getStatusCode();
      $this->description .= $this
        ->parseStatusCode($status_code, $endpoint_name, $endpoint_url);
    }
    else {
      $endpoint_url = '/acquia-contenthub/display/node/{entity_id}/default';
      $this->description .= $this
        ->t("@endpoint_name (@endpoint_url) requires a node to exist on the site in order to test. Create a node and try again.", [
        '@endpoint_name' => $endpoint_name,
        '@endpoint_url' => $endpoint_url,
      ]);
    }
  }

  /**
   * Get the Nid of a published node on the site.
   *
   * @return int|bool
   *   Nid of a published node. FALSE if none exist.
   */
  protected function getTestNid() {
    $nodes = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->range(0, 1)
      ->execute();
    if (count($nodes)) {
      return array_pop($nodes);
    }
    return FALSE;
  }

  /**
   * Parse the status code and return the error, if applicable.
   *
   * @param int $status_code
   *   Status code of response.
   * @param string $endpoint_name
   *   Human readable name of endpoint.
   * @param string $endpoint_url
   *   Url of endpoint.
   *
   * @return string
   *   Error to be added to the description.
   */
  protected function parseStatusCode($status_code, $endpoint_name, $endpoint_url) {

    // 200 response is the only successful response.
    if ($status_code == 200) {
      return '';
    }
    elseif (substr($status_code, 0, 1) == 3) {
      return $this
        ->t("@endpoint_name (@endpoint_url) received a @status_code response indicating a redirect. The Content Hub service will not follow redirects.\n", [
        '@endpoint_name' => $endpoint_name,
        '@endpoint_url' => $endpoint_url,
        '@status_code' => $status_code,
      ]);
    }
    elseif ($status_code == 401) {
      return $this
        ->t("@endpoint_name (@endpoint_url) received a 401 response indicating that credentials are required. Disable the Shield module or any other authentication method being used on the endpoint.\n", [
        '@endpoint_name' => $endpoint_name,
        '@endpoint_url' => $endpoint_url,
      ]);
    }
    elseif ($status_code == 404) {
      return $this
        ->t("@endpoint_name (@endpoint_url) received a 404 response indicating that the endpoint cannot be reached.\n", [
        '@endpoint_name' => $endpoint_name,
        '@endpoint_url' => $endpoint_url,
      ]);

      // Give a generic error for all other responses.
    }
    else {
      return $this
        ->t("@endpoint_name (@endpoint_url) received a @status_code response. Please ensure a 200 response is sent.\n", [
        '@endpoint_name' => $endpoint_name,
        '@endpoint_url' => $endpoint_url,
        '@status_code' => $status_code,
      ]);
    }
  }

  /**
   * Gets the authorization header for a given endpoint and method.
   *
   * @param string $endpoint
   *   Url of endpoint.
   * @param string $method
   *   Method of the request. (e.g GET or POST).
   *
   * @return string
   *   The authorization header.
   */
  protected function getAuthorizationHeader($endpoint, $method = 'GET') {
    $request = Request::create($endpoint, $method);
    $subscription = \Drupal::service('acquia_contenthub.acquia_contenthub_subscription');
    $shared_secret = $subscription
      ->getSharedSecret();
    $signature = $this->clientManager
      ->getRequestSignature($request, $shared_secret);
    return 'Acquia ContentHub:' . $signature;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentHubRequirementBase::$moduleHandler protected property The module handler.
ContentHubRequirementBase::$severity protected property The requirement's result/severity level.
ContentHubRequirementBase::$value protected property The current value.
ContentHubRequirementBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ContentHubRequirementBase::description public function Returns the description of the requirement/status. Overrides ContentHubRequirementInterface::description 1
ContentHubRequirementBase::getDomain protected function Get the domain to run the tests on.
ContentHubRequirementBase::setDescription protected function Sets the description of the requirement/status.
ContentHubRequirementBase::setValue protected function Sets the current value.
ContentHubRequirementBase::severity public function Returns the requirement's result/severity level. Overrides ContentHubRequirementInterface::severity
ContentHubRequirementBase::title public function Returns the name of the requirement. Overrides ContentHubRequirementInterface::title
ContentHubRequirementBase::value public function Returns the current value. Overrides ContentHubRequirementInterface::value
ContentHubRequirementBase::__construct public function Constructs a new ContentHubRequirementBase. Overrides PluginBase::__construct
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EndpointAccessibilityRequirement::$clientManager protected property The Content Hub Client Manager.
EndpointAccessibilityRequirement::$description protected property The description to be shown to the user. Overrides ContentHubRequirementBase::$description
EndpointAccessibilityRequirement::$domain protected property The domain which will be calculated and used for requests.
EndpointAccessibilityRequirement::getAuthorizationHeader protected function Gets the authorization header for a given endpoint and method.
EndpointAccessibilityRequirement::getTestNid protected function Get the Nid of a published node on the site.
EndpointAccessibilityRequirement::parseStatusCode protected function Parse the status code and return the error, if applicable.
EndpointAccessibilityRequirement::REQUEST_OPTIONS constant The request options required to ensure an appropriate request.
EndpointAccessibilityRequirement::testContentViewEndpoint protected function Test the content view endpoint.
EndpointAccessibilityRequirement::testWebhookEndpoint protected function Test the webhook endpoint.
EndpointAccessibilityRequirement::verify public function Verify the accessibility of the content hub endpoints. Overrides ContentHubRequirementBase::verify
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.