You are here

protected function GatherContentSubProcess::gcUrlToDrupal in GatherContent 8.5

Returns formatted string with replaced urls.

Parameters

string $text: String containing the urls.

Return value

string Formatted string containing the replaced urls.

1 call to GatherContentSubProcess::gcUrlToDrupal()
GatherContentSubProcess::replaceUrls in src/Plugin/migrate/process/GatherContentSubProcess.php
Replaces the GC urls to Drupal entity url.

File

src/Plugin/migrate/process/GatherContentSubProcess.php, line 119

Class

GatherContentSubProcess
Perform custom value transformation.

Namespace

Drupal\gathercontent\Plugin\migrate\process

Code

protected function gcUrlToDrupal(string $text) {
  $collectedUrls = [];
  preg_match_all("/https?:\\/\\/([a-z0-9]+)\\.gathercontent\\.com\\/item\\/(\\d+)/", $text, $collectedUrls);
  if (empty($collectedUrls[0])) {
    return $text;
  }
  if (!is_array($collectedUrls[0])) {
    $collectedUrls[0] = [
      $collectedUrls[0],
    ];
  }
  $gcUrls = array_unique(array_combine($collectedUrls[2], $collectedUrls[0]));
  $query = $this->database
    ->select('gathercontent_entity_mapping')
    ->fields('gathercontent_entity_mapping', [
    'gc_id',
    'entity_id',
    'entity_type',
  ]);
  $query
    ->condition('gc_id', array_unique($collectedUrls[2]), 'IN');
  $results = $query
    ->execute()
    ->fetchAll();
  if (empty($results)) {
    return $text;
  }
  $validGcUrls = [];
  $internalUrls = [];
  foreach ($results as $result) {
    $validGcUrls[] = $gcUrls[$result->gc_id];
    try {
      $entity = $this->entityTypeManager
        ->getStorage($result->entity_type)
        ->load($result->entity_id);
    } catch (InvalidPluginDefinitionException $e) {
    } catch (PluginNotFoundException $e) {
    }
    $entityType = $entity
      ->getEntityTypeId();
    $entityId = $entity
      ->id();
    $internalUrls[] = Url::fromUri("base:/{$entityType}/{$entityId}")
      ->setAbsolute()
      ->toString();
  }
  $text = str_replace($validGcUrls, $internalUrls, $text);
  return $text;
}