69 lines
2.2 KiB
PHP
69 lines
2.2 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../../db/config.php';
|
|
|
|
class CategoryController {
|
|
|
|
public function index() {
|
|
$pdo = db();
|
|
$stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
|
|
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
public function store($name) {
|
|
$slug = $this->slugify($name);
|
|
$pdo = db();
|
|
try {
|
|
$stmt = $pdo->prepare("INSERT INTO categories (name, slug) VALUES (?, ?)");
|
|
$stmt->execute([$name, $slug]);
|
|
return ['success' => true];
|
|
} catch (PDOException $e) {
|
|
if ($e->errorInfo[1] == 1062) { // Duplicate entry
|
|
return ['success' => false, 'message' => 'Uma categoria com este nome ou slug já existe.'];
|
|
}
|
|
return ['success' => false, 'message' => 'Erro ao criar categoria.'];
|
|
}
|
|
}
|
|
|
|
public function show($id) {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
return $stmt->fetch(PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
public function update($id, $name) {
|
|
$slug = $this->slugify($name);
|
|
$pdo = db();
|
|
try {
|
|
$stmt = $pdo->prepare("UPDATE categories SET name = ?, slug = ? WHERE id = ?");
|
|
$stmt->execute([$name, $slug, $id]);
|
|
return ['success' => true];
|
|
} catch (PDOException $e) {
|
|
if ($e->errorInfo[1] == 1062) {
|
|
return ['success' => false, 'message' => 'Uma categoria com este nome ou slug já existe.'];
|
|
}
|
|
return ['success' => false, 'message' => 'Erro ao atualizar categoria.'];
|
|
}
|
|
}
|
|
|
|
public function destroy($id) {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
return ['success' => true];
|
|
}
|
|
|
|
private function slugify($text) {
|
|
$text = preg_replace('~[\pL\d]+~u', '-', $text);
|
|
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
|
|
$text = preg_replace('~[^\w]+~u', '-', $text);
|
|
$text = trim($text, '-');
|
|
$text = preg_replace('~-~', '-', $text);
|
|
$text = strtolower($text);
|
|
if (empty($text)) {
|
|
return 'n-a';
|
|
}
|
|
return $text;
|
|
}
|
|
}
|