You are here

public function ContentHubInternalRequest::getEntityCdfByInternalRequest in Acquia Content Hub 8

Makes an internal HMAC-authenticated request to the site to obtain CDF.

Parameters

string $entity_type: The Entity type.

string $entity_id: The Entity ID.

bool $include_references: Whether to include referenced entities in the CDF.

Return value

array The CDF array.

File

src/ContentHubInternalRequest.php, line 115

Class

ContentHubInternalRequest
Provides a method to do internal sub-requests to obtain an entity CDF.

Namespace

Drupal\acquia_contenthub

Code

public function getEntityCdfByInternalRequest($entity_type, $entity_id, $include_references = TRUE) {
  global $base_path;

  // Creating a fake user account to give as context to the normalization.
  $this->accountSwitcher
    ->switchTo($this->renderUser);
  try {
    $params = [
      'entity_type' => $entity_type,
      'entity_id' => $entity_id,
      $entity_type => $entity_id,
      '_format' => 'acquia_contenthub_cdf',
    ];
    if ($include_references) {
      $params['include_references'] = 'true';
    }
    $url = Url::fromRoute('acquia_contenthub.entity.' . $entity_type . '.GET.acquia_contenthub_cdf', $params)
      ->toString();
    $url = str_replace($base_path, '/', $url);

    // Creating an internal HMAC-signed request.
    $master_request = $this->requestStack
      ->getCurrentRequest();
    $request = Request::create($url, 'GET', [], $master_request->cookies
      ->all(), [], $master_request->server
      ->all());
    $request = $this->contentHubSubscription
      ->setHmacAuthorization($request, TRUE);

    /** @var \Drupal\Core\Render\HtmlResponse $response */
    $response = $this->kernel
      ->handle($request, HttpKernelInterface::SUB_REQUEST);
    $entity_cdf_json = $response
      ->getContent();
    $bulk_cdf = Json::decode($entity_cdf_json);
  } catch (\Exception $e) {

    // Do nothing, route does not exist, just log a message about it.
    $this->loggerFactory
      ->get('acquia_contenthub')
      ->debug('Exception: %msg', [
      '%msg' => $e
        ->getMessage(),
    ]);
    $bulk_cdf = [];
  }
  $this->accountSwitcher
    ->switchBack();

  // Test to make sure CDF returned an entities array.
  if (isset($bulk_cdf['message'])) {
    $this->loggerFactory
      ->get('acquia_contenthub')
      ->debug('Exception: %msg', [
      '%msg' => $bulk_cdf['message'],
    ]);
    $bulk_cdf = [];
  }

  // Return CDF.
  return empty($bulk_cdf) ? [
    'entities' => [],
  ] : $bulk_cdf;
}