шаг 3 завершен

This commit is contained in:
Alisa
2026-06-04 00:27:17 +03:00
parent 420e67c9bd
commit 62ce8c4d01
27 changed files with 1565 additions and 42 deletions
+110
View File
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace App\Repositories;
final class CategoryRepository extends BaseRepository
{
/**
* @return array<int, array<string, mixed>>
*/
public function active(): array
{
$statement = $this->pdo()->query(
'SELECT id, parent_id, name, slug, legacy_path, h1, seo_title, seo_description, seo_keywords, image_path, sort_order
FROM categories
WHERE is_active = 1
ORDER BY parent_id IS NOT NULL, sort_order, name'
);
return $statement->fetchAll();
}
/**
* @return array<int, array<string, mixed>>
*/
public function tree(): array
{
$items = $this->active();
$childrenByParent = [];
foreach ($items as $item) {
$parentKey = $item['parent_id'] === null ? 0 : (int) $item['parent_id'];
$childrenByParent[$parentKey][] = $item;
}
return $this->buildTree($childrenByParent, 0);
}
/**
* @param array<int, array<int, array<string, mixed>>> $childrenByParent
* @return array<int, array<string, mixed>>
*/
private function buildTree(array $childrenByParent, int $parentId): array
{
$branch = [];
foreach ($childrenByParent[$parentId] ?? [] as $item) {
$item['children'] = $this->buildTree($childrenByParent, (int) $item['id']);
$branch[] = $item;
}
return $branch;
}
/**
* @return array<string, mixed>|null
*/
public function findBySlug(string $slug): ?array
{
$statement = $this->pdo()->prepare(
'SELECT id, parent_id, name, slug, legacy_path, description, h1, seo_title, seo_description, seo_keywords, image_path
FROM categories
WHERE slug = :slug AND is_active = 1
LIMIT 1'
);
$statement->execute(['slug' => $slug]);
$category = $statement->fetch();
return $category ?: null;
}
/**
* @return array<int, array<string, string>>
*/
public function breadcrumbs(int $categoryId): array
{
$items = [];
$currentId = $categoryId;
while ($currentId > 0) {
$statement = $this->pdo()->prepare(
'SELECT id, parent_id, name, slug
FROM categories
WHERE id = :id
LIMIT 1'
);
$statement->execute(['id' => $currentId]);
$category = $statement->fetch();
if (!$category) {
break;
}
array_unshift($items, [
'title' => $category['name'],
'url' => '/catalog/' . $category['slug'],
]);
$currentId = $category['parent_id'] === null ? 0 : (int) $category['parent_id'];
}
array_unshift($items, [
'title' => 'Главная',
'url' => '/',
]);
return $items;
}
}