Created
July 14, 2018 13:35
Fetch a random node by type and return it as a JSON response.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types = 1); | |
namespace Drupal\harlib_surprise_me\Controller; | |
use Drupal\Core\Controller\ControllerBase; | |
use Drupal\node\Entity\Node; | |
use Symfony\Component\HttpFoundation\JsonResponse; | |
/** | |
* Class SurpriseMeController. | |
*/ | |
class SurpriseMeController extends ControllerBase { | |
/** | |
* Return a random collection node as a JSON object. | |
* | |
* @return \Symfony\Component\HttpFoundation\JsonResponse | |
* The node information. | |
* | |
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException | |
* @throws \Drupal\Core\Entity\EntityMalformedException | |
*/ | |
public function surprise() : JsonResponse { | |
$nid = $this->getRandomCollection(); | |
$node = $this->entityTypeManager()->getStorage('node')->load($nid); | |
$node = [ | |
'id' => $node->id(), | |
'title' => $node->getTitle(), | |
'url' => $node->toUrl()->toString(), | |
'card_type' => $node->get('field_directory_view')->value | |
]; | |
$response = new JsonResponse($node); | |
$response->setMaxAge(30); | |
$response->setSharedMaxAge(30); | |
$response->setPublic(); | |
return $response; | |
} | |
/** | |
* Query for collections and return a random one. | |
* | |
* @return int | |
* The random node id. | |
* | |
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException | |
*/ | |
protected function getRandomCollection() { | |
$query = $this->entityTypeManager()->getStorage('node')->getQuery(); | |
$query->condition('type', 'collection'); | |
$query->condition('status', Node::PUBLISHED); | |
$query->condition('field_show_in_listing', TRUE); | |
$results = $query->execute(); | |
$results = array_values($results); | |
$key = array_rand($results); | |
return $results[$key]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment