You are here

class ContentHubFilterResource in Acquia Content Hub 8

Provides a resource to perform CRUD operations on Content Hub Filters.

Plugin annotation


@RestResource(
  id = "contenthub_filter",
  label = @Translation("Content Hub Filter"),
  serialization_class = "Drupal\acquia_contenthub_subscriber\Entity\ContentHubFilter",
  uri_paths = {
    "canonical" = "/acquia_contenthub/contenthub_filter/{contenthub_filter}",
    "create" = "/acquia_contenthub/contenthub_filter",
  }
)

Hierarchy

Expanded class hierarchy of ContentHubFilterResource

File

acquia_contenthub_subscriber/src/Plugin/rest/resource/ContentHubFilterResource.php, line 35

Namespace

Drupal\acquia_contenthub_subscriber\Plugin\rest\resource
View source
class ContentHubFilterResource extends ResourceBase {

  /**
   * Permission to allow access to this resource.
   *
   * @var string
   */
  protected $permission = 'administer acquia content hub';

  /**
   * A curent user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

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

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @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 manager.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user account.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, EntityTypeManagerInterface $entity_type_manager, AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->entityTypeManager = $entity_type_manager;
    $this->currentUser = $current_user;
  }

  /**
   * {@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'));
  }

  /**
   * Validates input from user.
   *
   * @param \Drupal\acquia_contenthub_subscriber\ContentHubFilterInterface|null $contenthub_filter
   *   The Content Hub Filter entity.
   * @param bool $is_new
   *   Validate taken into consideration it is a new entity or an existent one.
   */
  public function validate(ContentHubFilterInterface $contenthub_filter, $is_new = TRUE) {
    $messages = [];
    if (!empty($contenthub_filter
      ->uuid())) {
      if (!Uuid::isValid($contenthub_filter
        ->uuid())) {
        $messages[] = t('The filter has an invalid "uuid" field.');
      }
    }
    if (empty($contenthub_filter
      ->id())) {
      $messages[] = t('The filter has an invalid "id" field.');
    }
    else {
      if (preg_match("/^[a-zA-Z0-9_]*\$/", $contenthub_filter
        ->id(), $matches) !== 1) {
        $messages[] = t('The "id" field has to be a "machine_name" (Only small letters, numbers and underscore allowed).');
      }

      // @todo Check that the ID is unique making a query to the database.
    }
    if (!isset($contenthub_filter->name)) {
      $messages[] = t('The filter has to have a "name" field.');
    }
    if (!isset($contenthub_filter->author) || $contenthub_filter->author == 0) {
      $messages[] = t('You are trying to create a new filter without a valid session.');
    }

    // Validating Date fields.
    if (!empty($contenthub_filter->from_date)) {
      if (\DateTime::createFromFormat('m-d-Y', $contenthub_filter->from_date) === FALSE) {
        $messages[] = t('Invalid "from_date" field. Valid format is "m-d-Y".');
      }
    }
    if (!empty($contenthub_filter->to_date)) {
      if (\DateTime::createFromFormat('m-d-Y', $contenthub_filter->to_date) === FALSE) {
        $messages[] = t('Invalid "to_date" field. Valid format is "m-d-Y".');
      }
    }

    // @todo Validate other fields.
    if (count($messages) > 0) {
      $message = implode("\n", $messages);
      throw new HttpException(422, $message);
    }
  }

