You are here

class ParagraphsType in Paragraphs 8

Same name in this branch
  1. 8 src/Entity/ParagraphsType.php \Drupal\paragraphs\Entity\ParagraphsType
  2. 8 src/Plugin/migrate/source/d7/ParagraphsType.php \Drupal\paragraphs\Plugin\migrate\source\d7\ParagraphsType

Defines the ParagraphsType entity.

Plugin annotation


@ConfigEntityType(
  id = "paragraphs_type",
  label = @Translation("Paragraphs type"),
  label_collection = @Translation("Paragraphs types"),
  label_singular = @Translation("Paragraphs type"),
  label_plural = @Translation("Paragraphs types"),
  label_count = @PluralTranslation(
    singular = "@count Paragraphs type",
    plural = "@count Paragraphs types",
  ),
  handlers = {
    "access" = "Drupal\paragraphs\ParagraphsTypeAccessControlHandler",
    "list_builder" = "Drupal\paragraphs\Controller\ParagraphsTypeListBuilder",
    "form" = {
      "add" = "Drupal\paragraphs\Form\ParagraphsTypeForm",
      "edit" = "Drupal\paragraphs\Form\ParagraphsTypeForm",
      "delete" = "Drupal\paragraphs\Form\ParagraphsTypeDeleteConfirm"
    }
  },
  config_prefix = "paragraphs_type",
  admin_permission = "administer paragraphs types",
  entity_keys = {
    "id" = "id",
    "label" = "label",
  },
  config_export = {
    "id",
    "label",
    "icon_uuid",
    "icon_default",
    "description",
    "behavior_plugins",
  },
  bundle_of = "paragraph",
  links = {
    "edit-form" = "/admin/structure/paragraphs_type/{paragraphs_type}",
    "delete-form" = "/admin/structure/paragraphs_type/{paragraphs_type}/delete",
    "collection" = "/admin/structure/paragraphs_type",
  }
)

Hierarchy

Expanded class hierarchy of ParagraphsType

21 files declare their use of ParagraphsType
paragraphs.module in ./paragraphs.module
Contains paragraphs.module
ParagraphsAddModesTest.php in tests/src/Functional/WidgetLegacy/ParagraphsAddModesTest.php
ParagraphsAddModesTest.php in tests/src/Functional/WidgetStable/ParagraphsAddModesTest.php
ParagraphsBehaviorBase.php in src/ParagraphsBehaviorBase.php
ParagraphsBehaviorInterface.php in src/ParagraphsBehaviorInterface.php

... See full list

File

src/Entity/ParagraphsType.php, line 57

Namespace

Drupal\paragraphs\Entity
View source
class ParagraphsType extends ConfigEntityBundleBase implements ParagraphsTypeInterface, EntityWithPluginCollectionInterface {

  /**
   * The ParagraphsType ID.
   *
   * @var string
   */
  public $id;

  /**
   * The ParagraphsType label.
   *
   * @var string
   */
  public $label;

  /**
   * A brief description of this paragraph type.
   *
   * @var string
   */
  public $description;

  /**
   * UUID of the Paragraphs type icon file.
   *
   * @var string
   */
  protected $icon_uuid;

  /**
   * Default icon encoded as data URL scheme (RFC 2397).
   *
   * @var string
   */
  protected $icon_default;

  /**
   * The Paragraphs type behavior plugins configuration keyed by their id.
   *
   * @var array
   */
  public $behavior_plugins = [];

  /**
   * Holds the collection of behavior plugins that are attached to this
   * Paragraphs type.
   *
   * @var \Drupal\paragraphs\ParagraphsBehaviorCollection
   */
  protected $behaviorCollection;

