You are here

abstract class BaseContext in Acquia Lift Connector 8.4

Same name and namespace in other branches
  1. 8.3 src/Service/Context/BaseContext.php \Drupal\acquia_lift\Service\Context\BaseContext

Hierarchy

Expanded class hierarchy of BaseContext

File

src/Service/Context/BaseContext.php, line 5

Namespace

Drupal\acquia_lift\Service\Context
View source
abstract class BaseContext implements ContextInterface {

  /**
   * HTML head contexts.
   *
   * @var array
   */
  protected $htmlHeadContexts = [];

  /**
   * Cache contexts.
   *
   * @var array
   */
  protected $cacheContexts = [];

  /**
   * Get the render array for a single meta tag.
   *
   * @param string $name
   *   The name for the meta tag
   * @param string $content
   *   The content for the meta tag
   * @return array
   *   The render array
   */
  protected function getMetaTagRenderArray($name, $content) {
    return [
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => [
        'itemprop' => 'acquia_lift:' . $name,
        'content' => $content,
      ],
    ];
  }

  /**
   * Populate page's HTML head.
   *
   * @param &$html_head
   *   The page's HTML head that is to be populated.
   */
  protected function populateHtmlHead(&$html_head) {

    // Attach Lift's metatags.
    foreach ($this->htmlHeadContexts as $name => $context) {
      $renderArray = $this
        ->getMetaTagRenderArray($name, $context);

      // To generate meta tags within HTML head, Drupal requires this precise
      // format of render array.
      $html_head[] = [
        $renderArray,
        $name,
      ];
    }
  }

  /**
   * Populate page's cache context.
   *
   * @param &$page
   *   The page that is to be populated.
   */
  protected function populateCache(&$page) {

    // Set cache contexts.
    foreach ($this->cacheContexts as $context) {
      $page['#cache']['contexts'][] = $context;
    }

    // Guard from a possible case that cache contexts contain duplicate items.
    if (isset($page['#cache']['contexts'])) {
      $page['#cache']['contexts'] = array_unique($page['#cache']['contexts']);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function populate(&$page) {
    $this
      ->populateHtmlHead($page['#attached']['html_head']);
    $this
      ->populateCache($page);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BaseContext::$cacheContexts protected property Cache contexts.
BaseContext::$htmlHeadContexts protected property HTML head contexts. 1
BaseContext::getMetaTagRenderArray protected function Get the render array for a single meta tag.
BaseContext::populate public function Populate page by context. Overrides ContextInterface::populate
BaseContext::populateCache protected function Populate page's cache context.
BaseContext::populateHtmlHead protected function Populate page's HTML head. 1