Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
novicell/dds_global_content / src / GlobalContent.php
Size: Mime:
<?php

namespace Drupal\dds_global_content;

/**
 * Class \Drupal\dds_global_content\GlobalContentStorageException()ge
 * Drupal\dds_global_content
 */

use Drupal\Component\Transliteration\TransliterationInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Render\RenderableInterface;
use Drupal\Core\TypedData\TranslatableInterface;

/**
 * Class \Drupal\dds_global_content\GlobalContentStorageException()e
 * Drupal\dds_global_content
 */
class GlobalContent implements CacheableDependencyInterface, TranslatableInterface, RenderableInterface {

  /**
   * The machine name.
   *
   * @var
   */
  private $machine_name;

  /**
   * The global_content data.
   *
   * @var
   */
  private $data;

  /**
   * The language of the data.
   *
   * @var string
   */
  private $langcode;

  /**
   * The type of field to use for editing.
   *
   * @var string
   */
  private $type;

  /**
   * @var array
   */
  private $options = [];

  /**
   * @var
   */
  private $title;

  /**
   * @var
   */
  private $description;

  /**
   * @var string
   */
  private $category = 'Miscellaneous';

  /**
   * @var string
   */
  private $group_name;

  /**
   * @var string
   */
  private $group_id = '';

  /**
   * @var string
   */
  private $subgroup_name;

  /**
   * @var string
   */
  private $subgroup_id;

  /**
   * @var int
   */
  private $weight = 0;

  /**
   * @var
   */
  private $default;

  /** @var GlobalContentPluginInterface $plugin */
  private $plugin;

  private $isNew = TRUE;

  public function __construct(array $values = []) {
    $this->setValues($values);
  }

  /**
   * @return string|null
   */
  public function getMachineName(): ?string {
    return $this->machine_name;
  }

  /**
   * @param string $machine_name
   *
   * @return GlobalContent
   */
  public function setMachineName($machine_name) {
    $this->machine_name = $machine_name;
    return $this;
  }

  /**
   * @return mixed
   */
  public function getData() {
    return $this->data;
  }

  /**
   * @param mixed $data
   *
   * @return self
   */
  public function setData($data) {
    $this->data = $data;
    return $this;
  }

  /**
   * @return string
   */
  public function getLangcode() {

    if (empty($this->langcode)) {
      return LanguageInterface::LANGCODE_NOT_SPECIFIED;
    } elseif (!$this->isTranslatable()) {
      return LanguageInterface::LANGCODE_NOT_APPLICABLE;
    }

    return $this->langcode;
  }

  /**
   * @param string $langcode
   *
   * @return \Drupal\dds_global_content\GlobalContent
   */
  public function setLangcode($langcode) {
    if ($this->isTranslatable()) {
      $this->langcode = $langcode;
    } else {
      $this->langcode = LanguageInterface::LANGCODE_NOT_APPLICABLE;
    }
    //$this->setIsNew(!$this->getStorage()->languageExists($this->getMachineName(), $langcode));
    return $this;
  }

  /**
   * @return string
   */
  public function getType() {
    return $this->type;
  }

  /**
   * @param string $type
   *
   * @return GlobalContent
   */
  public function setType($type) {
    $this->type = $type;
    return $this;
  }

  /**
   * @return array
   */
  public function getOptions() {
    return $this->options;
  }

  /**
   * @param array $options
   *
   * @return self
   */
  public function setOptions(array $options) {
    $this->options = $options;
    return $this;
  }

  /**
   * @return array
   */
  public function getTokenTypes() {
    if (isset($this->options['token_types']) && is_array($this->options['token_types'])) {
      return $this->options['token_types'];
    } else {
      return [];
    }
  }

  /**
   * @param mixed $token_types
   *
   * @return \Drupal\dds_global_content\GlobalContent
   */
  public function setTokenTypes($token_types) {
    if (is_string($token_types)) {
      $this->options['token_types'] = explode(',', $token_types);
    }
    elseif (is_array($token_types)) {
      $this->options['token_types'] = $token_types;
    }
    return $this;
  }

  /**
   * @return GlobalContentPluginInterface|null
   */
  public function getPlugin() {
    if (empty($this->plugin)) {
      /** @var GlobalContentManager $manager */
      $manager = \Drupal::service('plugin.global_content.manager');
      if ($instance = $manager->createInstanceFromType($this->getType())) {
        $this->plugin = $instance;
      }
    }
    return $this->plugin;
  }

