LinkFieldUnserializer.php in Acquia Content Hub 8.2
File
src/EventSubscriber/UnserializeContentField/LinkFieldUnserializer.php
View source
<?php
namespace Drupal\acquia_contenthub\EventSubscriber\UnserializeContentField;
use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\UnserializeCdfEntityFieldEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LinkFieldUnserializer implements EventSubscriberInterface {
public static function getSubscribedEvents() {
$events[AcquiaContentHubEvents::UNSERIALIZE_CONTENT_ENTITY_FIELD] = [
'onUnserializeContentField',
10,
];
return $events;
}
public function onUnserializeContentField(UnserializeCdfEntityFieldEvent $event) {
$meta = $event
->getFieldMetadata();
if ($meta['type'] !== 'link') {
return;
}
$field = $event
->getField();
$values = [];
if (empty($field['value'])) {
return;
}
foreach ($field['value'] as $langcode => $fieldValues) {
foreach ($fieldValues as $value) {
if ($value['uri_type'] === 'entity') {
$uuid = $value['uri'];
$uri_entity = $event
->getStack()
->getDependency($uuid)
->getEntity();
$entity_link = "entity:{$uri_entity->getEntityTypeId()}/{$uri_entity->id()}";
$value['uri'] = $entity_link;
}
if ($value['uri_type'] === 'internal') {
$internal_type = array_key_exists('internal_type', $value) ? $value['internal_type'] : '';
if ($internal_type === 'internal_entity') {
$uuid = $value['uri'];
$uri_entity = $event
->getStack()
->getDependency($uuid)
->getEntity();
if ($uri_entity
->getEntityType()
->hasLinkTemplate('canonical') && $uri_entity
->toUrl('canonical')
->isRouted()) {
$internal_link = "internal:/" . $uri_entity
->toUrl('canonical')
->getInternalPath();
}
else {
$internal_link = "internal:/{$uri_entity->getEntityTypeId()}/{$uri_entity->id()}";
}
$value['uri'] = $internal_link;
}
if (!empty($internal_type)) {
unset($value['internal_type']);
}
}
unset($value['uri_type']);
$values[$langcode][$event
->getFieldName()][] = $value;
}
}
$event
->setValue($values);
$event
->stopPropagation();
}
}