<?php

namespace Drupal\local_task\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;

class SwapiLocalTask extends ControllerBase {

  public function exampleTabContent($node) {
    $nid = $node;
    $api = \Drupal::service('swapi.service_swapi');
    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->load($nid);
    $bundle = $node->bundle();
    $swapi_id = $node->get('field_swapi_id')->getValue();
    $url = 'https://swapi.dev/api/' . $bundle . '/' . $swapi_id[0]['value'];
    $result = $api->setUrl($url)->getResponse();

    foreach ($result as $key => $value) {
      if (is_array($value)) {
        $build = $build . "\"$key\"" . ": [<br>";
        foreach ($value as $value2) {
          $build = $build . " \"$value2\"" . ",<br>";
        }
        $build = $build . "],<br>";
      } else {
        $build = $build . "\"$key\": \"$value\",<br>";
      }
    }
    $build = substr($build,0,-5);
    return ['#markup' => $build];
  }
  public function access(AccountInterface $account, $node) {
    $nid = $node;
    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->load($nid);
    $bundle = $node->bundle();
    return AccessResult::allowedIfHasPermission($account, "edit any $bundle content");
  }
}
