feat: add categories/list API endpoint

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 18:51:26 +01:00
parent 6434933dfb
commit 2461087d9b
2 changed files with 88 additions and 0 deletions

View File

@@ -104,6 +104,10 @@ class ApiRouter
$producerRepo = new \Domain\Producer\ProducerRepository($db);
return new Controllers\DictionariesApiController($statusRepo, $transportRepo, $paymentRepo, $attrRepo, $producerRepo);
},
'categories' => function () use ($db) {
$categoryRepo = new \Domain\Category\CategoryRepository($db);
return new Controllers\CategoriesApiController($categoryRepo);
},
];
}

View File

@@ -0,0 +1,84 @@
<?php
namespace api\Controllers;
use api\ApiRouter;
use Domain\Category\CategoryRepository;
class CategoriesApiController
{
private $categoryRepo;
public function __construct(CategoryRepository $categoryRepo)
{
$this->categoryRepo = $categoryRepo;
}
public function list(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$db = $GLOBALS['mdb'] ?? null;
if (!$db) {
ApiRouter::sendError('INTERNAL_ERROR', 'Database not available', 500);
return;
}
// Pobierz domyślny język sklepu
$defaultLang = $db->get('pp_langs', 'id', ['start' => 1]);
if (!$defaultLang) {
$defaultLang = 'pl';
}
$defaultLang = (string)$defaultLang;
// Pobierz wszystkie aktywne kategorie (płaska lista)
$rows = $db->select(
'pp_shop_categories',
['id', 'parent_id'],
[
'status' => 1,
'ORDER' => ['o' => 'ASC'],
]
);
if (!is_array($rows)) {
ApiRouter::sendSuccess(['categories' => []]);
return;
}
$categories = [];
foreach ($rows as $row) {
$categoryId = (int)($row['id'] ?? 0);
if ($categoryId <= 0) {
continue;
}
$title = $db->get('pp_shop_categories_langs', 'title', [
'AND' => [
'category_id' => $categoryId,
'lang_id' => $defaultLang,
],
]);
// Fallback: jeśli brak tłumaczenia w domyślnym języku, weź pierwsze dostępne
if (!$title) {
$title = $db->get('pp_shop_categories_langs', 'title', [
'category_id' => $categoryId,
'title[!]' => '',
'LIMIT' => 1,
]);
}
$parentId = $row['parent_id'] !== null ? (int)$row['parent_id'] : null;
$categories[] = [
'id' => $categoryId,
'parent_id' => $parentId,
'title' => (string)($title ?? 'Kategoria #' . $categoryId),
];
}
ApiRouter::sendSuccess(['categories' => $categories]);
}
}