  /**
   * @param \Drupal\dds_global_content\GlobalContentPluginInterface $plugin
   *
   * @return self
   */
  public function setPlugin(GlobalContentPluginInterface $plugin) {
    $this->plugin = $plugin;
    return $this;
  }

  /**
   * @param mixed $plugin
   */
  //  public function setPlugin($plugin) {
  //    $this->plugin = $plugin;
  //    return $this;
  //  }

  /**
   * @return string
   */
  public function getTitle() {
    return $this->title;
  }

  /**
   * @param string $title
   *
   * @return GlobalContent
   */
  public function setTitle($title) {
    $this->title = $title;
    return $this;
  }

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

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

  /**
   * @return string
   */
  public function getCategory() {
    return $this->category;
  }

  /**
   * @param string $category
   *
   * @return GlobalContent
   */
  public function setCategory($category) {
    $this->category = $category;
    $this->group_id = '';
    return $this;
  }

  /**
   * @return string
   */
  public function getGroupID() {
    if (empty($this->group_id)) {
      $key = $this->getCategory() . ':' . $this->getGroupName();
      /** @var TransliterationInterface $transliteration */
      $transliteration = \Drupal::service('transliteration');
      $group_id = $transliteration->transliterate($key, LanguageInterface::LANGCODE_DEFAULT, '_');
      $group_id = strtolower($group_id);
      $group_id = preg_replace('/[^a-z0-9_]+/', '_', $group_id);
      $group_id = preg_replace('/_+/', '_', $group_id);
      $this->setGroupID($group_id);
    }
    return $this->group_id;
  }

  /**
   * @param string $group_id
   *
   * @return self
   */
  public function setGroupID($group_id) {
    $this->group_id = $group_id;
    return $this;
  }

  /**
   * @return string
   */
  public function getGroupName() {
    return $this->group_name;
  }

  /**
   * @param string $group_name
   *
   * @return self
   */
  public function setGroupName($group_name) {
    $this->group_name = $group_name;
    $this->group_id = '';
    return $this;
  }

  /**
   * @return string
   */
  public function getSubgroupName() {
    return $this->subgroup_name;
  }

  /**
   * @return string
   */
  public function getSubgroupID() {
    if (empty($this->subgroup_id)) {
      $key = $this->getSubgroupName();
      /** @var TransliterationInterface $transliteration */
      $transliteration = \Drupal::service('transliteration');
      $group_id = $transliteration->transliterate($key, LanguageInterface::LANGCODE_DEFAULT, '_');
      $group_id = strtolower($group_id);
      $group_id = preg_replace('/[^a-z0-9_]+/', '_', $group_id);
      $group_id = preg_replace('/_+/', '_', $group_id);
      $this->subgroup_id = $group_id;
    }
    return $this->subgroup_id;
  }

  /**
   * @param string $subgroup_name
   *
   * @return self
   */
  public function setSubgroupName($subgroup_name) {
    $this->subgroup_name = $subgroup_name;
    return $this;
  }

  /**
   * @return int
   */
  public function getWeight() {
    return $this->weight;
  }

  /**
   * @param int $weight
   *
   * @return \Drupal\dds_global_content\GlobalContent
   */
  public function setWeight($weight) {
    $this->weight = $weight;
    return $this;
  }

  /**
   * @return string|array
   */
  public function getDefault() {
    return $this->default;
  }

  /**
   * @param mixed $default
   *
   * @return \Drupal\dds_global_content\GlobalContent
   */
  public function setDefault($default) {
    $this->default = $default;
    return $this;
  }

  /**
   * @return GlobalContentStorage
   */
  public function getStorage() {
    return \Drupal::service('global_content.storage');
  }


  /**
   * @param array $values
   *
   * @return self
   */
  public function setValues(array $values) {
    foreach ($values as $key => $value) {
      switch($key) {
        case 'data':
          if ($this->isSerialized($value)) {
            $this->setData(unserialize($value));
          } else {
            $this->setData($value);
          }
          break;
        case 'options':
          if ($this->isSerialized($value)) {
            $this->setOptions(unserialize($value));
          } else {
            $this->setOptions($value);
          }
          break;
        case 'token_types':
          $this->setTokenTypes($value);
          break;
        case 'group_name':
          $this->setGroupName($value);
          break;
        case 'subgroup_name':
          $this->setSubgroupName($value);
          break;
        default:
          if (property_exists($this, $key)) {
            $this->$key = $value;
          }
          break;
      }
    }
    return $this;
  }

