You are here

class MessageTemplate in Message 8

Defines the Message template entity class.

Plugin annotation


@ConfigEntityType(
  id = "message_template",
  label = @Translation("Message template"),
  label_plural = @Translation("message templates"),
  label_singular = @Translation("message template"),
  label_count = @PluralTranslation(
    singular="@count message template",
    plural="@count message templates"
  ),
  config_prefix = "template",
  bundle_of = "message",
  entity_keys = {
    "id" = "template",
    "label" = "label",
    "langcode" = "langcode",
  },
  admin_permission = "administer message templates",
  handlers = {
    "form" = {
      "add" = "Drupal\message\Form\MessageTemplateForm",
      "edit" = "Drupal\message\Form\MessageTemplateForm",
      "delete" = "Drupal\message\Form\MessageTemplateDeleteConfirm"
    },
    "list_builder" = "Drupal\message\MessageTemplateListBuilder",
    "view_builder" = "Drupal\message\MessageViewBuilder",
  },
  links = {
    "add-form" = "/admin/structure/message/template/add",
    "edit-form" = "/admin/structure/message/manage/{message_template}",
    "delete-form" = "/admin/structure/message/delete/{message_template}"
  },
  config_export = {
    "template",
    "label",
    "langcode",
    "description",
    "text",
    "settings",
    "status"
  }
)

Hierarchy

Expanded class hierarchy of MessageTemplate

10 files declare their use of MessageTemplate
DaysTest.php in tests/src/Kernel/Plugin/MessagePurge/DaysTest.php
message.module in ./message.module
API functions to manipulate messages.
MessageCron.php in tests/src/Functional/MessageCron.php
MessageTemplateCreateTrait.php in tests/src/Kernel/MessageTemplateCreateTrait.php
MessageTemplateDependenciesTest.php in tests/src/Kernel/MessageTemplateDependenciesTest.php

... See full list

File

src/Entity/MessageTemplate.php, line 58

Namespace

Drupal\message\Entity
View source
class MessageTemplate extends ConfigEntityBundleBase implements MessageTemplateInterface {

  /**
   * The ID of this message template.
   *
   * @var string
   */
  protected $template;

  /**
   * The UUID of the message template.
   *
   * @var string
   */
  protected $uuid;

  /**
   * The human-readable name of the message template.
   *
   * @var string
   */
  protected $label;

  /**
   * A brief description of this message template.
   *
   * @var string
   */
  protected $description;

  /**
   * The serialised text of the message template.
   *
   * @var array
   */
  protected $text = [];

  /**
   * Array with the arguments and their replacement value, or callbacks.
   *
   * The argument keys will be replaced when rendering the message, and it
   * should be prefixed by @, %, ! - similar to way it's done in Drupal
   * core's t() function.
   *
   * @var array
   *
   * @code
   *
   * // Assuming out message-text is:
   * // %user-name created <a href="@message-url">@message-title</a>
   *
   * $message_template->arguments = [
   *   // Hard code the argument.
   *   '%user-name' => 'foo',
   *
   *   // Use a callback, and provide callbacks arguments.
   *   // The following example will call Drupal core's url() function to
   *   // get the most up-to-date path of message ID 1.
   *   '@message-url' => [
   *      'callback' => 'url',
   *      'callback arguments' => ['message/1'],
   *    ],
   *
   *   // Use callback, but instead of passing callback argument, we will
   *   // pass the Message entity itself.
   *   '@message-title' => [
   *      'callback' => 'example_bar',
   *      'pass message' => TRUE,
   *    ],
   * ];
   * @endcode
   *
   * Arguments assigned to message-template can be overridden by the ones
   * assigned to the message.
   */
  public $arguments = [];

  /**
   * Serialized array with misc options.
   *
   * Purge settings:
   * - 'purge_override': TRUE or FALSE override the global behavior.
   *    "Message settings" will apply. Defaults to FALSE.
   * - 'purge_methods': An array of purge method plugin configuration, keyed by
   *   the plugin ID. An empty array indicates no purge is enabled (although
   *   global settings will be used unless 'purge_override' is TRUE).
   *
   * Token settings:
   * - 'token replace': Indicate if message's text should be passed
   *    through token_replace(). defaults to TRUE.
   * - 'token options': Array with options to be passed to
   *    token_replace().
   *
   * Tokens settings assigned to message-template can be overriden by the ones
   * assigned to the message.
   *
   * @var array
   */
  protected $settings = [];

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

