95 lines
2.4 KiB
PHP
95 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Models\CategoryModel;
|
|
|
|
class Categories extends BaseController
|
|
{
|
|
private function model(): CategoryModel
|
|
{
|
|
return model(CategoryModel::class);
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
return view('categories/index', [
|
|
'title' => 'Kategorie',
|
|
'categories' => $this->model()->tree(),
|
|
]);
|
|
}
|
|
|
|
public function new()
|
|
{
|
|
return view('categories/form', [
|
|
'title' => 'Nowa kategoria',
|
|
'cat' => null,
|
|
'parents' => $this->model()->tree(),
|
|
]);
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
return $this->persist(null);
|
|
}
|
|
|
|
public function edit($id)
|
|
{
|
|
$cat = $this->model()->find((int) $id);
|
|
if (! $cat) {
|
|
return redirect()->to('/categories')->with('error', 'Nie znaleziono kategorii.');
|
|
}
|
|
|
|
return view('categories/form', [
|
|
'title' => 'Edycja kategorii',
|
|
'cat' => $cat,
|
|
'parents' => $this->model()->tree(),
|
|
]);
|
|
}
|
|
|
|
public function update($id)
|
|
{
|
|
return $this->persist((int) $id);
|
|
}
|
|
|
|
public function delete($id)
|
|
{
|
|
$id = (int) $id;
|
|
if ($this->model()->usedByOperations($id)) {
|
|
return redirect()->to('/categories')
|
|
->with('error', 'Nie można usunąć kategorii używanej przez operacje. Najpierw przenieś lub usuń te operacje.');
|
|
}
|
|
$this->model()->delete($id);
|
|
|
|
return redirect()->to('/categories')->with('success', 'Kategoria usunięta.');
|
|
}
|
|
|
|
private function persist(?int $id)
|
|
{
|
|
$data = [
|
|
'name' => trim((string) $this->request->getPost('name')),
|
|
'type' => (string) $this->request->getPost('type'),
|
|
'parent_id' => $this->request->getPost('parent_id') ?: null,
|
|
];
|
|
|
|
// Kategoria nie moze byc wlasnym rodzicem
|
|
if ($id !== null && (int) $data['parent_id'] === $id) {
|
|
$data['parent_id'] = null;
|
|
}
|
|
|
|
$model = $this->model();
|
|
if ($id !== null) {
|
|
$ok = $model->update($id, $data);
|
|
} else {
|
|
$ok = $model->insert($data);
|
|
}
|
|
|
|
if ($ok === false) {
|
|
return redirect()->back()->withInput()
|
|
->with('error', implode(' ', $model->errors()));
|
|
}
|
|
|
|
return redirect()->to('/categories')->with('success', 'Zapisano kategorię.');
|
|
}
|
|
}
|