dchadwick/web/modules/custom/ufc/src/Controller/RecentFightsController.php

71 lines
2.2 KiB
PHP
Raw Normal View History

2024-04-09 12:08:12 -07:00
<?php
namespace Drupal\ufc\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManager;
2024-04-10 15:00:10 -07:00
use Drupal\Core\Url;
2024-04-09 12:08:12 -07:00
use Drupal\node\Entity\Node;
use Drupal\Core\Cache\CacheableJsonResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RecentFightsController extends ControllerBase {
protected $entityTypeManager;
public function __construct(
EntityTypeManager $entityTypeManager
) {
$this->entityTypeManager = $entityTypeManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
);
}
/**
* Gets recent fights.
*/
public function getRecentFights() {
$query = $this->entityTypeManager->getStorage('node')->getQuery();
$query->accessCheck(TRUE);
2024-04-11 13:10:33 -07:00
$query->condition('type', 'fight')->sort('created', 'DESC')->sort('nid', 'DESC');
$query->range(0, 13);
2024-04-09 12:08:12 -07:00
$nids = $query->execute();
$all_fights = Node::loadMultiple($nids);
$fights = [];
foreach ($all_fights as $fight) {
$f1 = Node::load($fight->field_fighter_one->target_id);
$f2 = Node::load($fight->field_fighter_two->target_id);
$result = Node::load($fight->field_result->target_id);
$alias = \Drupal::service('path_alias.manager')->getAliasByPath("/" . $fight->toUrl()->getInternalPath());
if ($f1 && $f2) {
2024-04-10 15:00:10 -07:00
$f1_uri = $f1->field_player_photo->entity->field_media_image->entity->getFileUri() ?? 'public://player-headshots/headshot-default.jpeg';
$f2_uri = $f2->field_player_photo->entity->field_media_image->entity->getFileUri() ?? 'public://player-headshots/headshot-default.jpeg';
$f1_pic_url = str_replace("public://", "/sites/default/files/", $f1_uri);
$f2_pic_url = str_replace("public://", "sites/default/files/", $f2_uri);
2024-04-09 12:08:12 -07:00
$fights[] = [
'fighter_one' => $f1->getTitle(),
2024-04-10 15:00:10 -07:00
'fighter_one_image' => $f1_pic_url,
2024-04-09 12:08:12 -07:00
'fighter_two' => $f2->getTitle(),
2024-04-10 15:00:10 -07:00
'fighter_two_image' => $f2_pic_url,
2024-04-09 12:08:12 -07:00
'result' => $result->getTitle(),
'url' => $alias
];
}
}
2024-04-10 15:00:10 -07:00
2024-04-09 12:08:12 -07:00
return new CacheableJsonResponse($fights);
}
}