You are here

class BackgroundImageViewBuilder in Background Image 8

Same name and namespace in other branches
  1. 2.x src/BackgroundImageViewBuilder.php \Drupal\background_image\BackgroundImageViewBuilder
  2. 2.0.x src/BackgroundImageViewBuilder.php \Drupal\background_image\BackgroundImageViewBuilder

Hierarchy

Expanded class hierarchy of BackgroundImageViewBuilder

File

src/BackgroundImageViewBuilder.php, line 10

Namespace

Drupal\background_image
View source
class BackgroundImageViewBuilder extends EntityViewBuilder {

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

    /** @type \Drupal\background_image\BackgroundImageInterface $background_image */
    $background_image = $build['#background_image'];
    $manager = BackgroundImageManager::service();
    switch ($build['#view_mode']) {
      case 'image':
        $build['image'] = $this
          ->buildImage($background_image, $manager);
        break;
      case 'text':
        $build['image'] = $this
          ->buildText($background_image, $manager);
        break;
      default:
      case 'full':
        $build['image'] = $this
          ->buildImage($background_image, $manager);
        $build['text'] = $this
          ->buildText($background_image, $manager);
        break;
    }
    return $build;
  }

  /**
   * Builds the image render array.
   *
   * @param \Drupal\background_image\BackgroundImageInterface $background_image
   *   The background image being processed.
   * @param \Drupal\background_image\BackgroundImageManagerInterface $manager
   *   The Background Image Manager service.
   *
   * @return array
   *   The built render array element.
   */
  public function buildImage(BackgroundImageInterface $background_image, BackgroundImageManagerInterface $manager) {

    // Immediately return if there is no image.
    if (!$background_image
      ->getImageFile()) {
      $build['#access'] = FALSE;
      $build['#cache']['contexts'][] = 'background_image';
      return $build;
    }
    $base_class = $manager
      ->getBaseClass();
    $build = [
      '#type' => 'container',
      '#theme_wrappers' => [
        'container__background_image__inner',
      ],
      '#bootstrap_ignore_pre_render' => TRUE,
      '#bootstrap_ignore_process' => TRUE,
      '#attributes' => [
        'class' => [
          "{$base_class}-inner",
        ],
      ],
    ];
    $build['image'] = [
      '#type' => 'container',
      '#theme_wrappers' => [
        'container__background_image__inner__image',
      ],
      '#attributes' => [
        'class' => [
          $base_class,
          $background_image
            ->getCssClass(),
        ],
      ],
      '#bootstrap_ignore_pre_render' => TRUE,
      '#bootstrap_ignore_process' => TRUE,
    ];
    $build['overlay'] = [
      '#type' => 'container',
      '#theme_wrappers' => [
        'container__background_image__inner__overlay',
      ],
      '#attributes' => [
        'class' => [
          "{$base_class}-overlay",
        ],
      ],
      '#bootstrap_ignore_pre_render' => TRUE,
      '#bootstrap_ignore_process' => TRUE,
    ];

    // Attach the scrolling blur effect JavaScript, if necessary.
    $full_viewport = $background_image
      ->getSetting('full_viewport');
    $blur_type = $background_image
      ->getSetting('blur.type');
    if ($blur_type == BackgroundImageInterface::BLUR_SCROLL || $full_viewport && BackgroundImageInterface::BLUR_SCROLL_FULL_VIEWPORT) {
      $build['#attached']['library'][] = 'background_image/scrolling.blur';
      $build['#attached']['drupalSettings']['backgroundImage']['blur'] = $background_image
        ->getSettings()
        ->drupalSettings('blur');
      $build['#attached']['drupalSettings']['backgroundImage']['fullViewport'] = $background_image
        ->getSettings()
        ->drupalSettings('full_viewport');
    }

    // Preload the necessary background background image.
    // @see https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/
    $build['#attached']['html_head_link'][][] = [
      'rel' => 'preload',
      'href' => $background_image
        ->getImageUrl($manager
        ->getPreloadImageStyle()),
      'as' => 'image',
    ];

    // Attach the necessary background image CSS.
    // Due to the dynamic nature of how these are generated, this must be
    // attached via html_head_link instead of a library.
    // @see \Drupal\background_image\Controller\BackgroundImageCssController::deliver
    $build['#attached']['html_head_link'][][] = [
      'rel' => 'stylesheet',
      'href' => file_url_transform_relative(file_create_url($background_image
        ->getCssUri())) . '?' . \Drupal::state()
        ->get('system.css_js_query_string') ?: '0',
      'media' => 'all',
    ];
    $build['#cache']['contexts'][] = 'background_image';
    $build['#cache']['contexts'][] = 'background_image.settings.blur';
    $build['#cache']['contexts'][] = 'background_image.settings.full_viewport';
    $context = [
      'background_image' => $background_image,
      'entity' => $this
        ->getEntity($background_image, $manager),
    ];
    $this
      ->moduleHandler()
      ->alter('background_image_build', $build, $context);
    \Drupal::service('theme.manager')
      ->alter('background_image_build', $build, $context);
    return $build;
  }

  /**
   * Builds the text render array.
   *
   * @param \Drupal\background_image\BackgroundImageInterface $background_image
   *   The background image being processed.
   * @param \Drupal\background_image\BackgroundImageManagerInterface $manager
   *   The Background Image Manager service.
   *
   * @return array
   *   The built render array element.
   */
  public function buildText(BackgroundImageInterface $background_image, BackgroundImageManagerInterface $manager) {
    $text = trim($background_image
      ->getSetting('text.value', ''));

    // Immediately return if there is no text.
    if (!$text) {
      $build['#access'] = FALSE;
      $build['#cache']['contexts'][] = 'background_image.settings.text';
      return $build;
    }
    $base_class = $manager
      ->getBaseClass();
    $build = [
      '#type' => 'processed_text',
      '#theme_wrappers' => [
        'container__background_image__text',
      ],
      '#attributes' => [
        'class' => [
          "{$base_class}-text",
        ],
      ],
      '#format' => $background_image
        ->getSetting('text.format', 'full_html'),
      '#langcode' => $background_image
        ->language()
        ->getId(),
      '#text' => $text,
    ];
    $build['#cache']['contexts'][] = 'background_image.settings.text';

    // Add entity to token data.
    $token_data = [
      'background_image' => $background_image,
    ];
    $entity = $this
      ->getEntity($background_image, $manager);
    if ($entity) {
      $token_data[$entity
        ->getEntityTypeId()] = $entity instanceof ViewEntityInterface ? $entity
        ->getExecutable() : $entity;
    }

    // Allow extensions a chance to alter the text before it's tokenized.
    $context = [
      'background_image' => $background_image,
      'entity' => $entity,
      'token_data' => $token_data,
      'token_options' => [
        'clear' => TRUE,
        'langcode' => &$build['#langcode'],
      ],
    ];
    $this
      ->moduleHandler()
      ->alter('background_image_text_build', $build, $context);
    \Drupal::service('theme.manager')
      ->alter('background_image_text_build', $build, $context);

    // Perform token replacements.
    $build['#text'] = \Drupal::token()
      ->replace($build['#text'], $context['token_data'], $context['token_options']);

    // Allow extensions a chance to alter the text after it's tokenized.
    $this
      ->moduleHandler()
      ->alter('background_image_text_after_build', $build, $context);
    \Drupal::service('theme.manager')
      ->alter('background_image_text_after_build', $build, $context);
    return $build;
  }

  /**
   * Determines the property entity to associate with this background image.
   *
   * @param \Drupal\background_image\BackgroundImageInterface $background_image
   *   The background image being processed.
   * @param \Drupal\background_image\BackgroundImageManagerInterface $manager
   *   The Background Image Manager service.
   *
   * @todo This should really be moved to the BackgroundImage entity class.
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   */
  protected function getEntity(BackgroundImageInterface $background_image, BackgroundImageManagerInterface $manager) {
    $type = $background_image
      ->getType();

    // Determine the proper "entity" to use.
    if ($entity = $background_image
      ->getTargetEntity()) {

      // Intentionally left empty, this is a specific associated entity.
    }
    else {
      if (($view = $background_image
        ->getTargetView()) && $view
        ->status()) {
        $entity = $view;
      }
      else {
        if ($type === BackgroundImageInterface::TYPE_ENTITY_BUNDLE && (list($entity_type, $bundle) = $background_image
          ->getTarget(TRUE)) && ($entity = $manager
          ->getEntityFromCurrentRoute($entity_type, $bundle))) {

          // Intentionally left empty. Entity is assigned in the if block to ensure
          // that if it doesn't find one, to move on to the next if statement.
        }
        else {
          if ($type === BackgroundImageInterface::TYPE_GLOBAL || $type === BackgroundImageInterface::TYPE_PATH || $type === BackgroundImageInterface::TYPE_ROUTE) {
            $entity = $manager
              ->getEntityFromCurrentRoute();
          }
        }
      }
    }
    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $background_image, $view_mode = 'full', $langcode = NULL) {

    /** @type \Drupal\background_image\BackgroundImageInterface $background_image */
    $build = parent::view($background_image, $view_mode, $langcode);
    $build['#langcode'] = $langcode;
    $build['#access'] = $background_image
      ->access('view', NULL, TRUE);

    // Attach, at the minimum, the baseClass drupal setting.
    $build['#attached']['drupalSettings']['backgroundImage']['baseClass'] = BackgroundImageManager::service()
      ->getBaseClass();

    // Add user permissions context.
    $build['#cache']['contexts'][] = 'user.permissions';
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BackgroundImageViewBuilder::build public function Builds an entity's view; augments entity defaults. Overrides EntityViewBuilder::build
BackgroundImageViewBuilder::buildImage public function Builds the image render array.
BackgroundImageViewBuilder::buildText public function Builds the text render array.
BackgroundImageViewBuilder::getEntity protected function Determines the property entity to associate with this background image.
BackgroundImageViewBuilder::view public function Builds the render array for the provided entity. Overrides EntityViewBuilder::view
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
DeprecatedServicePropertyTrait::__get public function Allows to access deprecated/removed properties.
EntityHandlerBase::$moduleHandler protected property The module handler to invoke hooks on. 2
EntityHandlerBase::moduleHandler protected function Gets the module handler. 2
EntityHandlerBase::setModuleHandler public function Sets the module handler for this handler.
EntityViewBuilder::$cacheBin protected property The cache bin used to store the render cache.
EntityViewBuilder::$deprecatedProperties protected property
EntityViewBuilder::$entityDisplayRepository protected property The entity display repository.
EntityViewBuilder::$entityRepository protected property The entity repository service.
EntityViewBuilder::$entityType protected property Information about the entity type.
EntityViewBuilder::$entityTypeId protected property The type of entities for which this view builder is instantiated.
EntityViewBuilder::$languageManager protected property The language manager.
EntityViewBuilder::$singleFieldDisplays protected property The EntityViewDisplay objects created for individual field rendering.
EntityViewBuilder::$themeRegistry protected property The theme registry.
EntityViewBuilder::addContextualLinks protected function Add contextual links.
EntityViewBuilder::alterBuild protected function Specific per-entity building. 1
EntityViewBuilder::buildComponents public function Builds the component fields and properties of a set of entities. Overrides EntityViewBuilderInterface::buildComponents 6
EntityViewBuilder::buildMultiple public function Builds multiple entities' views; augments entity defaults.
EntityViewBuilder::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityHandlerInterface::createInstance 2
EntityViewBuilder::getBuildDefaults protected function Provides entity-specific defaults to the build process. 4
EntityViewBuilder::getCacheTags public function The cache tag associated with this entity view builder. Overrides EntityViewBuilderInterface::getCacheTags
EntityViewBuilder::getSingleFieldDisplay protected function Gets an EntityViewDisplay for rendering an individual field.
EntityViewBuilder::isViewModeCacheable protected function Determines whether the view mode is cacheable.
EntityViewBuilder::resetCache public function Resets the entity render cache. Overrides EntityViewBuilderInterface::resetCache
EntityViewBuilder::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 2
EntityViewBuilder::viewField public function Builds a renderable array for the value of a single field in an entity. Overrides EntityViewBuilderInterface::viewField
EntityViewBuilder::viewFieldItem public function Builds a renderable array for a single field item. Overrides EntityViewBuilderInterface::viewFieldItem
EntityViewBuilder::viewMultiple public function Builds the render array for the provided entities. Overrides EntityViewBuilderInterface::viewMultiple 4
EntityViewBuilder::__construct public function Constructs a new EntityViewBuilder. 2
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.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.