  /**
   * Responds to GET requests.
   *
   * Returns a list of filters.
   *
   * @return \Drupal\rest\ResourceResponse
   *   The response containing a list of filters.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
  public function get($contenthub_filter = NULL) {
    if (!$this->currentUser
      ->hasPermission($this->permission)) {
      throw new AccessDeniedHttpException();
    }
    $entities = NULL;
    if (!empty($contenthub_filter) && $contenthub_filter !== 'all') {
      $entities = [];
      $entities[] = $contenthub_filter;
    }
    $filters = $this->entityTypeManager
      ->getStorage('contenthub_filter')
      ->loadMultiple($entities);
    if (!empty($filters)) {
      foreach ($filters as $key => $filter) {

        // Present the date fields in format "m-d-Y".
        $filters[$key]
          ->changeDateFormatYearMonthDay2MonthDayYear();
      }
      $response = new ResourceResponse(array_values($filters));
      $response
        ->addCacheableDependency($filters);
      return $response;
    }
    elseif ($contenthub_filter == 'all') {
      $response = new ResourceResponse([]);
      $response
        ->addCacheableDependency($filters);
      return $response;
    }
    throw new NotFoundHttpException(t('No Content Hub Filters were found'));
  }

  /**
   * Responds to POST requests.
   *
   * @param \Drupal\acquia_contenthub_subscriber\ContentHubFilterInterface|null $contenthub_filter
   *   The Content Hub Filter.
   *
   * @return \Drupal\rest\ResourceResponse
   *   The Content Hub Filter after it has been saved.
   */
  public function post(ContentHubFilterInterface $contenthub_filter = NULL) {
    if (!$this->currentUser
      ->hasPermission($this->permission)) {
      throw new AccessDeniedHttpException();
    }
    if (empty($contenthub_filter)) {
      throw new BadRequestHttpException('No Content Hub Filter content received.');
    }

    // This Filter is owned by the user who created it.
    if (empty($contenthub_filter->author)) {
      $uid = $this->currentUser
        ->id();

      // Anonymous should not be able to have 'Administer Acquia Content Hub'
      // permission but if it ever does, this filter will be owned by admin.
      $contenthub_filter->author = $uid ?: 1;
    }

    // Verify that we have valid Content Hub Filter Entity.
    $this
      ->validate($contenthub_filter, TRUE);

    // Now that it has been validated, we need to convert the Date to the
    // appropriate storage format in "Y-m-d".
    $contenthub_filter
      ->changeDateFormatMonthDayYear2YearMonthDay();

    // We are ONLY creating new entities through POST requests.
    if (!$contenthub_filter
      ->isNew()) {
      $message = t('Only new entities can be created. Filter "!name" already exists (id = "!id", uuid = "!uuid").', [
        '!id' => $contenthub_filter
          ->id(),
        '!name' => $contenthub_filter->name,
        '!uuid' => $contenthub_filter
          ->uuid(),
      ]);
      throw new BadRequestHttpException($message);
    }

    // Validation has passed, now try to save the entity.
    try {
      $contenthub_filter
        ->save();
      $this->logger
        ->notice('Created entity %type with ID %id.', [
        '%type' => $contenthub_filter
          ->getEntityTypeId(),
        '%id' => $contenthub_filter
          ->id(),
      ]);

      // Convert back the Dates to format "m-d-Y".
      $contenthub_filter
        ->changeDateFormatYearMonthDay2MonthDayYear();
      return new ResourceResponse($contenthub_filter);
    } catch (EntityStorageException $e) {
      $message = new FormattableMarkup('Internal Server Error [!message].', [
        '!message' => $e
          ->getMessage(),
      ]);
      throw new HttpException(500, $message, $e);
    }
  }

  /**
   * Responds to PATCH requests.
   *
   * @param \Drupal\acquia_contenthub_subscriber\ContentHubFilterInterface $contenthub_filter
   *   The Content Hub Filter entity submitted by REST.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The HTTP request object.
   *
   * @return \Drupal\rest\ResourceResponse
   *   The Content Hub Filter after it has been saved.
   */
  public function patch(ContentHubFilterInterface $contenthub_filter, Request $request) {
    if (!$this->currentUser
      ->hasPermission($this->permission)) {
      throw new AccessDeniedHttpException();
    }
    if (empty($contenthub_filter)) {
      throw new BadRequestHttpException('No Content Hub Filter content received.');
    }

    // Obtain the original Content Hub Filter.
    $contenthub_filter_original = $this->entityTypeManager
      ->getStorage('contenthub_filter')
      ->load($contenthub_filter
      ->getOriginalId());
    if (empty($contenthub_filter_original)) {
      throw new BadRequestHttpException('No Content Hub Filter "id" received. You have to provide an existing entity "id" in the body message.');
    }

    // This Filter is owned by the user who initially created it.
    if (empty($contenthub_filter->author)) {

      // Anonymous should not be able to have 'Administer Acquia Content Hub'
      // permission but if it ever does, this filter will be owned by admin.
      $contenthub_filter->author = $contenthub_filter_original->author ?: 1;
    }

    // Verify that we have valid values submitted in Content Hub Filter.
    $this
      ->validate($contenthub_filter, FALSE);

    // Now that it has been validated, we need to convert the Date to the
    // appropriate storage format in "Y-m-d".
    $contenthub_filter
      ->changeDateFormatMonthDayYear2YearMonthDay();

    // Update original entity with submitted values.

    /** @var \Drupal\acquia_contenthub_subscriber\ContentHubFilterInterface $contenthub_filter_updated */
    $contenthub_filter_updated = $contenthub_filter
      ->updateValues($contenthub_filter_original);

    // Validation has passed, now try to save the original updated entity.
    try {
      $contenthub_filter_updated
        ->save();
      $this->logger
        ->notice('Updated entity %type with ID %id.', [
        '%type' => $contenthub_filter_updated
          ->getEntityTypeId(),
        '%id' => $contenthub_filter_updated
          ->id(),
      ]);

      // Convert back the Dates to format "m-d-Y".
      $contenthub_filter_updated
        ->changeDateFormatYearMonthDay2MonthDayYear();
      return new ResourceResponse($contenthub_filter_updated);
    } catch (EntityStorageException $e) {
      $message = new FormattableMarkup('Internal Server Error [!message].', [
        '!message' => $e
          ->getMessage(),
      ]);
      throw new HttpException(500, $message, $e);
    }
  }

