Commit e39397bc authored by Damien McKenna's avatar Damien McKenna Committed by Damien McKenna
Browse files

Issue #3350298 by DamienMcKenna: Backport metatag_data_decode() from v2.

parent b680e95d
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -32,6 +32,7 @@ Metatag 8.x-1.x-dev, 2022-xx-xx
#3335688 by idebr, DamienMcKenna: Document meta name="referrer" relationship
  with Referrer-policy HTTP header.
#3132062 by DamienMcKenna: Updated fixtures with some documentation and todo's.
#3350298 by DamienMcKenna: Backport metatag_data_decode() from v2.


Metatag 8.x-1.22, 2022-09-29
+35 −0
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@

use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Plugin\Factory\DefaultFactory;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
@@ -1007,3 +1008,37 @@ function _metatag_is_migration_plugin_supported(array $definition) {
  // Metatag migration will be automatically handled.
  return TRUE;
}

/**
 * Decode the different versions of encoded values supported by Metatag.
 *
 * Metatag v1 stored data in serialized arrays. Metatag v2 stores data in
 * JSON-encoded strings.
 *
 * @param string $string
 *   The string to decode.
 *
 * @return array
 *   A Metatag values array.
 */
function metatag_data_decode($string): array {
  $data = [];

  // Serialized arrays from Metatag v1.
  if (substr($string, 0, 2) === 'a:') {
    $data = @unserialize($string, ['allowed_classes' => FALSE]);
  }

  // Encoded JSON from Metatag v2.
  elseif (substr($string, 0, 2) === '{"') {
    // @todo Handle non-array responses.
    $data = Json::decode($string);
  }

  // This is expected to be an array, so if it isn't then convert it to one.
  if (!is_array($data)) {
    $data = [];
  }

  return $data;
}