You are here

abstract class DemoSystem in Open Social 8

Same name and namespace in other branches
  1. 8.9 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  2. 8.2 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  3. 8.3 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  4. 8.4 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  5. 8.5 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  6. 8.6 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  7. 8.7 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  8. 8.8 modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  9. 10.3.x modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  10. 10.0.x modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  11. 10.1.x modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem
  12. 10.2.x modules/custom/social_demo/src/DemoSystem.php \Drupal\social_demo\DemoSystem

Class DemoSystem.

@package Drupal\social_demo

Hierarchy

Expanded class hierarchy of DemoSystem

1 file declares its use of DemoSystem
System.php in modules/custom/social_demo/src/Plugin/DemoContent/System.php

File

modules/custom/social_demo/src/DemoSystem.php, line 20

Namespace

Drupal\social_demo
View source
abstract class DemoSystem extends DemoContent {

  /**
   * The user storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $blockStorage;

  /**
   * The Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * The file storage.
   *
   * @var \Drupal\file\FileStorageInterface
   */
  protected $fileStorage;

  /**
   * DemoComment constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, DemoContentParserInterface $parser, EntityStorageInterface $block_storage, ConfigFactory $config_factory, FileStorageInterface $file_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->parser = $parser;
    $this->blockStorage = $block_storage;
    $this->configFactory = $config_factory;
    $this->fileStorage = $file_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('social_demo.yaml_parser'), $container
      ->get('entity.manager')
      ->getStorage('block_content'), $container
      ->get('config.factory'), $container
      ->get('entity.manager')
      ->getStorage('file'));
  }

  /**
   * {@inheritdoc}
   */
  public function createContent() {

    // Fetch data from yml file.
    $data = $this
      ->fetchData();

    // First let's load the active theme.
    $active_theme = \Drupal::theme()
      ->getActiveTheme()
      ->getName();

    // Site.
    if (isset($data['site'])) {
      $this->content['site'] = TRUE;

      // Get editable config.
      $config = $this->configFactory
        ->getEditable('system.site');

      // Set the site name and save.
      $config
        ->set('name', $data['site']['name'])
        ->save();
    }

    // Homepage block.
    if (isset($data['homepage'])) {
      $this->content['homepage'] = TRUE;

      // This uuid can be used like this since it's defined
      // in the code as well (@see social_core.install).
      $block = $this->blockStorage
        ->loadByProperties([
        'uuid' => '8bb9d4bb-f182-4afc-b138-8a4b802824e4',
      ]);
      $block = current($block);
      if ($block instanceof BlockContent) {
        $this
          ->replaceAnBlock($block, $data['homepage']);
      }
    }

    // Theme settings.
    if (isset($data['theme'])) {
      $this->content['theme'] = TRUE;

      // Get theme settings.
      $config = $this->configFactory
        ->getEditable($active_theme . '.settings');

      // Favicon.
      if (isset($data['theme']['favicon'])) {
        $favicon = [
          'mimetype' => $data['theme']['favicon']['mimetype'],
          'path' => $data['theme']['favicon']['path'],
          'url' => $data['theme']['favicon']['url'],
          'use_default' => FALSE,
        ];

        // And save it.
        $config
          ->set('favicon', $favicon)
          ->save();
      }

      // Logo.
      $logo = $this
        ->preparePicture($data['theme']['logo']);

      // Must be a valid file.
      if ($logo instanceof File) {
        $theme_logo = [
          'path' => $logo
            ->getFileUri(),
          'url' => file_create_url($logo
            ->getFileUri()),
          'use_default' => FALSE,
        ];

        // Store the array.
        $config
          ->set('logo', $theme_logo)
          ->save();
      }

      // Font.
      $config
        ->set('font_primary', $this
        ->getOrCreateFont($data['theme']['font_primary']))
        ->save();

      // Borders.
      $config
        ->set('card_radius', $data['theme']['card_radius'])
        ->save();
      $config
        ->set('form_control_radius', $data['theme']['form_control_radius'])
        ->save();
      $config
        ->set('button_radius', $data['theme']['button_radius'])
        ->save();

      // Get the colors.
      $color = $this->configFactory
        ->getEditable('color.theme.' . $active_theme);

      // Set as a palette.
      $palette = [
        'brand-primary' => $data['theme']['color_primary'],
        'brand-secondary' => $data['theme']['color_secondary'],
        'brand-accent' => $data['theme']['color_accents'],
        'brand-link' => $data['theme']['color_link'],
        'navbar-bg' => $data['theme']['navbar-bg'],
        'navbar-text' => $data['theme']['navbar-text'],
        'navbar-active-bg' => $data['theme']['navbar-active-bg'],
        'navbar-active-text' => $data['theme']['navbar-active-text'],
        'navbar-sec-bg' => $data['theme']['navbar-sec-bg'],
        'navbar-sec-text' => $data['theme']['navbar-sec-text'],
      ];

      // Save the palette.
      $color
        ->set('palette', $palette)
        ->save();

      /*
       * The code below has been stolen from the color.module. This module makes
       * no use of services or any other way to make its code a bit more
       * re-usable. Therefore a rip/copy was needed.
       *
       * The code makes sure that the above enforced color configuration is
       * in fact applied.
       */

      // Define the library name(s).
      $libraries = [
        'assets/css/brand.css',
      ];
      $id = $active_theme . '-' . substr(hash('sha256', serialize($palette) . microtime()), 0, 8);
      $paths['color'] = 'public://color';
      $paths['target'] = $paths['color'] . '/' . $id;
      foreach ($paths as $path) {
        file_prepare_directory($path, FILE_CREATE_DIRECTORY);
      }
      $paths['target'] = $paths['target'] . '/';
      $paths['id'] = $id;
      $paths['source'] = drupal_get_path('theme', $active_theme) . '/';
      $paths['files'] = $paths['map'] = [];
      $css = [];
      foreach ($libraries as $stylesheet) {

        // Build a temporary array with CSS files.
        $files = [];
        if (file_exists($paths['source'] . $stylesheet)) {
          $files[] = $stylesheet;
        }
        foreach ($files as $file) {
          $css_optimizer = new CssOptimizer();

          // Aggregate @imports recursively for each configured top level
          // CSS file without optimization.
          // Aggregation and optimization will be handled by
          // drupal_build_css_cache() only.
          $style = $css_optimizer
            ->loadFile($paths['source'] . $file, FALSE);

          // Return the path to where this CSS file originated from, stripping
          // off the name of the file at the end of the path.
          $css_optimizer->rewriteFileURIBasePath = base_path() . dirname($paths['source'] . $file) . '/';

          // Prefix all paths within this CSS file, ignoring absolute paths.
          $style = preg_replace_callback('/url\\([\'"]?(?![a-z]+:|\\/+)([^\'")]+)[\'"]?\\)/i', [
            $css_optimizer,
            'rewriteFileURI',
          ], $style);

          // Rewrite stylesheet with new colors.
          $style = _color_rewrite_stylesheet($active_theme, $info, $paths, $palette, $style);
          $base_file = drupal_basename($file);
          $css[] = $paths['target'] . $base_file;
          _color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
        }
      }

      // Maintain list of files.
      $color
        ->set('stylesheets', $css)
        ->set('files', $paths['files'])
        ->save();
    }

    // Return something.
    return $this->content;
  }

