You are here

public function UuidLinkEnhancer::prepareForInput in JSON:API Extras 8

Apply the initial transformations to the input value of a single field.

Parameters

mixed $value: The value to be processed so it can be used as an input.

Return value

mixed The value after being post precessed.

Overrides ResourceFieldEnhancerInterface::prepareForInput

File

src/Plugin/jsonapi/FieldEnhancer/UuidLinkEnhancer.php, line 79

Class

UuidLinkEnhancer
Use UUID for internal link field value.

Namespace

Drupal\jsonapi_extras\Plugin\jsonapi\FieldEnhancer

Code

public function prepareForInput($value) {
  if (isset($value['uri'])) {

    // Check if it is a link to an entity.
    preg_match("/entity:(.*)\\/(.*)\\/(.*)/", $value['uri'], $parsed_uri);
    if (!empty($parsed_uri)) {
      $entity_type = $parsed_uri[1];
      $entity_uuid = $parsed_uri[3];
      $entities = $this->entityTypeManager
        ->getStorage($entity_type)
        ->loadByProperties([
        'uuid' => $entity_uuid,
      ]);
      if (!empty($entities)) {
        $entity = array_shift($entities);
        $value['uri'] = 'entity:' . $entity_type . '/' . $entity
          ->id();
      }
      else {

        // If the entity has not been imported yet we unset the field value.
        $value = [];
      }
    }
  }
  return $value;
}