  /**
   * @param string $machine_name
   * @param string|null $langcode
   *
   * @return \Drupal\dds_global_content\GlobalContent|null
   */
  public static function load($machine_name, $langcode = NULL) {
    //    $storage = \Drupal::service('global_content.storage');
    //    $fields = $storage->findByMachineName($machine_name, $langcode);
    //    $global_content = new GlobalContent($fields);
    //    $global_content->locations = $storage->getLocations($machine_name, $langcode);
    $global_content = self::loadMultiple([$machine_name], $langcode);
    if (empty($global_content)) {
      return NULL;
    }
    else {
      return reset($global_content);
    }
  }

  /**
   * @param string $group_id
   * @param string|null $langcode
   *
   * @return GlobalContent[]
   */
  public static function loadGroup($group_id, $langcode = NULL) {
    /** @var \Drupal\dds_global_content\GlobalContentStorage $storage */
    $storage = \Drupal::service('global_content.storage');
    $machine_names = $storage->getMachineNames($group_id);
    return self::loadMultiple($machine_names, $langcode);
  }

  /**
   * @param array $machine_names
   * @param string|null $langcode
   *
   * @return GlobalContent[]
   */
  public static function loadMultiple(array $machine_names, $langcode = NULL) {
    /** @var GlobalContentStorage $storage */
    $storage = \Drupal::service('global_content.storage');
    $loaded = $storage->loadMultiple($machine_names, $langcode);

    $response = [];
    foreach ($loaded as $content) {
      $response[] = new GlobalContent($content);
    }
    return $response;
  }

  /**
   * @return self
   * @throws \Drupal\dds_global_content\GlobalContentStorageException
   */
  public function save() {
    if ($storage = $this->getStorage()) {
      $storage->save($this);
    }
    else {
      throw new GlobalContentStorageException('The data cannot be saved because its not bound to a storage: ' . $this->getTitle());
    }
    return $this;
  }

  /**
   * @return self
   * @throws \Drupal\dds_global_content\GlobalContentStorageException
   */
  public function rebuild() {
    if ($storage = $this->getStorage()) {
      $storage->rebuild($this);
    }
    else {
      throw new GlobalContentStorageException('The data cannot be saved because its not bound to a storage: ' . $this->getTitle());
    }
    return $this;
  }

  /**
   * @return \Drupal\dds_global_content\ViewableGlobalContent
   */
  public function view() {
    /** @var GlobalContentViewBuilder $service */
    $service = \Drupal::service('global_contents');
    return $service->get($this->getMachineName(), $this->getLangcode());
  }

  /**
   * Returns a render array representation of the object.
   *
   * @return array
   *   A render array.
   */
  public function toRenderable() {
    return $this->view()->toRenderable();
  }

  /**
   * Checks if string is serialized data
   *
   * @param $string string String to check
   *
   * @return bool
   */
  function isSerialized($string) {
    return ($string === 'b:0;' || @unserialize($string) !== FALSE);
  }

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

  /**
   * Set whether the Global Content object is new and previously unsaved to the database
   *
   * @param bool $isNew
   */
  public function setIsNew(bool $isNew) {
    $this->isNew = $isNew;
  }

  public function getDefaultLangcode() {
    \Drupal::languageManager()->getDefaultLanguage();
  }

  /**
   * The cache contexts associated with this object.
   *
   * These identify a specific variation/representation of the object.
   *
   * Cache contexts are tokens: placeholders that are converted to cache keys by
   * the @cache_contexts_manager service. The replacement value depends on the
   * request context (the current URL, language, and so on). They're converted
   * before storing an object in cache.
   *
   * @return string[]
   *   An array of cache context tokens, used to generate a cache ID.
   *
   * @see \Drupal\Core\Cache\Context\CacheContextsManager::convertTokensToKeys()
   */
  public function getCacheContexts() {
    if (!$this->isTranslatable()) {
      return [];
    } else {
      return [
        'languages:' . LanguageInterface::TYPE_CONTENT
      ];
    }
  }

