ExampleController.php in HTTP Client Manager 8
File
modules/http_client_manager_example/src/Controller/ExampleController.php
View source
<?php
namespace Drupal\http_client_manager_example\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\http_client_manager\Entity\HttpConfigRequest;
use Drupal\http_client_manager\HttpClientInterface;
use Drupal\http_client_manager_example\Response\FindPostsResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ExampleController extends ControllerBase {
protected $httpClient;
public function __construct(HttpClientInterface $http_client) {
$this->httpClient = $http_client;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('example_api.http_client'));
}
public function getClient() {
return $this->httpClient;
}
public function findPosts($postId = NULL) {
$client = $this
->getClient();
$response = $client
->findPosts([
'postId' => $postId,
]);
$post_link = TRUE;
if (!empty($postId)) {
$post_link = FALSE;
$response = [
$postId => $response,
];
}
$build = [];
foreach ($response as $id => $post) {
$build[$id] = $this
->buildPostResponse($post, $post_link);
}
return $build;
}
protected function buildPostResponse(FindPostsResponse $post, $post_link) {
$route = 'http_client_manager_example.find_posts';
$link_text = $post_link ? $this
->t('Read more') : $this
->t('Back to list');
$route_params = $post_link ? [
'postId' => $post
->getId(),
] : [];
$output = [
'#type' => 'fieldset',
'#title' => $post
->getId() . ') ' . $post
->getTitle(),
'body' => [
'#markup' => '<p>' . $post
->getBody() . '</p>',
],
'link' => [
'#markup' => Link::createFromRoute($link_text, $route, $route_params)
->toString(),
],
];
return $output;
}
public function createPost() {
if ($request = HttpConfigRequest::load('create_post')) {
$response = '<pre>' . print_r($request
->execute(), TRUE) . '</pre>';
}
else {
$response = $this
->t('Unable to load "create_post" configured request.');
}
return [
'#type' => 'markup',
'#markup' => $response,
];
}
}