dev/endpoints/bundle_AAAAA/src/Controller/CategoryController.php
2023-12-31 00:04:21 +02:00

66 lines
1.6 KiB
PHP

<?php
namespace Drupal\bundle_article\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class CategoryController extends ControllerBase {
private const VOCABULARY = 'AAAAA_category'; // Editable
private const HTTP_BAD_REQUEST = 400;
private const HTTP_OK = 200;
private array $response = [];
private int $statusCode = self::HTTP_OK;
// MAIN
public function getCategories(Request $request, $lang) {
$this->response = [
'code' => $this->statusCode,
'lang' => $lang,
'categories' => $this->buildVocabulary($lang)];
return new JsonResponse($this->response, $this->statusCode);
}
// RESPONSE ARRAY
private function buildVocabulary($lang): array {
$terms = $this->loadTerms($lang);
$terms_response = [];
foreach ($terms as $type) {
$terms_response[] = [
'id' => $type->id(),
'name' => $type->getName()
];
}
return $terms_response;
}
// RESPONSE ARRAY VALUES
private function loadTerms($lang) {
// All terms from the vocabulary
$terms=\Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties([
'vid' => self::VOCABULARY,
]);
// Current language only
$termList=[];
foreach($terms as $term) {
if($term->hasTranslation($lang)){
$tid = $term->id();
$translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $lang);
$termList[$tid] = $translated_term;
}
}
return $termList;
}
}