You are here

public static function SchemaMetatagManager::arrayTrim in Schema.org Metatag 8

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

Remove empty values from a nested array.

If the result is an empty array, the nested array is completely empty.

Parameters

mixed $array: The array or object to assess.

Return value

array The original array with empty values removed.

Overrides SchemaMetatagManagerInterface::arrayTrim

3 calls to SchemaMetatagManager::arrayTrim()
SchemaMetatagManager::serialize in src/SchemaMetatagManager.php
Wrapper for serialize to prevent errors.
SchemaMetatagManager::unserialize in src/SchemaMetatagManager.php
Wrapper for unserialize to prevent errors.
SchemaMetatagManagerTest::testArrayTrim in tests/src/Unit/SchemaMetatagManagerTest.php
@covers ::arrayTrim @dataProvider arrayData

File

src/SchemaMetatagManager.php, line 265

Class

SchemaMetatagManager
Class SchemaMetatagManager.

Namespace

Drupal\schema_metatag

Code

public static function arrayTrim($array) {

  // See if this is an array or an object.
  $needs_type = static::isObject($array);
  foreach ($array as $key => &$value) {
    if (empty($value)) {
      unset($array[$key]);
    }
    else {
      if (is_array($value)) {
        $value = static::arrayTrim($value);
        if (empty($value)) {
          unset($array[$key]);
        }
      }
    }
  }

  // If all that's left is the pivot, return empty.
  if ($array == [
    'pivot' => 1,
  ]) {
    return [];
  }

  // If all that's left is @type, return empty.
  if (count($array) == 1 && key($array) == '@type') {
    return [];
  }

  // If this is an object but none of the values is @type or @id, return
  // empty.
  if ($needs_type && is_array($array) && !array_key_exists('@type', $array) && !array_key_exists('@id', $array)) {
    return [];
  }

  // Otherwise return the cleaned up array.
  return (array) $array;
}