You are here

FlaggingCollection.php in Flag Lists 8

Same filename and directory in other branches
  1. 4.0.x src/Entity/FlaggingCollection.php

File

src/Entity/FlaggingCollection.php
View source
<?php

namespace Drupal\flag_lists\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\RevisionableContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\user\UserInterface;
use Drupal\flag\Entity\Flag;

/**
 * Defines the Flagging collection entity.
 *
 * @ingroup flag_lists
 *
 * @ContentEntityType(
 *   id = "flagging_collection",
 *   label = @Translation("Flagging collection"),
 *   label_plural = @Translation("Flagging collections"),
 *   label_count = @PluralTranslation(
 *     singular = "@count flagging collection",
 *     plural = "@count flagging collections"
 *   ),
 *   bundle_label = @Translation("Flagging collection type"),
 *   handlers = {
 *     "storage" = "Drupal\flag_lists\FlaggingCollectionStorage",
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\flag_lists\FlaggingCollectionListBuilder",
 *     "views_data" = "Drupal\flag_lists\Entity\FlaggingCollectionViewsData",
 *     "translation" = "Drupal\flag_lists\FlaggingCollectionTranslationHandler",
 *
 *     "form" = {
 *       "default" = "Drupal\flag_lists\Form\FlaggingCollectionForm",
 *       "add" = "Drupal\flag_lists\Form\FlaggingCollectionForm",
 *       "edit" = "Drupal\flag_lists\Form\FlaggingCollectionForm",
 *       "delete" = "Drupal\flag_lists\Form\FlaggingCollectionDeleteForm",
 *     },
 *     "access" = "Drupal\flag_lists\Access\FlaggingCollectionAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\flag_lists\FlaggingCollectionHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "flagging_collection",
 *   data_table = "flagging_collection_field_data",
 *   revision_table = "flagging_collection_revision",
 *   revision_data_table = "flagging_collection_field_revision",
 *   show_revision_ui = TRUE,
 *   translatable = TRUE,
 *   admin_permission = "add flag lists",
 *   entity_keys = {
 *     "id" = "id",
 *     "revision" = "vid",
 *     "bundle" = "type",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   revision_metadata_keys = {
 *     "revision_user" = "revision_user",
 *     "revision_created" = "revision_created",
 *     "revision_log_message" = "revision_log_message"
 *   },
 *   links = {
 *     "canonical" = "/flagging_collection/{flagging_collection}",
 *     "add-page" = "/flagging_collection/add",
 *     "add-form" = "/flagging_collection/add/{flagging_collection_type}",
 *     "edit-form" = "/flagging_collection/{flagging_collection}/edit",
 *     "delete-form" = "/flagging_collection/{flagging_collection}/delete",
 *     "version-history" = "/flagging_collection/{flagging_collection}/revisions",
 *     "revision" = "/flagging_collection/{flagging_collection}/revisions/{flagging_collection_revision}/view",
 *     "revision_revert" = "/flagging_collection/{flagging_collection}/revisions/{flagging_collection_revision}/revert",
 *     "revision_delete" = "/flagging_collection/{flagging_collection}/revisions/{flagging_collection_revision}/delete",
 *     "translation_revert" = "/flagging_collection/{flagging_collection}/revisions/{flagging_collection_revision}/revert/{langcode}",
 *     "collection" = "/flagging_collection",
 *   },
 *   bundle_entity_type = "flagging_collection_type",
 *   field_ui_base_route = "entity.flagging_collection_type.edit_form"
 * )
 */
