шаг 4 завершен
This commit is contained in:
@@ -21,6 +21,21 @@ final class CategoryRepository extends BaseRepository
|
||||
return $statement->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function flatActive(): array
|
||||
{
|
||||
$statement = $this->pdo()->query(
|
||||
'SELECT id, parent_id, name, slug, 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>>
|
||||
*/
|
||||
@@ -107,4 +122,63 @@ final class CategoryRepository extends BaseRepository
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function descendantIds(int $categoryId): array
|
||||
{
|
||||
$items = $this->flatActive();
|
||||
$childrenByParent = [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
$parentId = $item['parent_id'] === null ? 0 : (int) $item['parent_id'];
|
||||
$childrenByParent[$parentId][] = (int) $item['id'];
|
||||
}
|
||||
|
||||
$ids = [$categoryId];
|
||||
$queue = [$categoryId];
|
||||
|
||||
while ($queue !== []) {
|
||||
$currentId = array_shift($queue);
|
||||
|
||||
foreach ($childrenByParent[$currentId] ?? [] as $childId) {
|
||||
$ids[] = $childId;
|
||||
$queue[] = $childId;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function create(array $data): int
|
||||
{
|
||||
if (($data['name'] ?? '') === '' || ($data['slug'] ?? '') === '') {
|
||||
throw new \InvalidArgumentException('Название и slug обязательны.');
|
||||
}
|
||||
|
||||
$statement = $this->pdo()->prepare(
|
||||
'INSERT INTO categories
|
||||
(parent_id, name, slug, h1, seo_title, seo_description, seo_keywords, sort_order, is_active)
|
||||
VALUES
|
||||
(:parent_id, :name, :slug, :h1, :seo_title, :seo_description, :seo_keywords, :sort_order, :is_active)'
|
||||
);
|
||||
|
||||
$statement->execute([
|
||||
'parent_id' => $data['parent_id'],
|
||||
'name' => $data['name'],
|
||||
'slug' => $data['slug'],
|
||||
'h1' => $data['h1'] ?: null,
|
||||
'seo_title' => $data['seo_title'] ?: null,
|
||||
'seo_description' => $data['seo_description'] ?: null,
|
||||
'seo_keywords' => $data['seo_keywords'] ?: null,
|
||||
'sort_order' => $data['sort_order'] ?? 100,
|
||||
'is_active' => $data['is_active'] ?? 1,
|
||||
]);
|
||||
|
||||
return (int) $this->pdo()->lastInsertId();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user