function MetaEventSubscriber::addResourceObjectMeta

Parameters

\Drupal\jsonapi\Events\CollectResourceObjectMetaEvent $event: Event to be processed.

Return value

void

File

core/modules/jsonapi/tests/modules/jsonapi_test_meta_events/src/EventSubscriber/MetaEventSubscriber.php, line 35

Class

MetaEventSubscriber
Event subscriber which tests adding metadata to ResourceObjects and relationships.

Namespace

Drupal\jsonapi_test_meta_events\EventSubscriber

Code

public function addResourceObjectMeta(CollectResourceObjectMetaEvent $event) : void {
    $config = \Drupal::state()->get('jsonapi_test_meta_events.object_meta', [
        'enabled_type' => FALSE,
        'enabled_id' => FALSE,
        'fields' => FALSE,
        'user_is_admin_context' => FALSE,
    ]);
    // Only continue if the recourse type is enabled.
    if ($config['enabled_type'] === FALSE || $config['enabled_type'] !== $event->getResourceObject()
        ->getTypeName()) {
        return;
    }
    // Only apply on the referenced ID of the resource.
    if ($config['enabled_id'] !== FALSE && $config['enabled_id'] !== $event->getResourceObject()
        ->getId()) {
        return;
    }
    if ($config['fields'] === FALSE) {
        return;
    }
    if ($config['user_is_admin_context']) {
        $event->addCacheContexts([
            'user.roles',
        ]);
        $event->setMetaValue('resource_meta_user_has_admin_role', $this->currentUserHasAdminRole());
        $event->setMetaValue('resource_meta_user_id', \Drupal::currentUser()->id());
    }
    // Add the metadata for each field. The field configuration must be an array
    // of field values keyed by the field name.
    foreach ($config['fields'] as $field_name) {
        $event->setMetaValue('resource_meta_' . $field_name, $event->getResourceObject()
            ->getField($field_name)->value);
    }
    $event->addCacheTags([
        'jsonapi_test_meta_events.object_meta',
    ]);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.