activity_stream-1.0.x-dev/src/Plugin/rest/resource/StreamResource.php

src/Plugin/rest/resource/StreamResource.php
<?php

declare(strict_types=1);

namespace Drupal\activity_stream\Plugin\rest\resource;

use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Routing\Route;
use Drupal\activity_stream\Helper;
use Drupal\message\MessageInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Pager\PagerManagerInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\Cache\CacheableResponseTrait;

/**
 * Represents Stream records as resources.
 *
 * @RestResource (
 *   id = "activity_stream_stream",
 *   label = @Translation("Activity Stream"),
 *   serialization_class = "Drupal\activity_stream\Entity\ActivityStreamActivity",
 *   uri_paths = {
 *     "canonical" = "/api/activity-stream-stream/{destination}",
 *   }
 * )
 */
final class StreamResource extends ResourceBase {

  //use CacheableResponseTrait;

  /**
   * The RestHelper service.
   */
  private readonly Helper $helperService;  

  /**
   * The Page manager.
   */
  private readonly PagerManagerInterface $pagerManager;    

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    Helper $helper_service,
    PagerManagerInterface $pager_manager
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger, $helper_service, $pager_manager);
    $this->helperService  = $helper_service;
    $this->pagerManager = $pager_manager;
  }

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

  /**
   * Responds to GET requests.
   */
  public function get($destination): ModifiedResourceResponse {

    $data = [];
    $activities = [];

    // Current user
    $current_user = \Drupal::currentUser();

    $activity_date_from = \Drupal::request()->query->get('activity_date_from');
    $activity_date_to = \Drupal::request()->query->get('activity_date_to');
    $activity_entity_type = \Drupal::request()->query->get('activity_entity_type');
    $activity_entity_bundle = \Drupal::request()->query->get('activity_entity_bundle');
    $current_page = \Drupal::request()->query->get('current_page');
    $sort_field = \Drupal::request()->query->get('sort_field');
    $sort_value = \Drupal::request()->query->get('sort_value'); 

    try {
      // Validate parameters
      if (!$this->helperService->validateDestination($destination)) {
        throw new BadRequestHttpException('The destination is not a valid.');
      } 
      if (
          isset($activity_date_from) && 
          !$this->helperService->isValidTimestamp($activity_date_from)
      ) {
        throw new BadRequestHttpException('The activity_date_from is not a valid timestamp.');
      }
      if (
        isset($activity_date_to) && 
        !$this->helperService->isValidTimestamp($activity_date_to)
      ) {
        throw new BadRequestHttpException('The activity_date_to is not a valid timestamp.');
      }
      if (
        isset($activity_entity_type) &&
        !$this->helperService->isValidEntityType($activity_entity_type)
      ) {
        throw new BadRequestHttpException('The activity_entity_type is not a valid entity type.');
      }
      if (
        isset($activity_entity_bundle) &&
        empty($activity_entity_bundle)
      ) {
        throw new BadRequestHttpException('The activity_entity_bundle must not be empty.');
      }
      if (isset($sort_field) && !$this->helperService->isValidSortField($sort_field)) {
        throw new BadRequestHttpException('The sort field is not supported.');
      }
      if (isset($sort_value) && !$this->helperService->isValidSortValue($sort_value)) {
        throw new BadRequestHttpException('The sort value is not supported. Allowed are DESC or ASC.');
      }

      $query = \Drupal::entityQuery('activity_stream_activity')
        ->condition('field_activity_destinations', $destination, 'IN');        
        
      // Get data that belons to current user. 
      $query->condition('uid', $current_user->id(), '=');
        
        
      if (isset($activity_date_from) && isset($activity_date_to)) {
        $query->condition('field_activity_date.value', $activity_date_from, '>=');
        $query->condition('field_activity_date.value', $activity_date_to, '<=');
      }
        
      if (isset($activity_entity_type) && isset($activity_entity_bundle)) {  
        if ($activity_entity_type !== $activity_entity_bundle) {
          $query->condition("field_activity_entity.entity:$activity_entity_type.bundle", $activity_entity_bundle, '=');
        }
        else {
          $query->condition('field_activity_entity.target_type', $activity_entity_type, '=');
        }
      } 

      if (isset($activity_entity_bundle)) {          
        $query->condition("activity_entity_bundle", $activity_entity_bundle, '=');
      }       

      if (isset($sort_field)) {
        if (!isset($sort_value) || empty($sort_value)) {
          $order = 'ASC';
        }
        else {
          $order = $sort_value;
        } 

        $query->sort($sort_field , $order);
      }

      $current_page_now = $current_page * 50;

      $query->accessCheck(TRUE);
      $query->range($current_page_now,50);
      //$query->pager();
      $results = $query->execute();  
      
      if (!empty($results)) {

        $entities = \Drupal::entityTypeManager()->getStorage('activity_stream_activity')->loadMultiple($results);

        $i = 0;
        foreach ($entities as $entity) {
          if ($entity instanceof EntityInterface) {
            $activities[$i] = $this->helperService->loadTree($entity); 
          }
          $i++;
        }       
      }
      else {
        $data['activities'] = [];
      }

      $data['activities'] = $activities;
      $pager = $this->pagerManager->createPager(count($results), 50);

      if ($pager instanceof \Drupal\Core\Pager\Pager) {

        if ($pager->getTotalItems() > 0) {
          $next_page = $current_page +  1;
        }
        else {
          $next_page = NULL;
        }

        if ($current_page > 0) {
          $prev_page = $current_page - 1;
        }
        else {
          $prev_page = NULL;
        }

        $pager_data = [
          'total_items' => $pager->getTotalItems(),
          'total_pages' => $pager->getTotalPages(),
          'current_page' => $current_page,
          'next_page' => $next_page,
          'limit' => $pager->getLimit(),
          'time' => time()
        ]; 
        $data['pager'][] = $pager_data; 
      } 

      $response = new ModifiedResourceResponse($data, 201);

    }
    catch (BadRequestHttpException $exception) {
      $response = new ModifiedResourceResponse([
       'error' => $exception->getMessage() 
      ]);
    }
    catch (UnprocessableEntityHttpException $exception) {
      $response = new ModifiedResourceResponse([
        'error' => $exception->getMessage() 
       ]);
    }    
    catch (\Exception $exception) {
      $response = new ModifiedResourceResponse([
        'error' => $exception->getMessage() 
       ]);
    }

    return $response;  

  }


}

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

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