You are here

public static function SchemaMetatagManager::pivot in Schema.org Metatag 8.2

Same name and namespace in other branches
  1. 8 src/SchemaMetatagManager.php \Drupal\schema_metatag\SchemaMetatagManager::pivot()

Pivot multiple value results.

Complex serialized value that might contain multiple values. In this case we have to pivot the results.

Parameters

mixed $content: The value to pivot.

Return value

array The pivoted array.

Overrides SchemaMetatagManagerInterface::pivot

1 call to SchemaMetatagManager::pivot()
SchemaMetatagManagerTest::testPivot in tests/src/Unit/SchemaMetatagManagerTest.php
@covers ::pivot @dataProvider pivotData

File

src/SchemaMetatagManager.php, line 108

Class

SchemaMetatagManager
The SchemaMetatag Manager.

Namespace

Drupal\schema_metatag

Code

public static function pivot($content) {
  if (!is_array($content) || empty($content)) {
    return $content;
  }

  // Figure out the maximum number of items to include in the pivot.
  // Nested associative arrays should be excluded, only count numeric arrays.
  $count = max(array_map([
    __CLASS__,
    'countNumericKeys',
  ], $content));
  $pivoted = [];
  $exploded = [];
  for ($i = 0; $i < $count; $i++) {
    foreach ($content as $key => $item) {

      // If a lower array is pivoted, pivot that first.
      if (is_array($item) && array_key_exists('pivot', $item)) {
        unset($item['pivot']);
        $item = self::pivot($item);
      }

      // Some properties, like @type, may need to repeat the first item,
      // others may have too few values to fill out the array.
      // Make sure all properties have the right number of values.
      if (is_string($item) || !is_string($item) && self::countNumericKeys($item) <= $count) {
        $exploded[$key] = [];
        $prev = '';
        for ($x = 0; $x < $count; $x++) {
          if (!is_string($item) && self::countNumericKeys($item) > $x) {
            $exploded[$key][$x] = $item[$x];
            $prev = $item[$x];
          }
          elseif (!is_string($item) && self::countNumericKeys($item) > 0) {
            $exploded[$key][$x] = $prev;
          }
          else {
            $exploded[$key][$x] = $item;
          }
        }
        $pivoted[$i][$key] = $exploded[$key][$i];
      }
      else {
        $pivoted[$i][$key] = $item;
      }
    }
  }
  return $pivoted;
}