content_packager-8.x-1.x-dev/src/JsonApiHelper.php

src/JsonApiHelper.php
<?php

namespace Drupal\content_packager;

use Drupal\Component\Serialization\Json;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * A helper that assists with processing multi-page JSON:API responses.
 *
 * @package content_packager
 */
class JsonApiHelper {

  /**
   * Helper function that returns data from all of the pages for a JSON:API uri.
   *
   * TODO: Add some caching here, this gets called at least twice on each
   *       uri and all these extra requests and Json::decode() probably add up.
   *
   * @param string $uri
   *   JSON:API endpoint/request.
   *
   * @return array
   *   An array of individual parsed JSON:API results converted into PHP data.
   */
  public static function retrievePagesFromUri($uri) {
    /** @var \Symfony\Component\HttpKernel\HttpKernel $http_kernel */
    $http_kernel = \Drupal::service('http_kernel.basic');
    /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
    $request_stack = \Drupal::service('request_stack');

    $content = [];
    $next_page = $uri;
    while ($next_page) {
      $jsonApiRequest = Request::create($next_page, 'GET');
      $jsonApiRequest->setSession($request_stack->getCurrentRequest()->getSession());
      try {
        $subResponse = $http_kernel->handle($jsonApiRequest, HttpKernelInterface::SUB_REQUEST, FALSE);
        $response = $subResponse->getContent();
        $content[] = $response;
      }
      catch (\Exception $e) {
        // This will prevent ANY content from being packaged, but this seems
        // fine... there doesn't seem to be much value in a partial export.
        return NULL;
      }

      /* TODO: Find a quicker/more efficient approach than this;
      Json::decode() is getting called multiple times throughout
      this module. */
      $decoded = Json::decode($response);
      $next_page = empty($decoded['links']['next']) ? FALSE : $decoded['links']['next']['href'];
    }

    return $content;
  }

}

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

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