  /**
   * {@inheritdoc}
   */
  public function getEntry(array $item) {

    // TODO: Implement getEntry() method.
  }

  /**
   * Prepares data about an image.
   *
   * @param string $picture
   *   The picture by uuid.
   *
   * @return array
   *   Returns an array.
   */
  protected function preparePicture($picture) {
    $value = NULL;
    $files = $this->fileStorage
      ->loadByProperties([
      'uuid' => $picture,
    ]);
    if ($files) {
      return current($files);
    }
    return $value;
  }

  /**
   * Get or create the font.
   *
   * @param string $fontName
   *   The font name.
   *
   * @return int|mixed|null|string
   *   Return the font.
   */
  private function getOrCreateFont($fontName) {

    /** @var \Drupal\social_font\Entity\Font $font_entities */
    foreach (Font::loadMultiple() as $font_entities) {
      if ($fontName == $font_entities
        ->get('name')->value) {
        return $font_entities
          ->id();
      }
    }

    // Ok, so it doesn't exist.

    /* @var Font $font */
    $font = Font::create([
      'name' => $fontName,
      'user_id' => 1,
      'created' => \Drupal::time()
        ->getRequestTime(),
      'field_fallback' => '0',
    ]);
    $font
      ->save();

    // Return the id.
    return $font
      ->id();
  }

