<?php

namespace Drupal\pagedesigner\Plugin;

use Drupal\Core\Cache\CacheFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Base implementation for entity related elements.
 */
trait HandlerCacheTrait {

  /**
   * The cache factory.
   *
   * @var \Drupal\Core\Cache\CacheFactoryInterface
   */
  protected $cacheFactory = NULL;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->setCacheFactory($container->get('cache_factory'));
    return $instance;
  }

  /**
   * Set the cache factory.
   *
   * @param \Drupal\Core\Cache\CacheFactoryInterface $cache_factory
   *   The cache factory.
   */
  public function setCacheFactory(CacheFactoryInterface $cache_factory) {
    $this->cacheFactory = $cache_factory;
  }

  /**
   * Create a cache id for caching computed patterns.
   *
   * @param string $type
   *   The entity type.
   * @param string $id
   *   The entity id.
   * @param string $langcode
   *   The langcode.
   * @param bool $render_markup
   *   Whether markup is being rendered.
   *
   * @return string
   *   The cache id.
   */
  public function createCid(string $type, string $id, string $langcode, bool $render_markup = FALSE) {
    $cid = 'pagedesigner_cache:' . $type . ':' . $id . ':' . $langcode;
    if ($render_markup) {
      // Append cid if we include markup.
      $cid .= ':markup';
    }
    return $cid;
  }

}
