pantheon_decoupled-1.0.0-alpha3/src/Controller/PantheonDecoupledTestController.php

src/Controller/PantheonDecoupledTestController.php
<?php declare(strict_types = 1);

namespace Drupal\pantheon_decoupled\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for Preview Site test controller used by FES Settings.
 */
final class PantheonDecoupledTestController extends ControllerBase {
  /**
   * An http client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs an PantheonDecoupledTestController object.
   *
   * @param \GuzzleHttp\ClientInterface $http_client
   *   The http_client.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(ClientInterface $http_client, EntityTypeManagerInterface $entity_type_manager) {
      $this->httpClient = $http_client;
      $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('http_client'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * Builds the response.
   */
  public function __invoke($preview_site): array {
    // Get data for preview site
    $storage = $this->entityTypeManager()->getStorage('dp_preview_site');
    $site = $storage->load($preview_site);
    $content_types = $site->get('content_type');
    foreach (array_reverse($content_types) as $key => $value) {
      if ($value === 0) {
        unset($content_types[$key]);
      }
    }
    $content_type = !empty($content_types) ? array_shift($content_types) : $key;

    // Get example content to preview
    $query = $this->entityTypeManager->getStorage('node')->getQuery();
    $results = $query->condition('type', $content_type)
      ->range(0, 1)
      ->accessCheck(TRUE)
      ->execute();
    $node_storage = $this->entityTypeManager()->getStorage('node');
    $node = !empty($results) ? $node_storage->load(array_shift($results)) : NULL;

    $docs_item = [
      '#type' => 'item',
      // Note - not using t() here since the docs aren't localized.
      '#markup' => "Consult the Pantheon Documentation for more information on <a href='https://docs.pantheon.io/guides/decoupled/drupal-nextjs-frontend-starters/content-preview' target='_blank' rel='noopener noreferrer'>configuring content preview</a>.",
    ];

    $build['content'][] = [
      '#type' => 'item',
      '#markup' => '<h3>'. t('Preview Site') . ': ' . $site->label() . '</h3>',
    ];

    if (!empty($node)) {
      // Build test API Call
      $params = [
        'secret' => $site->get('secret'),
        'slug' => $node->toUrl()->toString(),
        'objectName' => 'node--' . $content_type,
        'test' => true,
        'locale' => $node->get('langcode')->value,
        'key' => $node->get('uuid')->value,
      ];
      $test_url = $site->get('url') . '?' . http_build_query($params);
    }
    else {
      $build['content'][] = [
        '#type' => 'item',
        '#markup' => t('No example content found matching configured content types.'),
      ];
      $build['content'][] = $docs_item;
      return $build;
    }

    // Build render array based on result of test API call.
    try {
      $response = $this->httpClient->get($test_url);
      $body = json_decode($response->getBody()->getContents(), TRUE);
      $status = $response->getStatusCode();
      if (isset($body['message']) && $status === 200) {
        $build['content'][] = [
          '#type' => 'item',
          '#markup' => t('Drupal was able to communicate with your preview site and preview example content.'),
        ];
        if (isset($status)) {
          $build['content'][] = [
            '#type' => 'item',
            '#markup' => t('Code') . ': ' . $status,
          ];
        }
        if (isset($body['message'])) {
          $build['content'][] = [
            '#type' => 'item',
            '#markup' => t('Message') . ': ' . $body['message'],
          ];
        }
      }
      else {
        // Should catch a 200 from a URL isn't actually a preview endpoint.
        $build['content'][] = [
          '#type' => 'item',
          '#markup' => t('There was an error connecting to the preview site. Please confirm that the URL is a valid preview API endpoint.'),
        ];
        $build['content'][] = $docs_item;
      }
    }
    catch (RequestException $e) {
      $response = $e->getResponse();
      // No response body - includes a completely invalid host or URL
      if (empty($response)) {
        $build['content'][] = [
          '#type' => 'item',
          '#markup' => t('There was an error connecting to the preview site. Please confirm that the URL is a valid preview API endpoint.'),
        ];
        $build['content'][] = [
          '#type' => 'item',
          '#markup' => t('Error') . ': ' . $e->getMessage(),
        ];
        $build['content'][] = $docs_item;
      }
      // The preview endpoint responded, but responded with an exception
      else {
        $body = json_decode($response->getBody()->getContents(), TRUE);

        $build['content'][] = [
          '#type' => 'item',
          '#markup' => t('There was an error connecting to the preview site.'),
        ];
        if (isset( $body['error'])) {
          $build['content'][] = [
            '#type' => 'item',
            '#markup' => t('Error') . ': ' . $body['error'],
          ];
        }
        if (isset( $body['message'])) {
          $build['content'][] = [
            '#type' => 'item',
            '#markup' => t('Message') . ': ' . $body['message'],
          ];
        }
        $build['content'][] = $docs_item;
      }
    }

    return $build;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc