You are here

public function LinkExtractorService::extractFromField in Link checker 8

Extracts links from field.

Parameters

\Drupal\Core\Field\FieldItemListInterface $fieldItemList: The field from which to extract.

Return value

\Drupal\linkchecker\LinkCheckerLinkInterface[] Array of extracted links.

2 calls to LinkExtractorService::extractFromField()
LinkExtractorService::extractFromEntity in src/LinkExtractorService.php
Extracts links from entity fields.
LinkExtractorService::isLinkExists in src/LinkExtractorService.php
Checks if link was not removed from content.

File

src/LinkExtractorService.php, line 119

Class

LinkExtractorService
Class LinkExtractor.

Namespace

Drupal\linkchecker

Code

public function extractFromField(FieldItemListInterface $fieldItemList) {
  $urls = [];
  $entity = $fieldItemList
    ->getEntity();
  $entityBundle = $fieldItemList
    ->getEntity()
    ->bundle();
  $fieldConfig = $fieldItemList
    ->getFieldDefinition()
    ->getConfig($entityBundle);
  $scan = $fieldConfig
    ->getThirdPartySetting('linkchecker', 'scan', FALSE);
  if ($scan) {
    try {
      $baseContentUrl = $entity
        ->toUrl()
        ->setAbsolute()
        ->toString();
    } catch (\Exception $e) {
      $baseContentUrl = NULL;
    }
    $extractorName = $fieldConfig
      ->getThirdPartySetting('linkchecker', 'extractor', NULL);

    /** @var \Drupal\linkchecker\Plugin\LinkExtractorInterface $extractor */
    $extractor = $this->extractorManager
      ->createInstance($extractorName);
    $urls = $extractor
      ->extract($fieldItemList
      ->getValue());

    // Remove empty values.
    $urls = array_filter($urls);

    // Remove duplicate urls.
    $urls = array_unique($urls);
    $urls = $this
      ->getLinks($urls, $baseContentUrl);
  }
  $linkCheckerLinks = [];
  foreach ($urls as $link) {
    $linkCheckerLinks[$this->pos] = LinkCheckerLink::create([
      'url' => $link,
      'entity_id' => [
        'target_id' => $entity
          ->id(),
        'target_type' => $entity
          ->getEntityTypeId(),
      ],
      'entity_field' => $fieldItemList
        ->getFieldDefinition()
        ->getName(),
      'entity_langcode' => $fieldItemList
        ->getLangcode(),
    ]);
    $this->pos++;
  }
  return $linkCheckerLinks;
}