  /**
   * Responds to DELETE requests.
   *
   * @param \Drupal\acquia_contenthub_subscriber\ContentHubFilterInterface $contenthub_filter
   *   The Content Hub Filter.
   *
   * @return \Drupal\rest\ModifiedResourceResponse
   *   The success status of the request.
   */
  public function delete(ContentHubFilterInterface $contenthub_filter) {
    $contenthub_filter_id = $contenthub_filter
      ->id();
    if (!$this->currentUser
      ->hasPermission($this->permission)) {
      throw new AccessDeniedHttpException();
    }
    if (empty($contenthub_filter_id)) {
      throw new BadRequestHttpException('No Content Hub Filter information was sent to be deleted.');
    }

    // Obtain the original Content Hub Filter.
    $contenthub_filter = $this->entityTypeManager
      ->getStorage('contenthub_filter')
      ->load($contenthub_filter_id);
    if (empty($contenthub_filter)) {
      throw new BadRequestHttpException("No Content Hub Filter exists for id = \"{$contenthub_filter_id}\".");
    }
    try {
      $contenthub_filter
        ->delete();

      // DELETE responses have an empty body.
      return new ModifiedResourceResponse(NULL, 204);
    } catch (EntityStorageException $e) {
      $message = new FormattableMarkup('Internal Server Error [!message].', [
        '!message' => $e
          ->getMessage(),
      ]);
      throw new HttpException(500, $message, $e);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentHubFilterResource::$currentUser protected property A curent user instance.
ContentHubFilterResource::$entityTypeManager protected property A instance of entity type manager.
ContentHubFilterResource::$permission protected property Permission to allow access to this resource.
ContentHubFilterResource::create public static function Creates an instance of the plugin. Overrides ResourceBase::create
ContentHubFilterResource::delete public function Responds to DELETE requests.
ContentHubFilterResource::get public function Responds to GET requests.
ContentHubFilterResource::patch public function Responds to PATCH requests.
ContentHubFilterResource::post public function Responds to POST requests.
ContentHubFilterResource::validate public function Validates input from user.
ContentHubFilterResource::__construct public function Constructs a Drupal\rest\Plugin\ResourceBase object. Overrides ResourceBase::__construct
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
ResourceBase::$logger protected property A logger instance.
ResourceBase::$serializerFormats protected property The available serialization formats.
ResourceBase::availableMethods public function Returns the available HTTP request methods on this plugin. Overrides ResourceInterface::availableMethods 1
ResourceBase::getBaseRoute protected function Gets the base route for a particular method. 2
ResourceBase::getBaseRouteRequirements protected function Gets the base route requirements for a particular method. 1
ResourceBase::permissions public function Implements ResourceInterface::permissions(). Overrides ResourceInterface::permissions 2
ResourceBase::requestMethods protected function Provides predefined HTTP request methods.
ResourceBase::routes public function Returns a collection of routes with URL path information for the resource. Overrides ResourceInterface::routes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.