  /**
   * The cache tags associated with this object.
   *
   * When this object is modified, these cache tags will be invalidated.
   *
   * @return string[]
   *   A set of cache tags.
   */
  public function getCacheTags() {
    return [
      'global_content:' . $this->getMachineName()
    ];
  }

  /**
   * The maximum age for which this object may be cached.
   *
   * @return int
   *   The maximum time in seconds that this object may be cached.
   */
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * Returns the translation language.
   *
   * @return \Drupal\Core\Language\LanguageInterface
   *   The language object.
   */
  public function language() {
    \Drupal::languageManager()->getLanguage($this->getLangcode());
  }

  /**
   * Checks whether the translation is the default one.
   *
   * @return bool
   *   TRUE if the translation is the default one, FALSE otherwise.
   */
  public function isDefaultTranslation() {
    return $this->getLangcode() == $this->getDefaultLangcode();
  }

  /**
   * Checks whether the translation is new.
   *
   * @return bool
   *   TRUE if the translation is new, FALSE otherwise.
   */
  public function isNewTranslation() {
    return $this->isNew();
  }

  /**
   * Returns the languages the data is translated to.
   *
   * @param bool $include_default
   *   (optional) Whether the default language should be included. Defaults to
   *   TRUE.
   *
   * @return \Drupal\Core\Language\LanguageInterface[]
   *   An associative array of language objects, keyed by language codes.
   */
  public function getTranslationLanguages($include_default = TRUE) {
    $translations = $this->getStorage()->getTranslations($this->getMachineName());
    if (!$include_default) {
      foreach ($translations as $index => $langcode) {
        if ($langcode == $this->getDefaultLangcode()) {
          unset ($translations[$index]);
        }
      }
    }
    return $translations;
  }

  /**
   * Gets a translation of the data.
   *
   * The returned translation has to be of the same type than this typed data
   * object.
   *
   * @param $langcode
   *   The language code of the translation to get or
   *   LanguageInterface::LANGCODE_DEFAULT
   *   to get the data in default language.
   *
   * @return $this
   *   A typed data object for the translated data.
   *
   * @throws \InvalidArgumentException
   *   If an invalid or non-existing translation language is specified.
   */
  public function getTranslation($langcode) {
    return static::load($this->getMachineName(), $langcode);
  }

  /**
   * Returns the translatable object referring to the original language.
   *
   * @return $this
   *   The translation object referring to the original language.
   */
  public function getUntranslated() {
    if ($this->isDefaultTranslation()) {
      return $this;
    } else {
      return $this->getTranslation($this->getDefaultLangcode());
    }
  }

  /**
   * Checks there is a translation for the given language code.
   *
   * @param string $langcode
   *   The language code identifying the translation.
   *
   * @return bool
   *   TRUE if the translation exists, FALSE otherwise.
   */
  public function hasTranslation($langcode) {
    return $this->getStorage()->languageExists($this->getMachineName(), $langcode);
  }

  /**
   * Adds a new translation to the translatable object.
   *
   * @param string $langcode
   *   The language code identifying the translation.
   * @param array $values
   *   (optional) An array of initial values to be assigned to the translatable
   *   fields. Defaults to none.
   *
   * @return $this
   *
   * @throws \InvalidArgumentException
   *   If an invalid or existing translation language is specified.
   */
  public function addTranslation($langcode, array $values = []) {
    if ($this->hasTranslation($langcode)) {
      throw new \InvalidArgumentException();
    }
    $globalContent = clone $this;
    $globalContent->setLangcode($langcode);
    if (!empty($values)) $globalContent->setData($values);
    try {
      $globalContent->save();
      return $globalContent;
    } catch (\Exception $exception) {
      return $globalContent;
    }
  }

  /**
   * Removes the translation identified by the given language code.
   *
   * @param string $langcode
   *   The language code identifying the translation to be removed.
   */
  public function removeTranslation($langcode) {
    if ($langcode != $this->getDefaultLangcode()) {
      $this->getStorage()
        ->deleteTranslation($this->getMachineName(), $langcode);
    }
  }

  /**
   * Returns the translation support status.
   *
   * @return bool
   *   TRUE if the object has translation support enabled.
   */
  public function isTranslatable() {
    return $this->getOptions()['translatable'] ?? TRUE;
  }
}