  /**
   * Function to replace the AN homepage Block.
   *
   * @param \Drupal\block_content\Entity\BlockContent $block
   *   The block.
   * @param array $data
   *   The data.
   */
  private function replaceAnBlock(BlockContent $block, array $data) {
    $block->field_text_block = [
      'value' => $data['textblock'],
      'format' => 'full_html',
    ];

    /* @var \Drupal\file\Entity\File $file */
    $file = $this
      ->preparePicture($data['image']);
    $block_image = [
      'target_id' => $file
        ->id(),
      'alt' => "Anonymous front page image homepage'",
    ];
    $block->field_hero_image = $block_image;

    // Set the links.
    $action_links = [
      [
        'uri' => 'internal:' . $data['cta1']['url'],
        'title' => $data['cta1']['text'],
      ],
      [
        'uri' => 'internal:' . $data['cta2']['url'],
        'title' => $data['cta2']['text'],
      ],
    ];
    $itemList = new FieldItemList($block->field_call_to_action_link
      ->getFieldDefinition());
    $itemList
      ->setValue($action_links);
    $block->field_call_to_action_link = $itemList;
    $block
      ->save();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DemoContent::$content protected property Contains the created content.
DemoContent::$data protected property Contains data from a file.
DemoContent::$entityStorage protected property Contains the entity storage.
DemoContent::$parser protected property Parser.
DemoContent::$profile protected property Profile.
DemoContent::checkMentionOrLinkByUuid protected function Extract the mention from the content by [~Uuid].
DemoContent::count public function Returns quantity of created items. Overrides DemoContentInterface::count 1
DemoContent::fetchData protected function Gets the data from a file.
DemoContent::getModule public function Returns the module name. Overrides DemoContentInterface::getModule
DemoContent::getProfile public function Returns the profile. Overrides DemoContentInterface::getProfile
DemoContent::getSource public function Returns the file name. Overrides DemoContentInterface::getSource
DemoContent::loadByUuid protected function Load entity by uuid.
DemoContent::removeContent public function Removes content. Overrides DemoContentInterface::removeContent
DemoContent::setEntityStorage public function Set entity storage. Overrides DemoContentInterface::setEntityStorage
DemoContent::setProfile public function Sets the used profile. Overrides DemoContentInterface::setProfile
DemoSystem::$blockStorage protected property The user storage.
DemoSystem::$configFactory protected property The Config factory.
DemoSystem::$fileStorage protected property The file storage.
DemoSystem::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
DemoSystem::createContent public function Creates content. Overrides DemoContentInterface::createContent
DemoSystem::getEntry public function Makes an array with data of an entity. Overrides DemoContent::getEntry
DemoSystem::getOrCreateFont private function Get or create the font.
DemoSystem::preparePicture protected function Prepares data about an image.
DemoSystem::replaceAnBlock private function Function to replace the AN homepage Block.
DemoSystem::__construct public function DemoComment constructor. Overrides PluginBase::__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.
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.