  /**
   * {@inheritdoc}
   */
  public function setSettings(array $settings) {
    $this->settings = $settings;
    return $this;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getSetting($key, $default_value = NULL) {
    if (isset($this->settings[$key])) {
      return $this->settings[$key];
    }
    return $default_value;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function setLabel($label) {
    $this->label = $label;
    return $this;
  }

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

  /**
   * {@inheritdoc}
   */
  public function setTemplate($template) {
    $this->template = $template;
    return $this;
  }

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

  /**
   * {@inheritdoc}
   */
  public function setUuid($uuid) {
    $this->uuid = $uuid;
    return $this;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function getText($langcode = Language::LANGCODE_NOT_SPECIFIED, $delta = NULL) {
    $text = $this->text;
    $language_manager = \Drupal::languageManager();
    if ($language_manager instanceof ConfigurableLanguageManagerInterface) {
      if ($langcode == Language::LANGCODE_NOT_SPECIFIED) {

        // Get the default language code when not specified.
        $langcode = $language_manager
          ->getDefaultLanguage()
          ->getId();
      }
      if ($this->langcode !== $langcode) {
        $config_translation = $language_manager
          ->getLanguageConfigOverride($langcode, 'message.template.' . $this
          ->id());
        $translated_text = $config_translation
          ->get('text');

        // If there was no translated text, we return nothing instead of falling
        // back to the default language.
        $text = $translated_text ?: [];
      }
    }

    // Process text format.
    foreach ($text as $key => $item) {

      // Call the renderer directly instead of adding a dependency on the Filter
      // module's check_markup() function.
      // @see check_markup()
      $build = [
        '#type' => 'processed_text',
        '#text' => isset($item['value']) ? $item['value'] : '',
        '#format' => $item['format'],
        '#langcode' => $langcode,
      ];
      $text[$key] = \Drupal::service('renderer')
        ->renderPlain($build);
    }
    if (isset($delta)) {

      // Return just the delta if it exists. Always wrap in an array here to
      // ensure compatibility with methods calling getText.
      return isset($text[$delta]) ? [
        $text[$delta],
      ] : [];
    }
    return $text;
  }

  /**
   * {@inheritdoc}
   */
  public function isLocked() {
    return !$this
      ->isNew();
  }

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\message\MessageTemplateInterface
   *   A message template object ready to be save.
   */
  public static function create(array $values = []) {
    return parent::create($values);
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {

    // Don't do anything during config sync.
    if (\Drupal::isConfigSyncing()) {
      return;
    }
    $this->text = array_filter($this->text, function ($partial) {

      // Filter out any partials with an empty `value`.
      return !empty($partial['value']);
    });
    $language_manager = \Drupal::languageManager();
    if ($language_manager instanceof ConfigurableLanguageManagerInterface) {

      // Set the values for the default site language.
      $config_translation = $language_manager
        ->getLanguageConfigOverride($language_manager
        ->getDefaultLanguage()
        ->getId(), 'message.template.' . $this
        ->id());
      $config_translation
        ->set('text', $this->text);
      $config_translation
        ->save();
    }
    parent::preSave($storage);
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
    $text_format_ids = [];
    foreach ($this->text as $item) {
      if (!empty($item['format']) && !in_array($item['format'], $text_format_ids, TRUE)) {
        $text_format_ids[] = $item['format'];
      }
    }

    // The template depends on the text text format config entities, if any.
    if ($text_format_ids) {
      $text_format_storage = $this
        ->entityTypeManager()
        ->getStorage('filter_format');
      foreach ($text_format_storage
        ->loadMultiple($text_format_ids) as $id => $text_format) {
        $this
          ->addDependency($text_format
          ->getConfigDependencyKey(), $text_format
          ->getConfigDependencyName());
      }
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) {
    $changed = parent::onDependencyRemoval($dependencies);
    foreach ($dependencies['config'] as $text_format) {
      if ($text_format instanceof FilterFormatInterface) {
        foreach ($this->text as &$item) {
          if (!empty($item['format']) && $item['format'] === $text_format
            ->id()) {

            // If a text format, in use by this template, is removed, prevent
            // deleting the whole message template and replace the deleted text
            // format with the fallback format.
            $item['format'] = filter_fallback_format();
            $changed = TRUE;
          }
        }
      }
    }
    return $changed;
  }

}

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::$_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::postSave public function Acts on a saved entity before the insert or update hook is invoked. Overrides EntityBase::postSave 2
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::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::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.
MessageTemplate::$arguments public property Array with the arguments and their replacement value, or callbacks.
MessageTemplate::$description protected property A brief description of this message template.
MessageTemplate::$label protected property The human-readable name of the message template.
MessageTemplate::$settings protected property Serialized array with misc options.
MessageTemplate::$template protected property The ID of this message template.
MessageTemplate::$text protected property The serialised text of the message template.
MessageTemplate::$uuid protected property The UUID of the message template. Overrides ConfigEntityBase::$uuid
MessageTemplate::calculateDependencies public function Calculates dependencies and stores them in the dependency property. Overrides ConfigEntityBase::calculateDependencies
MessageTemplate::create public static function Overrides EntityBase::create
MessageTemplate::getDescription public function Get the message template description. Overrides MessageTemplateInterface::getDescription
MessageTemplate::getLabel public function Get the message template label. Overrides MessageTemplateInterface::getLabel
MessageTemplate::getRawText public function
MessageTemplate::getSetting public function Return a single setting by key. Overrides MessageTemplateInterface::getSetting
MessageTemplate::getSettings public function Return the message template settings. Overrides MessageTemplateInterface::getSettings
MessageTemplate::getTemplate public function Get the message template. Overrides MessageTemplateInterface::getTemplate
MessageTemplate::getText public function Retrieves the configured message text in a certain language. Overrides MessageTemplateInterface::getText
MessageTemplate::getUuid public function Get the UUID. Overrides MessageTemplateInterface::getUuid
MessageTemplate::id public function Gets the identifier. Overrides EntityBase::id
MessageTemplate::isLocked public function Check if the message is new. Overrides MessageTemplateInterface::isLocked
MessageTemplate::onDependencyRemoval public function Informs the entity that entities it depends on will be deleted. Overrides ConfigEntityBase::onDependencyRemoval
MessageTemplate::preSave public function Acts on an entity before the presave hook is invoked. Overrides ConfigEntityBundleBase::preSave
MessageTemplate::setDescription public function Set the message template description. Overrides MessageTemplateInterface::setDescription
MessageTemplate::setLabel public function Set the message template label. Overrides MessageTemplateInterface::setLabel
MessageTemplate::setSettings public function Set additional settings for the message template. Overrides MessageTemplateInterface::setSettings
MessageTemplate::setTemplate public function Set the message template. Overrides MessageTemplateInterface::setTemplate
MessageTemplate::setUuid public function Set the UUID. Overrides MessageTemplateInterface::setUuid
MessageTemplateInterface::getRaWText public function Return text.
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