Списки: фильтры, сортировка, выгрузка и загрузка CSV
This commit is contained in:
1 parent
9075c817dc
commit
c4e9f6fc37
31 files changed
+1734
-184
No files matched your search
@@ -212,11 +212,14 @@ class Builder
|
||||
*/
|
||||
public function whereLike(string $column, string $value, string $boolean = 'AND'): static
|
||||
{
|
||||
$escaped = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value);
|
||||
// Экранируем восклицательным знаком, а не обратным слэшем: ESCAPE '!'
|
||||
// пишется одинаково в SQLite и MySQL, а «\» в MySQL пришлось бы удваивать
|
||||
// ещё раз. Без ESCAPE поиск по «имя_файла» не нашёл бы ничего.
|
||||
$escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value);
|
||||
|
||||
$this->wheres[] = [
|
||||
'type' => 'basic',
|
||||
'sql' => $this->name($column) . ' LIKE ' . $this->bind('%' . $escaped . '%'),
|
||||
'sql' => $this->name($column) . ' LIKE ' . $this->bind('%' . $escaped . '%') . " ESCAPE '!'",
|
||||
'boolean' => $boolean,
|
||||
];
|
||||
|
||||
|
||||
@@ -6,7 +6,12 @@ namespace Rsgrinko\Proton\Http;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Export;
|
||||
use Rsgrinko\Proton\Support\Filter;
|
||||
use Rsgrinko\Proton\Support\Filters;
|
||||
use Rsgrinko\Proton\Support\Validator;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
@@ -106,6 +111,39 @@ abstract class Controller
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Фильтры списка из параметров адреса.
|
||||
*
|
||||
* @param array<int, Filter> $fields
|
||||
*/
|
||||
protected function filters(Request $request, array $fields): Filters
|
||||
{
|
||||
return Filters::make($request, $fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выгрузка списка файлом: тот же запрос, что на экране, — с фильтрами
|
||||
* и сортировкой. Слишком большую выборку не отдаём: файл собирается
|
||||
* в памяти, а человек ждёт ответа.
|
||||
*
|
||||
* @param array<string, string|array{0: string, 1: callable}> $columns
|
||||
*/
|
||||
protected function exportCsv(Builder $query, array $columns, string $name, string $entity = '', string $route = ''): Response
|
||||
{
|
||||
if (!Export::fits($query)) {
|
||||
$this->flash('Слишком много строк для выгрузки — сузьте отбор (предел ' . Export::limit() . ')', 'error');
|
||||
|
||||
return $this->redirect($route !== '' ? $route : 'home');
|
||||
}
|
||||
|
||||
// Выгрузка уносит данные наружу файлом — это действие, а не просмотр
|
||||
if ($entity !== '') {
|
||||
Audit::action($entity, 0, 'выгружен список: ' . $name);
|
||||
}
|
||||
|
||||
return Export::csv($query, $columns, $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сколько записей показывать на странице.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
/**
|
||||
* Чтение и запись CSV.
|
||||
*
|
||||
* Разделитель по умолчанию — точка с запятой, а в начале файла BOM: Excel с
|
||||
* русской локалью иначе показывает запятые как один столбец и ломает кириллицу.
|
||||
* Для машин это ничего не меняет — разделитель настраивается (`export.delimiter`).
|
||||
*/
|
||||
final class Csv
|
||||
{
|
||||
public const BOM = "\xEF\xBB\xBF";
|
||||
|
||||
/**
|
||||
* Строки в текст CSV.
|
||||
*
|
||||
* @param iterable<int, array<int|string, mixed>> $rows
|
||||
* @param array<int, string> $headers
|
||||
*/
|
||||
public static function write(iterable $rows, array $headers = [], string $delimiter = ''): string
|
||||
{
|
||||
$delimiter = $delimiter !== '' ? $delimiter : self::delimiter();
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
|
||||
if ($handle === false) {
|
||||
throw new ProtonException('Не удалось открыть временный поток для CSV');
|
||||
}
|
||||
|
||||
if ($headers !== []) {
|
||||
fputcsv($handle, $headers, $delimiter, '"', '\\');
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($handle, array_map(self::cell(...), $row), $delimiter, '"', '\\');
|
||||
}
|
||||
|
||||
rewind($handle);
|
||||
|
||||
$content = (string) stream_get_contents($handle);
|
||||
|
||||
fclose($handle);
|
||||
|
||||
return self::BOM . $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Разбор CSV в строки. Первая строка — заголовки, они же ключи каждой
|
||||
* строки: так импорт не зависит от порядка колонок в файле.
|
||||
*
|
||||
* @return array<int, array<string, string>>
|
||||
*/
|
||||
public static function read(string $content, string $delimiter = ''): array
|
||||
{
|
||||
$content = str_starts_with($content, self::BOM) ? substr($content, strlen(self::BOM)) : $content;
|
||||
|
||||
// Файл мог приехать из Windows-редактора или с макбука
|
||||
$content = str_replace(["\r\n", "\r"], "\n", $content);
|
||||
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
|
||||
if ($handle === false) {
|
||||
throw new ProtonException('Не удалось открыть временный поток для CSV');
|
||||
}
|
||||
|
||||
fwrite($handle, $content);
|
||||
rewind($handle);
|
||||
|
||||
$delimiter = $delimiter !== '' ? $delimiter : self::sniff($content);
|
||||
$headers = [];
|
||||
$rows = [];
|
||||
|
||||
while (($line = fgetcsv($handle, 0, $delimiter, '"', '\\')) !== false) {
|
||||
// Пустая строка в конце файла — обычное дело
|
||||
if ($line === [null] || $line === ['']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$line = array_map(static fn (mixed $value): string => trim((string) $value), $line);
|
||||
|
||||
if ($headers === []) {
|
||||
$headers = $line;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$row = [];
|
||||
|
||||
foreach ($headers as $index => $header) {
|
||||
$row[$header] = $line[$index] ?? '';
|
||||
}
|
||||
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
fclose($handle);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Разделитель файла: что чаще встречается в первой строке, то и разделитель.
|
||||
* Люди приносят файлы и из Excel, и из выгрузок с запятой.
|
||||
*/
|
||||
private static function sniff(string $content): string
|
||||
{
|
||||
$first = strtok($content, "\n");
|
||||
|
||||
if ($first === false) {
|
||||
return self::delimiter();
|
||||
}
|
||||
|
||||
return substr_count($first, ';') >= substr_count($first, ',') ? ';' : ',';
|
||||
}
|
||||
|
||||
private static function delimiter(): string
|
||||
{
|
||||
$delimiter = (string) Config::get('export.delimiter', ';');
|
||||
|
||||
return $delimiter !== '' ? $delimiter : ';';
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение ячейки. Формулы обезвреживаем: строка, начинающаяся со знака
|
||||
* равенства, в Excel выполнится, а файл может уехать кому угодно.
|
||||
*/
|
||||
private static function cell(mixed $value): string
|
||||
{
|
||||
if (is_bool($value)) {
|
||||
return $value ? 'да' : 'нет';
|
||||
}
|
||||
|
||||
$text = $value === null ? '' : (string) $value;
|
||||
|
||||
return preg_match('/^[=+\-@]/', $text) === 1 ? "'" . $text : $text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
|
||||
/**
|
||||
* Выгрузка списка файлом. Забирает тот же запрос, что показан на экране, —
|
||||
* вместе с фильтрами и сортировкой, иначе выгрузка расходится с тем, что человек
|
||||
* видел.
|
||||
*
|
||||
* return Export::csv($filters->apply(User::query()), [
|
||||
* 'login' => 'Логин',
|
||||
* 'role' => ['Роль', static fn (User $user): string => $roles[$user->raw('role_id')] ?? ''],
|
||||
* ], 'users');
|
||||
*
|
||||
* Колонка — это «поле => подпись» или «поле => [подпись, как получить значение]».
|
||||
* Строки достаются порциями: миллион записей в память не поднимается.
|
||||
*/
|
||||
final class Export
|
||||
{
|
||||
/** Сколько строк забираем за один запрос к базе */
|
||||
private const CHUNK = 500;
|
||||
|
||||
/**
|
||||
* @param array<string, string|array{0: string, 1: callable}> $columns
|
||||
*/
|
||||
public static function csv(Builder $query, array $columns, string $name): Response
|
||||
{
|
||||
$headers = [];
|
||||
|
||||
foreach ($columns as $key => $column) {
|
||||
$headers[] = is_array($column) ? $column[0] : $column;
|
||||
}
|
||||
|
||||
return Response::download(
|
||||
Csv::write(self::rows($query, $columns), $headers),
|
||||
self::fileName($name),
|
||||
'text/csv; charset=utf-8'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сколько строк уедет в файл. Больше этого выгружать не даём: файл собирается
|
||||
* в памяти, а запрос идёт синхронно — на такие объёмы нужен не экспорт
|
||||
* из панели, а задача.
|
||||
*/
|
||||
public static function limit(): int
|
||||
{
|
||||
return max(1, (int) Config::get('export.max_rows', 20000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Влезет ли выборка в выгрузку.
|
||||
*/
|
||||
public static function fits(Builder $query): bool
|
||||
{
|
||||
return (clone $query)->count() <= self::limit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Имя файла: раздел и дата, чтобы в загрузках не копились export(3).csv.
|
||||
*/
|
||||
public static function fileName(string $name, string $extension = 'csv'): string
|
||||
{
|
||||
return $name . '-' . date('Y-m-d-His') . '.' . $extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* Строки выгрузки по описанию колонок.
|
||||
*
|
||||
* @param array<string, string|array{0: string, 1: callable}> $columns
|
||||
*
|
||||
* @return iterable<int, array<int, mixed>>
|
||||
*/
|
||||
private static function rows(Builder $query, array $columns): iterable
|
||||
{
|
||||
$out = [];
|
||||
|
||||
$query->chunk(self::CHUNK, static function (array $rows) use ($columns, &$out): void {
|
||||
foreach ($rows as $row) {
|
||||
$line = [];
|
||||
|
||||
foreach ($columns as $key => $column) {
|
||||
$line[] = is_array($column) ? ($column[1])($row) : self::value($row, $key);
|
||||
}
|
||||
|
||||
$out[] = $line;
|
||||
}
|
||||
});
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение поля и у модели, и у обычной строки запроса.
|
||||
*/
|
||||
private static function value(mixed $row, string $key): mixed
|
||||
{
|
||||
if ($row instanceof Model) {
|
||||
return $row->raw($key);
|
||||
}
|
||||
|
||||
if (is_array($row)) {
|
||||
return $row[$key] ?? '';
|
||||
}
|
||||
|
||||
return $row->{$key} ?? '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
/**
|
||||
* Описание одного фильтра списка: что спросить у человека и во что это
|
||||
* превратится в запросе. Сам по себе ничего не делает — набор таких описаний
|
||||
* разбирает и применяет {@see Filters}.
|
||||
*/
|
||||
final class Filter
|
||||
{
|
||||
/** Подстрока по нескольким колонкам сразу */
|
||||
public const SEARCH = 'search';
|
||||
|
||||
/** Выбор из готового списка значений */
|
||||
public const SELECT = 'select';
|
||||
|
||||
/** Точное совпадение со строкой */
|
||||
public const TEXT = 'text';
|
||||
|
||||
/** Да/нет — колонка 0 или 1 */
|
||||
public const FLAG = 'flag';
|
||||
|
||||
/** Колонка заполнена или пуста — для read_at, deleted_at и им подобных */
|
||||
public const FILLED = 'filled';
|
||||
|
||||
/** Диапазон дат: два параметра, {ключ}_from и {ключ}_to */
|
||||
public const DATES = 'dates';
|
||||
|
||||
/**
|
||||
* @param array<int, string> $columns колонки, по которым идёт поиск
|
||||
* @param array<string, string> $options значение => подпись для выпадающего списка
|
||||
*/
|
||||
private function __construct(
|
||||
public readonly string $type,
|
||||
public readonly string $key,
|
||||
public readonly string $label,
|
||||
public readonly array $columns,
|
||||
public readonly array $options = [],
|
||||
public readonly string $placeholder = '',
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Поиск подстроки. Колонок может быть несколько — они складываются через OR.
|
||||
*
|
||||
* @param array<int, string>|string $columns
|
||||
*/
|
||||
public static function search(string $key, string $label, array|string $columns, string $placeholder = ''): self
|
||||
{
|
||||
return new self(self::SEARCH, $key, $label, (array) $columns, [], $placeholder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбор из списка: значение сверяется с ключами $options, чужое отбрасывается.
|
||||
*
|
||||
* @param array<string|int, string> $options
|
||||
*/
|
||||
public static function select(string $key, string $label, array $options, string $column = ''): self
|
||||
{
|
||||
$strings = [];
|
||||
|
||||
foreach ($options as $value => $title) {
|
||||
$strings[(string) $value] = $title;
|
||||
}
|
||||
|
||||
return new self(self::SELECT, $key, $label, [$column !== '' ? $column : $key], $strings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Точное совпадение: раздел журнала, тип записи.
|
||||
*/
|
||||
public static function text(string $key, string $label, string $column = '', string $placeholder = ''): self
|
||||
{
|
||||
return new self(self::TEXT, $key, $label, [$column !== '' ? $column : $key], [], $placeholder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Да/нет. Третьего значения нет: пустое — «неважно».
|
||||
*/
|
||||
public static function flag(string $key, string $label, string $yes = 'да', string $no = 'нет', string $column = ''): self
|
||||
{
|
||||
return new self(self::FLAG, $key, $label, [$column !== '' ? $column : $key], ['1' => $yes, '0' => $no]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Заполнена ли колонка: «прочитано», «подтверждено», «удалено».
|
||||
*/
|
||||
public static function filled(string $key, string $label, string $yes = 'да', string $no = 'нет', string $column = ''): self
|
||||
{
|
||||
return new self(self::FILLED, $key, $label, [$column !== '' ? $column : $key], ['1' => $yes, '0' => $no]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Диапазон дат по одной колонке: в адресе это два параметра — {ключ}_from
|
||||
* и {ключ}_to, чтобы обе половины ходили по ссылкам сами.
|
||||
*/
|
||||
public static function dates(string $key, string $label, string $column = ''): self
|
||||
{
|
||||
return new self(self::DATES, $key, $label, [$column !== '' ? $column : $key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Колонка, к которой привязан фильтр.
|
||||
*/
|
||||
public function column(): string
|
||||
{
|
||||
return $this->columns[0] ?? $this->key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Параметры адреса, которые занимает фильтр.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function keys(): array
|
||||
{
|
||||
if ($this->type === self::DATES) {
|
||||
return [$this->key . '_from', $this->key . '_to'];
|
||||
}
|
||||
|
||||
return [$this->key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Правила проверки значений — по ним `Filters` отсеивает мусор из адреса.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return match ($this->type) {
|
||||
self::SELECT => [$this->key => 'nullable|in:' . implode(',', array_keys($this->options))],
|
||||
self::FLAG, self::FILLED => [$this->key => 'nullable|in:0,1'],
|
||||
self::DATES => [$this->key . '_from' => 'nullable|date', $this->key . '_to' => 'nullable|date'],
|
||||
default => [$this->key => 'nullable|max:190'],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
|
||||
/**
|
||||
* Фильтры и сортировка списка: разбирает параметры адреса, подмешивает их
|
||||
* в запрос и отдаёт вьюхе то, из чего рисуется форма и ссылки постраничной
|
||||
* навигации.
|
||||
*
|
||||
* $filters = Filters::make($request, [
|
||||
* Filter::search('q', 'Поиск', ['login', 'email']),
|
||||
* Filter::select('role_id', 'Роль', $roles),
|
||||
* ])->sortable(['id', 'login'], 'id');
|
||||
*
|
||||
* $page = $filters->apply(User::query())->paginate($this->page($request), $this->perPage());
|
||||
*
|
||||
* Негодное значение из адреса не роняет страницу, а отбрасывается: список —
|
||||
* не форма, показывать ошибку тут некому, а ссылку правят руками сплошь и рядом.
|
||||
* В SQL при этом уходят только имена колонок из кода и подготовленные значения.
|
||||
*/
|
||||
final class Filters
|
||||
{
|
||||
/** @var array<int, Filter> */
|
||||
private array $fields = [];
|
||||
|
||||
/** @var array<string, string> Значения параметров адреса */
|
||||
private array $values = [];
|
||||
|
||||
/** @var array<int, string> Колонки, по которым разрешено сортировать */
|
||||
private array $sortable = [];
|
||||
|
||||
private string $sort = '';
|
||||
|
||||
private string $direction = 'asc';
|
||||
|
||||
private ?Request $request = null;
|
||||
|
||||
/**
|
||||
* @param array<int, Filter> $fields
|
||||
*/
|
||||
public static function make(Request $request, array $fields): self
|
||||
{
|
||||
$filters = new self();
|
||||
$filters->fields = $fields;
|
||||
$filters->request = $request;
|
||||
|
||||
$input = [];
|
||||
$rules = [];
|
||||
|
||||
foreach ($fields as $field) {
|
||||
$rules += $field->rules();
|
||||
|
||||
foreach ($field->keys() as $key) {
|
||||
$value = $request->query($key, '');
|
||||
|
||||
$input[$key] = is_scalar($value) ? trim((string) $value) : '';
|
||||
}
|
||||
}
|
||||
|
||||
$validator = Validator::make($input, $rules);
|
||||
|
||||
// Проверку нужно прогнать, чтобы появились ошибки; исключение тут не
|
||||
// нужно — негодное значение просто не попадёт в запрос
|
||||
$validator->passes();
|
||||
|
||||
$errors = $validator->errors();
|
||||
|
||||
foreach ($input as $key => $value) {
|
||||
$filters->values[$key] = isset($errors[$key]) ? '' : $value;
|
||||
}
|
||||
|
||||
return $filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Разрешённые колонки сортировки. Белый список обязателен: имя колонки
|
||||
* подставляется в ORDER BY, и брать его прямо из адреса нельзя.
|
||||
*
|
||||
* @param array<int, string> $columns
|
||||
*/
|
||||
public function sortable(array $columns, string $default = '', string $direction = 'desc'): self
|
||||
{
|
||||
$this->sortable = $columns;
|
||||
$this->sort = $default;
|
||||
$this->direction = strtolower($direction) === 'asc' ? 'asc' : 'desc';
|
||||
|
||||
// Сортировку из адреса читаем здесь: раньше просто не с чем сверять
|
||||
$sort = (string) ($this->request?->query('sort', '') ?? '');
|
||||
|
||||
if (in_array($sort, $this->sortable, true)) {
|
||||
$this->sort = $sort;
|
||||
$this->direction = strtolower((string) ($this->request?->query('dir', '') ?? '')) === 'asc' ? 'asc' : 'desc';
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Можно ли сортировать по колонке — вьюхе, чтобы не рисовать ссылку там,
|
||||
* где она ничего не даст.
|
||||
*/
|
||||
public function sortableBy(string $column): bool
|
||||
{
|
||||
return in_array($column, $this->sortable, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение фильтра — вьюхе, чтобы показать заполненную форму.
|
||||
*/
|
||||
public function value(string $key): string
|
||||
{
|
||||
return $this->values[$key] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Хоть что-то выбрано — значит, есть что сбрасывать.
|
||||
*/
|
||||
public function active(): bool
|
||||
{
|
||||
foreach ($this->values as $value) {
|
||||
if ($value !== '') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Непустые параметры вместе с сортировкой: их тащат за собой ссылки
|
||||
* постраничной навигации, заголовки колонок и выгрузка.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function params(): array
|
||||
{
|
||||
$params = array_filter($this->values, static fn (string $value): bool => $value !== '');
|
||||
|
||||
if ($this->sort !== '') {
|
||||
$params['sort'] = $this->sort;
|
||||
$params['dir'] = $this->direction;
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, Filter>
|
||||
*/
|
||||
public function fields(): array
|
||||
{
|
||||
return $this->fields;
|
||||
}
|
||||
|
||||
public function sort(): string
|
||||
{
|
||||
return $this->sort;
|
||||
}
|
||||
|
||||
public function direction(): string
|
||||
{
|
||||
return $this->direction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Условия и порядок — в запрос.
|
||||
*
|
||||
* @template T of Builder
|
||||
*
|
||||
* @param T $query
|
||||
*
|
||||
* @return T
|
||||
*/
|
||||
public function apply(Builder $query): Builder
|
||||
{
|
||||
foreach ($this->fields as $field) {
|
||||
$this->applyField($query, $field);
|
||||
}
|
||||
|
||||
if ($this->sort !== '') {
|
||||
$query->orderBy($this->sort, $this->direction);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function applyField(Builder $query, Filter $field): void
|
||||
{
|
||||
$value = $this->value($field->key);
|
||||
|
||||
switch ($field->type) {
|
||||
case Filter::SEARCH:
|
||||
if ($value === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$columns = $field->columns;
|
||||
|
||||
$query->where(static function (Builder $nested) use ($columns, $value): void {
|
||||
foreach ($columns as $index => $column) {
|
||||
$nested->whereLike($column, $value, $index === 0 ? 'AND' : 'OR');
|
||||
}
|
||||
});
|
||||
|
||||
return;
|
||||
|
||||
case Filter::SELECT:
|
||||
case Filter::TEXT:
|
||||
case Filter::FLAG:
|
||||
if ($value === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$query->where($field->column(), '=', $value);
|
||||
|
||||
return;
|
||||
|
||||
case Filter::FILLED:
|
||||
if ($value === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$value === '1' ? $query->whereNotNull($field->column()) : $query->whereNull($field->column());
|
||||
|
||||
return;
|
||||
|
||||
case Filter::DATES:
|
||||
$from = $this->value($field->key . '_from');
|
||||
$to = $this->value($field->key . '_to');
|
||||
|
||||
// Граница «по» включительно: человек имеет в виду весь день
|
||||
if ($from !== '') {
|
||||
$query->where($field->column(), '>=', $from . ' 00:00:00');
|
||||
}
|
||||
|
||||
if ($to !== '') {
|
||||
$query->where($field->column(), '<=', $to . ' 23:59:59');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Разбор загруженного CSV построчно: колонки файла переводятся в поля, каждая
|
||||
* строка проходит `Validator`, и только потом её получает обработчик.
|
||||
*
|
||||
* $report = Import::csv($content, [
|
||||
* 'Название' => 'title',
|
||||
* 'Текст' => 'body',
|
||||
* ], [
|
||||
* 'title' => 'required|max:191',
|
||||
* 'body' => 'nullable|max:5000',
|
||||
* ], static function (array $row): void {
|
||||
* Note::create($row);
|
||||
* });
|
||||
*
|
||||
* Одна плохая строка не отменяет весь файл: она попадает в отчёт с номером,
|
||||
* остальные загружаются. Номер строки — как в Excel, вместе с заголовком,
|
||||
* иначе искать ошибку в файле неудобно.
|
||||
*/
|
||||
final class Import
|
||||
{
|
||||
/**
|
||||
* @param array<string, string> $columns заголовок в файле => поле
|
||||
* @param array<string, string> $rules правила проверки полей
|
||||
* @param callable(array<string, mixed>, int): void $handler что делать со строкой
|
||||
* @param array<string, string> $labels подписи полей для сообщений об ошибках
|
||||
*/
|
||||
public static function csv(string $content, array $columns, array $rules, callable $handler, array $labels = []): ImportReport
|
||||
{
|
||||
// Без подписей человек читал бы «поле title» — подставляем заголовки файла
|
||||
if ($labels === []) {
|
||||
$labels = array_flip($columns);
|
||||
}
|
||||
|
||||
$rows = Csv::read($content);
|
||||
|
||||
if ($rows === []) {
|
||||
return new ImportReport(0, 0, ['В файле нет ни одной строки с данными']);
|
||||
}
|
||||
|
||||
$limit = max(1, (int) Config::get('import.max_rows', 5000));
|
||||
|
||||
if (count($rows) > $limit) {
|
||||
return new ImportReport(0, 0, ['Строк в файле больше, чем разрешено за раз: ' . $limit]);
|
||||
}
|
||||
|
||||
$missing = self::missing($rows[0], $columns);
|
||||
|
||||
if ($missing !== []) {
|
||||
return new ImportReport(0, 0, ['В файле нет колонок: ' . implode(', ', $missing)]);
|
||||
}
|
||||
|
||||
$loaded = 0;
|
||||
$failed = 0;
|
||||
$errors = [];
|
||||
|
||||
foreach ($rows as $index => $row) {
|
||||
// Первая строка файла — заголовки, поэтому данные начинаются со второй
|
||||
$line = $index + 2;
|
||||
|
||||
$data = [];
|
||||
|
||||
foreach ($columns as $header => $field) {
|
||||
$data[$field] = $row[$header] ?? '';
|
||||
}
|
||||
|
||||
$validator = Validator::make($data, $rules, $labels);
|
||||
|
||||
if (!$validator->passes()) {
|
||||
$failed++;
|
||||
$errors[] = 'Строка ' . $line . ': ' . self::first($validator->errors());
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$handler($data, $line);
|
||||
|
||||
$loaded++;
|
||||
} catch (Throwable $e) {
|
||||
$failed++;
|
||||
$errors[] = 'Строка ' . $line . ': ' . $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
return new ImportReport($loaded, $failed, $errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Каких колонок не хватает в файле.
|
||||
*
|
||||
* @param array<string, string> $row
|
||||
* @param array<string, string> $columns
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private static function missing(array $row, array $columns): array
|
||||
{
|
||||
$missing = [];
|
||||
|
||||
foreach (array_keys($columns) as $header) {
|
||||
if (!array_key_exists($header, $row)) {
|
||||
$missing[] = $header;
|
||||
}
|
||||
}
|
||||
|
||||
return $missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array<int, string>> $errors
|
||||
*/
|
||||
private static function first(array $errors): string
|
||||
{
|
||||
foreach ($errors as $messages) {
|
||||
foreach ($messages as $message) {
|
||||
return $message;
|
||||
}
|
||||
}
|
||||
|
||||
return 'строка не прошла проверку';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
/**
|
||||
* Чем кончился импорт: сколько строк загрузилось, сколько нет и почему.
|
||||
* Показывается человеку целиком — иначе он не поймёт, что править в файле.
|
||||
*/
|
||||
final class ImportReport
|
||||
{
|
||||
/** Сколько ошибок показываем: остальные в том же духе */
|
||||
private const SHOW_ERRORS = 20;
|
||||
|
||||
/**
|
||||
* @param array<int, string> $errors
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $loaded,
|
||||
public readonly int $failed,
|
||||
public readonly array $errors = [],
|
||||
) {
|
||||
}
|
||||
|
||||
public function ok(): bool
|
||||
{
|
||||
return $this->failed === 0 && $this->loaded > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Первые ошибки — списком для страницы.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function firstErrors(): array
|
||||
{
|
||||
return array_slice($this->errors, 0, self::SHOW_ERRORS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сколько ошибок не показали.
|
||||
*/
|
||||
public function restErrors(): int
|
||||
{
|
||||
return max(0, count($this->errors) - self::SHOW_ERRORS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Строка для сообщения и журнала.
|
||||
*/
|
||||
public function summary(): string
|
||||
{
|
||||
if ($this->loaded === 0 && $this->failed === 0) {
|
||||
return 'Из файла ничего не загружено';
|
||||
}
|
||||
|
||||
$text = 'Загружено строк: ' . $this->loaded;
|
||||
|
||||
return $this->failed > 0 ? $text . ', с ошибками: ' . $this->failed : $text;
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ final class Settings
|
||||
'Приложение' => [
|
||||
'app.name' => ['label' => 'Название', 'type' => self::STRING],
|
||||
'ui.per_page' => ['label' => 'Записей на странице', 'type' => self::INT, 'hint' => 'от 5 до 200'],
|
||||
'export.max_rows' => ['label' => 'Строк на выгрузку', 'type' => self::INT, 'hint' => 'больше — только задачей'],
|
||||
'log.level' => [
|
||||
'label' => 'Подробность логов',
|
||||
'type' => self::SELECT,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Форма фильтров списка. Рисуется по описанию (`Support\Filter`), поэтому
|
||||
* новый фильтр появляется в разметке сам — правится только контроллер.
|
||||
*
|
||||
* @var \Rsgrinko\Proton\Support\Filters $filters
|
||||
* @var string $route имя маршрута раздела
|
||||
* @var int $total сколько всего нашлось
|
||||
* @var string $submit подпись кнопки
|
||||
* @var string $export имя маршрута выгрузки, если она есть
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Support\Filter;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
$total = $total ?? -1;
|
||||
$submit = $submit ?? 'Показать';
|
||||
$export = $export ?? '';
|
||||
?>
|
||||
<div class="card">
|
||||
<form method="get" action="<?= View::e(View::route($route)) ?>">
|
||||
<?php if ($filters->sort() !== '') { ?>
|
||||
<input type="hidden" name="sort" value="<?= View::e($filters->sort()) ?>">
|
||||
<input type="hidden" name="dir" value="<?= View::e($filters->direction()) ?>">
|
||||
<?php } ?>
|
||||
|
||||
<div class="filters">
|
||||
<?php foreach ($filters->fields() as $field) { ?>
|
||||
<label>
|
||||
<span><?= View::e($field->label) ?></span>
|
||||
|
||||
<?php if ($field->type === Filter::SEARCH) { ?>
|
||||
<input type="search" name="<?= View::e($field->key) ?>" value="<?= View::e($filters->value($field->key)) ?>" placeholder="<?= View::e($field->placeholder) ?>">
|
||||
<?php } elseif ($field->type === Filter::TEXT) { ?>
|
||||
<input type="text" name="<?= View::e($field->key) ?>" value="<?= View::e($filters->value($field->key)) ?>" placeholder="<?= View::e($field->placeholder) ?>">
|
||||
<?php } elseif ($field->type === Filter::DATES) { ?>
|
||||
<span class="range">
|
||||
<input type="date" name="<?= View::e($field->key) ?>_from" value="<?= View::e($filters->value($field->key . '_from')) ?>">
|
||||
<input type="date" name="<?= View::e($field->key) ?>_to" value="<?= View::e($filters->value($field->key . '_to')) ?>">
|
||||
</span>
|
||||
<?php } else { ?>
|
||||
<select name="<?= View::e($field->key) ?>">
|
||||
<option value="">неважно</option>
|
||||
<?php foreach ($field->options as $value => $title) { ?>
|
||||
<option value="<?= View::e($value) ?>" <?= $filters->value($field->key) === (string) $value ? 'selected' : '' ?>><?= View::e($title) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
<?php } ?>
|
||||
</label>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<div class="filter-actions row">
|
||||
<button type="submit" class="primary"><?= View::e($submit) ?></button>
|
||||
|
||||
<?php if ($filters->active()) { ?>
|
||||
<a class="btn" href="<?= View::e(View::route($route)) ?>">Сбросить</a>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($export !== '') { ?>
|
||||
<a class="btn" href="<?= View::e(View::route($export, $filters->params())) ?>">Выгрузить CSV</a>
|
||||
<?php } ?>
|
||||
|
||||
<span class="spacer"></span>
|
||||
|
||||
<?php if ($total >= 0) { ?>
|
||||
<span class="muted small">Всего: <?= (int) $total ?></span>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -210,8 +210,20 @@ $unread = $viewer->isGuest() ? 0 : UserNotification::unreadFor($viewer->id());
|
||||
|
||||
.filters { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; align-items: end; }
|
||||
.filters label { margin: 0; }
|
||||
.filters .range { display: flex; gap: 6px; }
|
||||
.filters .range input { min-width: 0; }
|
||||
.filter-actions { margin-top: 12px; }
|
||||
|
||||
.chart { display: flex; align-items: flex-end; gap: 2px; height: 120px; margin: 12px 0 6px; }
|
||||
.chart .col { flex: 1 1 0; min-width: 2px; min-height: 2px; border-radius: 3px 3px 0 0; background: var(--accent); opacity: .85; }
|
||||
.chart .col:hover { opacity: 1; }
|
||||
.chart .col.empty { background: var(--border); }
|
||||
.chart-legend { display: flex; justify-content: space-between; }
|
||||
|
||||
a.sort { color: inherit; text-decoration: none; white-space: nowrap; }
|
||||
a.sort:hover { text-decoration: underline; }
|
||||
a.sort .arrow { margin-left: 4px; color: var(--accent); }
|
||||
|
||||
.flash { padding: 10px 14px; border-radius: 8px; margin-bottom: 14px; word-break: break-word; }
|
||||
.flash.ok { background: var(--ok-bg); color: var(--ok); }
|
||||
.flash.error { background: var(--err-bg); color: var(--err); }
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Заголовок колонки, по которой можно сортировать. Ссылка тащит за собой
|
||||
* текущие фильтры, иначе клик по стрелке сбрасывал бы отбор.
|
||||
*
|
||||
* @var \Rsgrinko\Proton\Support\Filters $filters
|
||||
* @var string $route имя маршрута раздела
|
||||
* @var string $column колонка из белого списка сортировки
|
||||
* @var string $label подпись
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
if (!$filters->sortableBy($column)) {
|
||||
echo View::e($label);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$current = $filters->sort() === $column;
|
||||
// По той же колонке — переворачиваем, по новой — начинаем с убывания:
|
||||
// свежее и большее чаще всего и нужно первым
|
||||
$direction = $current && $filters->direction() === 'desc' ? 'asc' : 'desc';
|
||||
$params = array_merge($filters->params(), ['sort' => $column, 'dir' => $direction]);
|
||||
?>
|
||||
<a class="sort<?= $current ? ' current' : '' ?>" href="<?= View::e(View::route($route, $params)) ?>"><?= View::e($label) ?><?php if ($current) { ?><span class="arrow"><?= $filters->direction() === 'asc' ? '↑' : '↓' ?></span><?php } ?></a>
|
||||
Reference in new issue
Block a user