You are here

public function WSExampleBlockDecoder::decode in Web Service Data 2.0.x

Same name and namespace in other branches
  1. 8 modules/wsdata_example/src/Plugin/WSDecoder/WSExampleBlockDecoder.php \Drupal\wsdata_example\Plugin\WSDecoder\WSExampleBlockDecoder::decode()

Decode the web service response string into an array.

Overrides WSDecoderBase::decode

File

modules/wsdata_example/src/Plugin/WSDecoder/WSExampleBlockDecoder.php, line 21

Class

WSExampleBlockDecoder
JSON Decoder.

Namespace

Drupal\wsdata_example\Plugin\WSDecoder

Code

public function decode($data) {
  $items = [];
  if (!isset($data) || empty($data)) {
    return;
  }

  // Remove UTF-8 BOM if present, json_decode() does not like it.
  if (substr($data, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) {
    $data = substr($data, 3);
  }
  $data = trim($data);
  $json_data = Json::decode($data);
  foreach ($json_data as $element) {
    $items[] = [
      '#markup' => '<h2>' . $element['title'] . '</h2><p>' . $element['body'] . '</p>',
    ];
  }
  $content = [
    '#theme' => 'item_list',
    '#list_type' => 'ul',
    '#title' => 'My List',
    '#items' => $items,
    '#attributes' => [
      'class' => 'mylist',
    ],
    '#wrapper_attributes' => [
      'class' => 'container',
    ],
  ];
  return \Drupal::service('renderer')
    ->render($content);
}