You are here

public function ResourceFieldEntityReference::preprocess in RESTful 7.2

Massage the value to set according to the format expected by the wrapper.

Parameters

mixed $value: The value passed in the request.

Return value

mixed The value to set using the wrapped property.

Overrides ResourceFieldEntity::preprocess

File

src/Plugin/resource/Field/ResourceFieldEntityReference.php, line 55
Contains \Drupal\restful\Plugin\resource\Field\ResourceFieldEntityReference.

Class

ResourceFieldEntityReference
Class ResourceFieldEntityReference.

Namespace

Drupal\restful\Plugin\resource\Field

Code

public function preprocess($value) {
  if (!$value) {

    // If value is empty, return NULL, so no new entity will be created.
    return NULL;
  }
  $cardinality = $this
    ->getCardinality();
  if ($cardinality != 1 && !is_array($value)) {

    // If the field is entity reference type and its cardinality larger than
    // 1 set value to an array.
    $value = explode(',', $value);
  }
  if ($cardinality != 1 && ResourceFieldBase::isArrayNumeric($value)) {

    // Set the cardinality to 1 to process each value as a single value item.
    $this
      ->setCardinality(1);

    // For multiple value items, pre-process them separately.
    $values = array();
    foreach ($value as $item) {
      $values[] = $this
        ->preprocess($item);
    }
    $this
      ->setCardinality($cardinality);
    return $values;
  }

  // If the provided value is the ID to the referenced entity, then do not do
  // a sub-request.
  if (!is_array($value) || empty($value['body'])) {

    // Allow to pass an array with the ID instead of the ID directly.
    return !empty($value['id']) && array_keys($value) == array(
      'id',
    ) ? $value['id'] : $value;
  }

  /* @var ResourceFieldCollectionInterface $merged_value */
  $merged_value = $this
    ->mergeEntityFromReference($value);
  return $merged_value
    ->getInterpreter()
    ->getWrapper()
    ->getIdentifier();
}