class FlaggingCollection extends RevisionableContentEntityBase implements FlaggingCollectionInterface {
  use EntityChangedTrait;

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()
        ->id(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
    foreach (array_keys($this
      ->getTranslationLanguages()) as $langcode) {
      $translation = $this
        ->getTranslation($langcode);

      // If no owner has been set explicitly, make the anonymous user the owner.
      if (!$translation
        ->getOwner()) {
        $translation
          ->setOwnerId(0);
      }
    }

    // If no revision author has been set explicitly,
    // make the flagging_collection owner the
    // revision author.
    if (!$this
      ->getRevisionUser()) {
      $this
        ->setRevisionUserId($this
        ->getOwnerId());
    }

    // Copy all field data from the base_flag, Template Flag
    // and store it in the a new Flag, referenced as related_flag.
    $flagListService = \Drupal::service('flaglists');
    $flagService = \Drupal::service('flag');
    $baseFlag = $flagListService
      ->getFlagForListById($this
      ->getBaseFlag()
      ->id());
    $flag_to_use = $flagService
      ->getFlagById($baseFlag
      ->get('base_flag'));

    // Copy its important content to a array.
    $template['label'] = $this
      ->label();
    if ($this
      ->isNew()) {

      // The id = machine id must be conformant with the rules.
      $template['id'] = strtolower($this
        ->label());
      $template['id'] = preg_replace("/[^a-z0-9_]/", "_", $template['id']);
      $this
        ->setRelatedFlag($template['id']);
    }
    else {

      // The Flagging Collection exist so reuse the old id.
      $template['id'] = $this
        ->getRelatedFlag()
        ->id();
    }
    $template['global'] = $flag_to_use
      ->isGlobal();
    $template['flag_short'] = $flag_to_use
      ->getShortText('flag');
    $template['flag_long'] = $flag_to_use
      ->getLongText('flag');
    $template['flag_message'] = $flag_to_use
      ->getMessage('flag');
    $template['unflag_short'] = $flag_to_use
      ->getShortText('unflag');
    $template['unflag_long'] = $flag_to_use
      ->getLongText('unflag');
    $template['unflag_message'] = $flag_to_use
      ->getMessage('unflag');
    $template['access'] = [];
    $template['access']['bundles'] = '';
    $template['unflag_denied_text'] = '';
    $template['link_type'] = $flag_to_use
      ->getLinkTypePlugin()
      ->getPluginId();
    $template['flag_type'] = $flag_to_use
      ->getFlagTypePlugin()
      ->getPluginId();
    $template['entity_type'] = $flag_to_use
      ->getFlaggableEntityTypeId();
    $template['flagTypeConfig'] = $flag_to_use
      ->getFlagTypePlugin()
      ->getConfiguration();

    // Use the array to create a new, possibly uniq, flag.
    $flag = new flag($template, 'flag');
    $flag
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public static function preDelete(EntityStorageInterface $storage, array $entities) {

    // When a Flagging Collection is deleted also delete the
    // related Flag.
    $flagService = \Drupal::service('flag');
    foreach ($entities as $entity) {
      $flag = $flagService
        ->getFlagById($entity
        ->getRelatedFlag()
        ->id());
      $flag
        ->delete();
    }
    parent::preDelete($storage, $entities);
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this
      ->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this
      ->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this
      ->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this
      ->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this
      ->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this
      ->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function getBaseFlag() {
    return $this
      ->get('templateflag')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function setBaseFlag($baseFlag) {
    return $this
      ->set('templateflag', $baseFlag);
  }

  /**
   * {@inheritdoc}
   */
  public function getRelatedFlag() {
    return $this
      ->get('relatedflag')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function setRelatedFlag($relatedflag) {
    return $this
      ->set('relatedflag', $relatedflag);
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this
      ->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this
      ->set('user_id', $account
      ->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isPublished() {
    return (bool) $this
      ->getEntityKey('status');
  }

  /**
   * {@inheritdoc}
   */
  public function setPublished($published) {
    $this
      ->set('status', $published ? TRUE : FALSE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $accountProxy = \Drupal::currentUser();
    $account = $accountProxy
      ->getAccount();

    // This might have to be fixed but for now this is good enough.
    // Doesn't work to have it visible for admins due to caching issues.
    // Go for hidden as implemented below.
    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Flagging collection entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', [
      'label' => 'hidden',
      'type' => 'author',
      'weight' => 0,
    ])
      ->setDisplayOptions('form', [
      'type' => 'hidden',
      'weight' => 5,
    ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the Flagging collection entity.'))
      ->setRevisionable(TRUE)
      ->setSettings([
      'max_length' => 50,
      'text_processing' => 0,
    ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
      'label' => 'hidden',
      'type' => 'string',
      'weight' => -4,
    ])
      ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => -4,
    ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', FALSE);
    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
      ->setDescription(t('A boolean indicating whether the Flagging collection is published.'))
      ->setRevisionable(TRUE)
      ->setDefaultValue(TRUE);
    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));
    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));
    $fields['revision_translation_affected'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Revision translation affected'))
      ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
      ->setReadOnly(TRUE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
    $fields['templateflag'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Base flag'))
      ->setDescription(t('The flag list used as base'))
      ->setTranslatable(TRUE)
      ->setSetting('target_type', 'flag')
      ->setSetting('handler', 'default')
      ->setRevisionable(TRUE)
      ->setDisplayOptions('view', [
      'label' => 'inline',
      'type' => 'string',
      'weight' => 1,
    ])
      ->setDisplayConfigurable('view', TRUE);
    $fields['relatedflag'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Related flag'))
      ->setDescription(t('The related flag used for for this list'))
      ->setTranslatable(TRUE)
      ->setSetting('target_type', 'flag')
      ->setSetting('handler', 'default')
      ->setRevisionable(TRUE)
      ->setDisplayOptions('view', [
      'label' => 'inline',
      'type' => 'string',
      'weight' => 0,
    ])
      ->setDisplayConfigurable('view', TRUE);
    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  protected function urlRouteParameters($rel) {
    $uri_route_parameters = parent::urlRouteParameters($rel);
    if ($rel === 'revision_revert' && $this instanceof RevisionableContentEntityBase) {
      $uri_route_parameters[$this
        ->getEntityTypeId() . '_revision'] = $this
        ->getRevisionId();
    }
    elseif ($rel === 'revision_delete' && $this instanceof RevisionableContentEntityBase) {
      $uri_route_parameters[$this
        ->getEntityTypeId() . '_revision'] = $this
        ->getRevisionId();
    }
    return $uri_route_parameters;
  }

}

Classes

Namesort descending Description
FlaggingCollection Defines the Flagging collection entity.