Files
proton/app/Controllers/Web/NotesController.php
T

299 lines
11 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controllers\Web;
use App\Models\Note;
use Rsgrinko\Proton\Access\Scope;
use Rsgrinko\Proton\Access\Viewer;
use Rsgrinko\Proton\Database\Model\Query;
use Rsgrinko\Proton\Events\Events;
use Rsgrinko\Proton\Files\Storage;
use Rsgrinko\Proton\Http\Controller;
use Rsgrinko\Proton\Http\Request;
use Rsgrinko\Proton\Http\Response;
use Rsgrinko\Proton\Support\Audit;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\Filter;
use Rsgrinko\Proton\Support\Filters;
use Rsgrinko\Proton\Support\Import;
use Rsgrinko\Proton\Support\ProtonException;
use Rsgrinko\Proton\View\View;
/**
* Заметки — демонстрационный раздел: список с поиском и страницами, карточка,
* форма, загрузка файла, мягкое удаление.
*
* Здесь же видно, как работает область видимости: обычный пользователь видит
* только свои заметки, а для администратора (право data.all) видны все.
* Чужая запись для остальных просто не существует — «не найдено», а не
* «нет доступа»: постороннему знать нечего.
*/
final class NotesController extends Controller
{
public function index(Request $request, Scope $scope): Response
{
$filters = $this->listFilters($request);
return $this->view('notes/index', [
'active' => 'notes',
'page' => $filters->apply($this->listQuery($scope))->paginate($this->page($request), $this->perPage()),
'filters' => $filters,
], 'Заметки');
}
/**
* Выгрузка: своя область видимости остаётся в силе — чужие заметки
* не уедут в файл.
*/
public function export(Request $request, Scope $scope): Response
{
$filters = $this->listFilters($request);
return $this->exportCsv($filters->apply($this->listQuery($scope)), [
'id' => 'ID',
'title' => 'Название',
'body' => 'Текст',
'pinned' => ['Закреплена', static fn (Note $note): string => $note->pinned ? 'да' : 'нет'],
'created_at' => 'Создана',
'updated_at' => 'Изменена',
], 'notes', 'note', 'notes.index');
}
private function listFilters(Request $request): Filters
{
return $this->filters($request, [
Filter::search('q', 'Поиск', ['title', 'body'], 'заголовок или текст'),
Filter::flag('pinned', 'Закреплена'),
Filter::dates('created', 'Создана', 'created_at'),
])->sortable(['id', 'title', 'created_at'], 'id');
}
/**
* Закреплённые всегда сверху, поэтому их порядок ставится до фильтров.
*/
private function listQuery(Scope $scope): Query
{
return $scope->apply(Note::query())->orderBy('pinned', 'desc');
}
/**
* Загрузка заметок из CSV. Файл разбирается построчно: плохая строка
* попадает в отчёт, остальные заводятся.
*/
public function import(Request $request, Viewer $viewer): Response
{
$file = $request->file('file');
if ($file === null || !$file->uploaded()) {
$this->flash($file?->error() ?? 'Выберите файл CSV', 'error');
return $this->redirect('notes.index');
}
if ($file->extension() !== 'csv') {
$this->flash('Нужен файл CSV', 'error');
return $this->redirect('notes.index');
}
$report = Import::csv(
(string) file_get_contents($file->tmpPath()),
['Название' => 'title', 'Текст' => 'body', 'Закреплена' => 'pinned'],
['title' => 'required|max:191', 'body' => 'nullable|max:20000', 'pinned' => 'nullable|max:10'],
static function (array $row) use ($viewer): void {
$note = new Note([
'title' => (string) $row['title'],
'body' => (string) ($row['body'] ?? ''),
'pinned' => in_array(mb_strtolower((string) ($row['pinned'] ?? '')), ['да', '1', 'true'], true) ? 1 : 0,
]);
$note->setAttribute('user_id', $viewer->id());
$note->save();
}
);
Audit::action('note', 0, 'импорт заметок: ' . $report->summary());
View::stash('import', $report);
$this->flash($report->summary(), $report->failed > 0 ? 'error' : 'ok');
return $this->redirect('notes.index');
}
public function create(): Response
{
return $this->view('notes/form', [
'active' => 'notes',
'note' => new Note(),
], 'Новая заметка');
}
public function store(Request $request, Viewer $viewer): Response
{
$data = $this->validate($request, [
'title' => 'required|max:191',
'body' => 'nullable|max:20000',
'pinned' => 'nullable|boolean',
], ['title' => 'Название', 'body' => 'Текст']);
$limit = (int) Config::get('notes.per_user', 0);
// Ограничение правится из панели; 0 — без ограничения
if ($limit > 0 && Note::query()->where('user_id', $viewer->id())->count() >= $limit) {
$this->flash('Заметок уже ' . $limit . ', больше настройка не разрешает', 'error');
return $this->redirect('notes.index');
}
$note = new Note($data);
$note->setAttribute('user_id', $viewer->id());
$this->attachFile($request, $note);
$note->save();
Audit::created('note', $note->id(), 'заметка «' . (string) $note->title . '»');
// Событие уходит подписчикам вебхуков — список в config/webhooks.php
Events::fire('note.created', ['note' => $note]);
$this->flash('Заметка сохранена');
return $this->redirect('notes.show', ['id' => $note->id()]);
}
public function show(int $id, Scope $scope): Response
{
$note = $this->find($id, $scope);
return $this->view('notes/show', [
'active' => 'notes',
'note' => $note,
'author' => $note->author,
], (string) $note->title);
}
public function edit(int $id, Scope $scope): Response
{
return $this->view('notes/form', [
'active' => 'notes',
'note' => $this->find($id, $scope),
], 'Правка заметки');
}
public function update(Request $request, int $id, Scope $scope): Response
{
$note = $this->find($id, $scope);
$data = $this->validate($request, [
'title' => 'required|max:191',
'body' => 'nullable|max:20000',
'pinned' => 'nullable|boolean',
], ['title' => 'Название', 'body' => 'Текст']);
$before = ['title' => $note->title, 'body' => $note->body, 'pinned' => $note->raw('pinned')];
$note->fill($data);
$this->attachFile($request, $note);
$note->save();
Audit::updated('note', $note->id(), 'заметка «' . (string) $note->title . '»', Audit::between($before, [
'title' => $note->title,
'body' => $note->body,
'pinned' => $note->raw('pinned'),
]));
Events::fire('note.updated', ['note' => $note]);
$this->flash('Заметка сохранена');
return $this->redirect('notes.show', ['id' => $note->id()]);
}
public function delete(int $id, Scope $scope): Response
{
$note = $this->find($id, $scope);
// Мягкое удаление: запись остаётся в базе с отметкой времени
$note->delete();
Audit::deleted('note', $note->id(), 'заметка «' . (string) $note->title . '»');
Events::fire('note.deleted', ['note' => $note]);
$this->flash('Заметка удалена');
return $this->redirect('notes.index');
}
/**
* Отдаёт приложенный файл. Хранилище лежит вне public, поэтому файлы
* отдаёт код — присланный «аватар.php» не должен стать скриптом на сайте.
*/
public function file(int $id, Scope $scope): Response
{
$note = $this->find($id, $scope);
if (!$note->hasFile() || !Storage::exists((string) $note->raw('file_path'))) {
$this->flash('Файла нет', 'error');
return $this->redirect('notes.show', ['id' => $note->id()]);
}
return Response::download(
Storage::read((string) $note->raw('file_path')),
(string) $note->raw('file_name')
);
}
/**
* Заметка с оглядкой на область видимости: чужая для обычного пользователя
* просто не существует.
*/
private function find(int $id, Scope $scope): Note
{
/** @var Note|null $note */
$note = $scope->apply(Note::query())->where('id', $id)->first();
/** @var Note $found */
$found = $this->require($note, 'notes.index', 'Заметка не найдена');
return $found;
}
/**
* Прикладывает файл, если его прислали. Прежний удаляем после того, как
* новый лёг на диск, — иначе при ошибке останемся без обоих.
*/
private function attachFile(Request $request, Note $note): void
{
$file = $request->file('attachment');
if ($file === null || !$file->uploaded()) {
return;
}
try {
$stored = Storage::put($file, 'notes');
} catch (ProtonException $e) {
$this->flash($e->getMessage(), 'error');
return;
}
$previous = (string) $note->raw('file_path');
$note->forceFill(['file_path' => $stored['path'], 'file_name' => $stored['name']]);
if ($previous !== '' && $previous !== $stored['path']) {
Storage::delete($previous);
}
}
}