function LinksetController::processCustomLinkAttributes

Same name and namespace in other branches
  1. 11.x core/modules/system/src/Controller/LinksetController.php \Drupal\system\Controller\LinksetController::processCustomLinkAttributes()

Process custom link parameters.

Since the values for attributes are dynamic and we can't guarantee that they adhere to the linkset specification, we do some custom processing as follows, 1. Transform all of them into an array if they are not already an array. 2. Transform all non-string values into strings (e.g. ["42"] instead of [42]) 3. Ignore (for now) any keys that are already specified. Namely: hreflang, media, type, title, and title*. 4. Ensure that custom names do not contain an asterisk and ignore them if they do. 5. These attributes require special handling. For instance, these parameters must be strings instead of an array of strings.

NOTE: Values which are not object/array are cast to string.

Parameters

array $link: Link structure.

array $attributes: Attributes available for the link.

1 call to LinksetController::processCustomLinkAttributes()
LinksetController::toLinkTargetObjects in core/modules/system/src/Controller/LinksetController.php
Encode a menu tree as link items and capture any cacheability metadata.

File

core/modules/system/src/Controller/LinksetController.php, line 220

Class

LinksetController
Linkset controller.

Namespace

Drupal\system\Controller

Code

private function processCustomLinkAttributes(array &$link, array $attributes = []) {
    $attribute_keys_to_ignore = [
        'hreflang',
        'media',
        'type',
        'title',
        'title*',
    ];
    foreach ($attributes as $key => $value) {
        if (in_array($key, $attribute_keys_to_ignore, TRUE)) {
            continue;
        }
        // Skip the attribute key if it has an asterisk (*).
        if (str_contains($key, '*')) {
            continue;
        }
        // Skip the value if it is an object.
        if (is_object($value)) {
            continue;
        }
        // See https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-linkset-03#section-4.2.4.3
        // Values for custom attributes must follow these rules,
        // - Values MUST be array.
        // - Each item in the array MUST be a string.
        if (is_array($value)) {
            $link[$key] = [];
            foreach ($value as $val) {
                if (is_object($val) || is_array($val)) {
                    continue;
                }
                $link[$key][] = (string) $val;
            }
        }
        else {
            $link[$key] = [
                (string) $value,
            ];
        }
    }
}

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