You are here

class HtmlLink in Entity Usage 8.3

Same name and namespace in other branches
  1. 8.2 src/Plugin/EntityUsage/Track/HtmlLink.php \Drupal\entity_usage\Plugin\EntityUsage\Track\HtmlLink

Tracks usage of entities referenced from regular HTML Links.

Plugin annotation


@EntityUsageTrack(
  id = "html_link",
  label = @Translation("HTML links"),
  description = @Translation("Tracks relationships created with standard links inside formatted text fields."),
  field_types = {"text", "text_long", "text_with_summary"},
)

Hierarchy

Expanded class hierarchy of HtmlLink

File

src/Plugin/EntityUsage/Track/HtmlLink.php, line 25

Namespace

Drupal\entity_usage\Plugin\EntityUsage\Track
View source
class HtmlLink extends TextFieldEmbedBase {

  /**
   * The Drupal Path Validator service.
   *
   * @var \Drupal\Core\Path\PathValidatorInterface
   */
  protected $pathValidator;

  /**
   * The public file directory.
   *
   * @var string
   */
  protected $publicFileDirectory;

  /**
   * Constructs the HtmlLink plugin.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\entity_usage\EntityUsage $usage_service
   *   The usage tracking service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The EntityTypeManager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The EntityFieldManager service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The EntityRepositoryInterface service.
   * @param \Drupal\Core\Path\PathValidatorInterface $path_validator
   *   The Drupal Path Validator service.
   * @param \Drupal\Core\StreamWrapper\PublicStream $public_stream
   *   The Public Stream service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityUsage $usage_service, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $config_factory, EntityRepositoryInterface $entity_repository, PathValidatorInterface $path_validator, PublicStream $public_stream) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $usage_service, $entity_type_manager, $entity_field_manager, $config_factory, $entity_repository);
    $this->pathValidator = $path_validator;
    $this->publicFileDirectory = $public_stream
      ->getDirectoryPath();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_usage.usage'), $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('config.factory'), $container
      ->get('entity.repository'), $container
      ->get('path.validator'), $container
      ->get('stream_wrapper.public'));
  }

  /**
   * {@inheritdoc}
   */
  public function parseEntitiesFromText($text) {
    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);
    $entities = [];

    // Loop trough all the <a> elements that don't have the LinkIt attributes.
    $xpath_query = "//a[@href != '']";
    foreach ($xpath
      ->query($xpath_query) as $element) {

      /** @var \DOMElement $element */
      try {

        // Get the href value of the <a> element.
        $href = $element
          ->getAttribute('href');

        // Strip off the scheme and host, so we only get the path.
        $site_domains = $this->config
          ->get('site_domains') ?: [];
        foreach ($site_domains as $site_domain) {
          $host_pattern = '{^https?://' . str_replace('.', '\\.', $site_domain) . '/}';
          if (\preg_match($host_pattern, $href)) {
            $href = preg_replace($host_pattern, '/', $href);
            break;
          }
        }
        $target_type = $target_id = NULL;

        // Check if the href links to an entity.
        $url = $this->pathValidator
          ->getUrlIfValidWithoutAccessCheck($href);
        if ($url && $url
          ->isRouted() && preg_match('/^entity\\./', $url
          ->getRouteName())) {

          // Ge the target entity type and ID.
          $route_parameters = $url
            ->getRouteParameters();
          $target_type = array_keys($route_parameters)[0];
          $target_id = $route_parameters[$target_type];
        }
        elseif (\preg_match('{^/?' . $this->publicFileDirectory . '/}', $href)) {

          // Check if we can map the link to a public file.
          $file_uri = preg_replace('{^/?' . $this->publicFileDirectory . '/}', 'public://', urldecode($href));
          $files = $this->entityTypeManager
            ->getStorage('file')
            ->loadByProperties([
            'uri' => $file_uri,
          ]);
          if ($files) {

            // File entity found.
            $target_type = 'file';
            $target_id = array_keys($files)[0];
          }
        }
        if ($target_type && $target_id) {
          $entity = $this->entityTypeManager
            ->getStorage($target_type)
            ->load($target_id);
          if ($entity) {
            if ($element
              ->hasAttribute('data-entity-uuid')) {

              // Normally the Linkit plugin handles when a element has this
              // attribute, but sometimes users may change the HREF manually and
              // leave behind the wrong UUID.
              $data_uuid = $element
                ->getAttribute('data-entity-uuid');

              // If the UUID is the same as found in HREF, then skip it because
              // it's LinkIt's job to register this usage.
              if ($data_uuid == $entity
                ->uuid()) {
                continue;
              }
            }
            $entities[$entity
              ->uuid()] = $target_type;
          }
        }
      } catch (\Exception $e) {

        // Do nothing.
      }
    }
    return $entities;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
EntityUsageTrackBase::$config protected property The Entity Update config.
EntityUsageTrackBase::$entityFieldManager protected property Entity field manager service.
EntityUsageTrackBase::$entityRepository protected property The EntityRepository service.
EntityUsageTrackBase::$entityTypeManager protected property Entity type manager service.
EntityUsageTrackBase::$usageService protected property The usage tracking service.
EntityUsageTrackBase::defaultConfiguration public function
EntityUsageTrackBase::getAllBottomLevelTargets protected function Calculates all bottom-level targets for a given entity.
EntityUsageTrackBase::getApplicableFieldTypes public function Returns the field types this plugin is capable of tracking. Overrides EntityUsageTrackInterface::getApplicableFieldTypes
EntityUsageTrackBase::getDescription public function Returns the tracking method description. Overrides EntityUsageTrackInterface::getDescription
EntityUsageTrackBase::getId public function Returns the tracking method unique id. Overrides EntityUsageTrackInterface::getId
EntityUsageTrackBase::getLabel public function Returns the tracking method label. Overrides EntityUsageTrackInterface::getLabel
EntityUsageTrackBase::getReferencingFields public function Retrieve fields of the given types on an entity. Overrides EntityUsageTrackInterface::getReferencingFields
EntityUsageTrackBase::isApplicable protected function Detects whether this plugin should act on a particular entity.
EntityUsageTrackBase::trackOnEntityCreation public function Track usage updates on the creation of entities. Overrides EntityUsageTrackInterface::trackOnEntityCreation
EntityUsageTrackBase::trackOnEntityUpdate public function Track usage updates on the edition of entities. Overrides EntityUsageTrackInterface::trackOnEntityUpdate
HtmlLink::$pathValidator protected property The Drupal Path Validator service.
HtmlLink::$publicFileDirectory protected property The public file directory.
HtmlLink::create public static function Creates an instance of the plugin. Overrides EntityUsageTrackBase::create
HtmlLink::parseEntitiesFromText public function Parse an HTML snippet looking for embedded entities. Overrides EmbedTrackInterface::parseEntitiesFromText
HtmlLink::__construct public function Constructs the HtmlLink plugin. Overrides EntityUsageTrackBase::__construct
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.
TextFieldEmbedBase::getTargetEntities public function Retrieve the target entity(ies) from a field item value. Overrides EntityUsageTrackInterface::getTargetEntities