  /**
   * Restores the icon file from the default icon value.
   *
   * @return \Drupal\file\FileInterface|bool
   *   The icon's file entity or FALSE if no default icon set.
   */
  protected function restoreDefaultIcon() {

    // Default icon data in RFC 2397 format ("data" URL scheme).
    if ($this->icon_default && ($icon_data = fopen($this->icon_default, 'r'))) {

      // Compose the default icon file destination.
      $icon_meta = stream_get_meta_data($icon_data);

      // File extension from MIME, only JPG/JPEG, PNG and SVG expected.
      list(, $icon_file_ext) = explode('image/', $icon_meta['mediatype']);

      // SVG special case.
      if ($icon_file_ext == 'svg+xml') {
        $icon_file_ext = 'svg';
      }
      $filesystem = \Drupal::service('file_system');
      $icon_upload_path = ParagraphsTypeInterface::ICON_UPLOAD_LOCATION;
      $icon_file_destination = $icon_upload_path . $this
        ->id() . '-default-icon.' . $icon_file_ext;

      // Check the directory exists before writing data to it.
      $filesystem
        ->prepareDirectory($icon_upload_path, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);

      // Save the default icon file.
      $icon_file_uri = $filesystem
        ->saveData($icon_data, $icon_file_destination);
      if ($icon_file_uri) {

        // Create the icon file entity.
        $icon_entity_values = [
          'uri' => $icon_file_uri,
          'uid' => \Drupal::currentUser()
            ->id(),
          'uuid' => $this->icon_uuid,
          'status' => FILE_STATUS_PERMANENT,
        ];

        // Delete existent icon file if it exists.
        if ($old_icon = $this
          ->getFileByUuid($this->icon_uuid)) {
          $old_icon
            ->delete();
        }
        $new_icon = File::create($icon_entity_values);
        $new_icon
          ->save();
        $this
          ->updateFileIconUsage($new_icon, $old_icon);
        return $new_icon;
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getIconFile() {
    $icon = $this
      ->getFileByUuid($this->icon_uuid) ?: $this
      ->restoreDefaultIcon();
    if ($this->icon_uuid && $icon) {
      return $icon;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getBehaviorPlugins() {
    if (!isset($this->behaviorCollection)) {
      $this->behaviorCollection = new ParagraphsBehaviorCollection(\Drupal::service('plugin.manager.paragraphs.behavior'), $this->behavior_plugins);
    }
    return $this->behaviorCollection;
  }

  /**
   * {@inheritdoc}
   */
  public function getIconUrl() {
    if ($image = $this
      ->getIconFile()) {
      return file_create_url($image
        ->getFileUri());
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getBehaviorPlugin($instance_id) {
    return $this
      ->getBehaviorPlugins()
      ->get($instance_id);
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();

    // Add the file icon entity as dependency if a UUID was specified.
    if ($this->icon_uuid && ($file_icon = $this
      ->getIconFile())) {
      $this
        ->addDependency($file_icon
        ->getConfigDependencyKey(), $file_icon
        ->getConfigDependencyName());
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) {
    $changed = parent::onDependencyRemoval($dependencies);
    $behavior_plugins = $this
      ->getBehaviorPlugins();
    foreach ($dependencies['module'] as $module) {

      /** @var \Drupal\Component\Plugin\PluginInspectionInterface $plugin */
      foreach ($behavior_plugins as $instance_id => $plugin) {
        $definition = (array) $plugin
          ->getPluginDefinition();

        // If a module providing a behavior plugin is being uninstalled,
        // remove the plugin and dependency so this paragraph bundle is not
        // deleted too.
        if (isset($definition['provider']) && $definition['provider'] === $module) {
          unset($this->behavior_plugins[$instance_id]);
          $this
            ->getBehaviorPlugins()
            ->removeInstanceId($instance_id);
          $changed = TRUE;
        }
      }
    }
    return $changed;
  }

  /**
   * {@inheritdoc}
   */
  public function getEnabledBehaviorPlugins() {
    return $this
      ->getBehaviorPlugins()
      ->getEnabled();
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginCollections() {
    return [
      'behavior_plugins' => $this
        ->getBehaviorPlugins(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this->description;
  }

  /**
   * {@inheritdoc}
   */
  public function hasEnabledBehaviorPlugin($plugin_id) {
    $plugins = $this
      ->getBehaviorPlugins();
    if ($plugins
      ->has($plugin_id)) {

      /** @var \Drupal\paragraphs\ParagraphsBehaviorInterface $plugin */
      $plugin = $plugins
        ->get($plugin_id);
      $config = $plugin
        ->getConfiguration();
      return array_key_exists('enabled', $config) && $config['enabled'] === TRUE;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    if (!$update || $this->icon_uuid != $this->original->icon_uuid) {

      // Update the file usage for the icon file.
      $new_icon_file = $this->icon_uuid ? $this
        ->getFileByUuid($this->icon_uuid) : FALSE;

      // Update the file usage of the old icon as well if the icon was changed.
      $old_icon_file = $update && $this->original->icon_uuid ? $this
        ->getFileByUuid($this->original->icon_uuid) : FALSE;
      $this
        ->updateFileIconUsage($new_icon_file, $old_icon_file);
    }
    parent::postSave($storage, $update);
  }

  /**
   * Gets the file entity defined by the UUID.
   *
   * @param string $uuid
   *   The file entity's UUID.
   *
   * @return \Drupal\file\FileInterface|null
   *   The file entity. NULL if the UUID is invalid.
   */
  protected function getFileByUuid($uuid) {
    if ($id = \Drupal::service('paragraphs_type.uuid_lookup')
      ->get($uuid)) {
      return $this
        ->entityTypeManager()
        ->getStorage('file')
        ->load($id);
    }
    return NULL;
  }

  /**
   * Updates the icon file usage information.
   *
   * @param \Drupal\file\FileInterface|mixed $new_icon
   *   The new icon file, FALSE on deletion.
   * @param \Drupal\file\FileInterface|mixed $old_icon
   *   (optional) Old icon, on update or deletion.
   */
  protected function updateFileIconUsage($new_icon, $old_icon = FALSE) {

    /** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
    $file_usage = \Drupal::service('file.usage');
    if ($new_icon) {

      // Add usage of the new icon file.
      $file_usage
        ->add($new_icon, 'paragraphs', 'paragraphs_type', $this
        ->id());
    }
    if ($old_icon) {

      // Delete usage of the old icon file.
      $file_usage
        ->delete($old_icon, 'paragraphs', 'paragraphs_type', $this
        ->id());
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
ConfigEntityBase::$isUninstalling private property Whether the config is being deleted by the uninstall process.
ConfigEntityBase::$langcode protected property The language code of the entity's default language.
ConfigEntityBase::$originalId protected property The original ID of the configuration entity.
ConfigEntityBase::$status protected property The enabled/disabled status of the configuration entity. 4
ConfigEntityBase::$third_party_settings protected property Third party entity settings.
ConfigEntityBase::$trustedData protected property Trust supplied data and not use configuration schema on save.
ConfigEntityBase::$uuid protected property The UUID for this entity.
ConfigEntityBase::$_core protected property Information maintained by Drupal core about configuration.
ConfigEntityBase::addDependency protected function Overrides \Drupal\Core\Entity\DependencyTrait:addDependency().
ConfigEntityBase::createDuplicate public function Creates a duplicate of the entity. Overrides EntityBase::createDuplicate 1
ConfigEntityBase::disable public function Disables the configuration entity. Overrides ConfigEntityInterface::disable 1
ConfigEntityBase::enable public function Enables the configuration entity. Overrides ConfigEntityInterface::enable
ConfigEntityBase::get public function Returns the value of a property. Overrides ConfigEntityInterface::get
ConfigEntityBase::getCacheTagsToInvalidate public function Returns the cache tags that should be used to invalidate caches. Overrides EntityBase::getCacheTagsToInvalidate 1
ConfigEntityBase::getConfigDependencyName public function Gets the configuration dependency name. Overrides EntityBase::getConfigDependencyName
ConfigEntityBase::getConfigManager protected static function Gets the configuration manager.
ConfigEntityBase::getConfigTarget public function Gets the configuration target identifier for the entity. Overrides EntityBase::getConfigTarget
ConfigEntityBase::getDependencies public function Gets the configuration dependencies. Overrides ConfigEntityInterface::getDependencies
ConfigEntityBase::getOriginalId public function Gets the original ID. Overrides EntityBase::getOriginalId
ConfigEntityBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
ConfigEntityBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
ConfigEntityBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
ConfigEntityBase::getTypedConfig protected function Gets the typed config manager.
ConfigEntityBase::hasTrustedData public function Gets whether on not the data is trusted. Overrides ConfigEntityInterface::hasTrustedData
ConfigEntityBase::invalidateTagsOnDelete protected static function Override to never invalidate the individual entities' cache tags; the config system already invalidates them. Overrides EntityBase::invalidateTagsOnDelete
ConfigEntityBase::invalidateTagsOnSave protected function Override to never invalidate the entity's cache tag; the config system already invalidates it. Overrides EntityBase::invalidateTagsOnSave
ConfigEntityBase::isInstallable public function Checks whether this entity is installable. Overrides ConfigEntityInterface::isInstallable 2
ConfigEntityBase::isNew public function Overrides Entity::isNew(). Overrides EntityBase::isNew
ConfigEntityBase::isUninstalling public function Returns whether this entity is being changed during the uninstall process. Overrides ConfigEntityInterface::isUninstalling
ConfigEntityBase::link public function Deprecated way of generating a link to the entity. See toLink(). Overrides EntityBase::link
ConfigEntityBase::preDelete public static function Acts on entities before they are deleted and before hooks are invoked. Overrides EntityBase::preDelete 8
ConfigEntityBase::save public function Saves an entity permanently. Overrides EntityBase::save 1
ConfigEntityBase::set public function Sets the value of a property. Overrides ConfigEntityInterface::set
ConfigEntityBase::setOriginalId public function Sets the original ID. Overrides EntityBase::setOriginalId
ConfigEntityBase::setStatus public function Sets the status of the configuration entity. Overrides ConfigEntityInterface::setStatus
ConfigEntityBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
ConfigEntityBase::setUninstalling public function
ConfigEntityBase::sort public static function Helper callback for uasort() to sort configuration entities by weight and label. 6
ConfigEntityBase::status public function Returns whether the configuration entity is enabled. Overrides ConfigEntityInterface::status 4
ConfigEntityBase::toArray public function Gets an array of all property values. Overrides EntityBase::toArray 2
ConfigEntityBase::toUrl public function Gets the URL object for the entity. Overrides EntityBase::toUrl
ConfigEntityBase::trustData public function Sets that the data should be trusted. Overrides ConfigEntityInterface::trustData
ConfigEntityBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
ConfigEntityBase::url public function Gets the public URL for this entity. Overrides EntityBase::url
ConfigEntityBase::urlInfo public function Gets the URL object for the entity. Overrides EntityBase::urlInfo
ConfigEntityBase::__construct public function Constructs an Entity object. Overrides EntityBase::__construct 10
ConfigEntityBase::__sleep public function Overrides EntityBase::__sleep 4
ConfigEntityBundleBase::deleteDisplays protected function Deletes display if a bundle is deleted.
ConfigEntityBundleBase::loadDisplays protected function Returns view or form displays for this bundle.
ConfigEntityBundleBase::postDelete public static function Acts on deleted entities before the delete hook is invoked. Overrides EntityBase::postDelete 2
ConfigEntityBundleBase::preSave public function Acts on an entity before the presave hook is invoked. Overrides ConfigEntityBase::preSave
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 Aliased as: traitSleep 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency. Aliased as: addDependencyTrait
EntityBase::$enforceIsNew protected property Boolean indicating whether the entity should be forced to be new.
EntityBase::$entityTypeId protected property The entity type.
EntityBase::$typedData protected property A typed data object wrapping this entity.
EntityBase::access public function Checks data value access. Overrides AccessibleInterface::access 1
EntityBase::bundle public function Gets the bundle of the entity. Overrides EntityInterface::bundle 1
EntityBase::create public static function Constructs a new entity object, without permanently saving it. Overrides EntityInterface::create
EntityBase::delete public function Deletes an entity permanently. Overrides EntityInterface::delete 2
EntityBase::enforceIsNew public function Enforces an entity to be new. Overrides EntityInterface::enforceIsNew
EntityBase::entityManager Deprecated protected function Gets the entity manager.
EntityBase::entityTypeBundleInfo protected function Gets the entity type bundle info service.
EntityBase::entityTypeManager protected function Gets the entity type manager.
EntityBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyTrait::getCacheContexts
EntityBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyTrait::getCacheMaxAge
EntityBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyTrait::getCacheTags
EntityBase::getConfigDependencyKey public function Gets the key that is used to store configuration dependencies. Overrides EntityInterface::getConfigDependencyKey
EntityBase::getEntityType public function Gets the entity type definition. Overrides EntityInterface::getEntityType
EntityBase::getEntityTypeId public function Gets the ID of the type of the entity. Overrides EntityInterface::getEntityTypeId
EntityBase::getListCacheTagsToInvalidate protected function The list cache tags to invalidate for this entity.
EntityBase::getTypedData public function Gets a typed data object for this entity object. Overrides EntityInterface::getTypedData
EntityBase::hasLinkTemplate public function Indicates if a link template exists for a given key. Overrides EntityInterface::hasLinkTemplate
EntityBase::id public function Gets the identifier. Overrides EntityInterface::id 11
EntityBase::label public function Gets the label of the entity. Overrides EntityInterface::label 6
EntityBase::language public function Gets the language of the entity. Overrides EntityInterface::language 1
EntityBase::languageManager protected function Gets the language manager.
EntityBase::linkTemplates protected function Gets an array link templates. 1
EntityBase::load public static function Loads an entity. Overrides EntityInterface::load
EntityBase::loadMultiple public static function Loads one or more entities. Overrides EntityInterface::loadMultiple
EntityBase::postCreate public function Acts on a created entity before hooks are invoked. Overrides EntityInterface::postCreate 4
EntityBase::postLoad public static function Acts on loaded entities. Overrides EntityInterface::postLoad 2
EntityBase::preCreate public static function Changes the values of an entity before it is created. Overrides EntityInterface::preCreate 5
EntityBase::referencedEntities public function Gets a list of entities referenced by this entity. Overrides EntityInterface::referencedEntities 1
EntityBase::toLink public function Generates the HTML for a link to this entity. Overrides EntityInterface::toLink
EntityBase::uriRelationships public function Gets a list of URI relationships supported by this entity. Overrides EntityInterface::uriRelationships
EntityBase::urlRouteParameters protected function Gets an array of placeholders for this entity. 2
EntityBase::uuid public function Gets the entity UUID (Universally Unique Identifier). Overrides EntityInterface::uuid 1
EntityBase::uuidGenerator protected function Gets the UUID generator.
ParagraphsType::$behaviorCollection protected property Holds the collection of behavior plugins that are attached to this Paragraphs type.
ParagraphsType::$behavior_plugins public property The Paragraphs type behavior plugins configuration keyed by their id.
ParagraphsType::$description public property A brief description of this paragraph type.
ParagraphsType::$icon_default protected property Default icon encoded as data URL scheme (RFC 2397).
ParagraphsType::$icon_uuid protected property UUID of the Paragraphs type icon file.
ParagraphsType::$id public property The ParagraphsType ID.
ParagraphsType::$label public property The ParagraphsType label.
ParagraphsType::calculateDependencies public function Calculates dependencies and stores them in the dependency property. Overrides ConfigEntityBase::calculateDependencies
ParagraphsType::getBehaviorPlugin public function Returns an individual plugin instance. Overrides ParagraphsTypeInterface::getBehaviorPlugin
ParagraphsType::getBehaviorPlugins public function Returns the ordered collection of feature plugin instances. Overrides ParagraphsTypeInterface::getBehaviorPlugins
ParagraphsType::getDescription public function Gets the description. Overrides ParagraphsTypeInterface::getDescription
ParagraphsType::getEnabledBehaviorPlugins public function Retrieves all the enabled plugins. Overrides ParagraphsTypeInterface::getEnabledBehaviorPlugins
ParagraphsType::getFileByUuid protected function Gets the file entity defined by the UUID.
ParagraphsType::getIconFile public function Returns the icon file entity. Overrides ParagraphsTypeInterface::getIconFile
ParagraphsType::getIconUrl public function Returns the icon's URL. Overrides ParagraphsTypeInterface::getIconUrl
ParagraphsType::getPluginCollections public function Gets the plugin collections used by this object. Overrides ObjectWithPluginCollectionInterface::getPluginCollections
ParagraphsType::hasEnabledBehaviorPlugin public function Returns TRUE if $plugin_id is enabled on this ParagraphType Entity. Overrides ParagraphsTypeInterface::hasEnabledBehaviorPlugin
ParagraphsType::onDependencyRemoval public function Informs the entity that entities it depends on will be deleted. Overrides ConfigEntityBase::onDependencyRemoval
ParagraphsType::postSave public function Acts on a saved entity before the insert or update hook is invoked. Overrides ConfigEntityBundleBase::postSave
ParagraphsType::restoreDefaultIcon protected function Restores the icon file from the default icon value.
ParagraphsType::updateFileIconUsage protected function Updates the icon file usage information.
ParagraphsTypeInterface::ICON_UPLOAD_LOCATION constant Icon upload location.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
SynchronizableEntityTrait::$isSyncing protected property Whether this entity is being created, updated or deleted through a synchronization process.
SynchronizableEntityTrait::isSyncing public function
SynchronizableEntityTrait::setSyncing public function