Untitled

mail@pastecode.io avatar
unknown
plain_text
22 days ago
4.7 kB
5
Indexable
Never
<?php

namespace Drupal\bw_user_course_project\Plugin\rest\resource;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Http\ClientFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\search_api\Query\QueryInterface;
use GuzzleHttp\Promise\Utils;
use GuzzleHttp\Psr7\Uri;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Return the current user's course projects.
 *
 * @RestResource(
 *   id = "bw_current_user_course_projects",
 *   label = @Translation("BW: User: Current user course projects"),
 *   uri_paths = {
 *     "canonical" = "/user/course-projects",
 *   },
 * )
 */
final class CurrentUserCourseProjectsResource extends ResourceBase {

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

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  private AccountInterface $currentUser;

  /**
   * The HTTP client.
   *
   * @var \Drupal\Core\Http\ClientFactory
   */
  protected $httpClient;

  /**
   * Class constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Http\ClientFactory $http_client
   *   The HTTP client.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    EntityTypeManagerInterface $entity_type_manager,
    AccountInterface $current_user,
    ClientFactory $http_client,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->entityTypeManager = $entity_type_manager;
    $this->currentUser = $current_user;
    $this->httpClient = $http_client;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('entity_type.manager'),
      $container->get('current_user'),
      $container->get('http_client_factory'),
    );
  }

  /**
   * Get the current user's course projects.
   *
   * @return \Drupal\rest\ModifiedResourceResponse
   *   The HTTP response object.
   */
  public function get(): ModifiedResourceResponse {
    ($query = $this->entityTypeManager
      ->getStorage('search_api_index')
      ->load('default')
      ->query()
    )
      ->addCondition('search_api_datasource', 'entity:course_project')
      ->addCondition('ucpj_user_id', $this->currentUser->id())
      ->addCondition('ucpj_status', 'banned', '<>')
      ->sort('ucpj_id', QueryInterface::SORT_DESC);
    $course_projects_ids = array_values(
      array_map(
        fn ($result) => $result->getField('ucpj_id')->getValues()[0],
        $query->execute()->getResultItems()
      )
    );

    $promises = [];
    $base_url = '';

    if (!empty($_ENV['PANTHEON_ENVIRONMENT'])) {
      switch ($_ENV['PANTHEON_ENVIRONMENT']) {
        case 'live':
          $base_url = 'https://live-app-brayn.pantheonsite.io';
          break;

        case 'test':
          $base_url = 'https://test-app-brayn.pantheonsite.io';
          break;

        default:
          $base_url = 'https://dev-app-brayn.pantheonsite.io';
      }
    } else {
      $base_url = 'https://brayn.localhost';
    }

    foreach ($course_projects_ids as $id) {
      $promise = $this->httpClient
        ->fromOptions([])
        ->getAsync("{$base_url}/api/course-project/{$id}");
      $promises[] = $promise;
    }

    $results = Utils::unwrap($promises);
    $data = [];
    foreach ($results as $response) {
      $data[] = $response->getBody()->getContents();
    }

    dd($data);

    return new ModifiedResourceResponse($course_projects_ids, 200);
  }

}