mirror of
https://gitlab.com/DanLegoff/mgap.git
synced 2026-11-16 14:12:39 +00:00
92 lines
2.6 KiB
PHP
92 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\QueryException;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
abstract class Controller
|
|
{
|
|
protected function deletePreservingHistory(Model $model): void
|
|
{
|
|
try {
|
|
$model->delete();
|
|
} catch (QueryException $exception) {
|
|
if ((string) $exception->getCode() !== '23000') {
|
|
throw $exception;
|
|
}
|
|
|
|
throw ValidationException::withMessages([
|
|
'delete' => 'No se puede eliminar porque existen relaciones o historial asociado.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
protected function applySearch(Builder $query, ?string $search, array $columns): Builder
|
|
{
|
|
$search = trim((string) $search);
|
|
|
|
if ($search === '') {
|
|
return $query;
|
|
}
|
|
|
|
return $query->where(function (Builder $query) use ($search, $columns) {
|
|
foreach ($columns as $index => $column) {
|
|
$method = $index === 0 ? 'where' : 'orWhere';
|
|
$query->{$method}($column, 'like', "%{$search}%");
|
|
}
|
|
});
|
|
}
|
|
|
|
protected function paginated(Builder $query, int $perPage = 10)
|
|
{
|
|
return $query->paginate($perPage)->withQueryString();
|
|
}
|
|
|
|
protected function streamCsv(string $fileName, array $columns, $items, callable $rowMapper)
|
|
{
|
|
$headers = [
|
|
'Content-type' => 'text/csv; charset=UTF-8',
|
|
'Content-Disposition' => "attachment; filename={$fileName}",
|
|
'Pragma' => 'no-cache',
|
|
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
|
|
'Expires' => '0',
|
|
];
|
|
|
|
$callback = function () use ($items, $columns, $rowMapper) {
|
|
$file = fopen('php://output', 'w');
|
|
fwrite($file, "\xEF\xBB\xBF");
|
|
fputcsv($file, $this->sanitizeCsvRow($columns));
|
|
|
|
foreach ($items as $item) {
|
|
fputcsv($file, $this->sanitizeCsvRow($rowMapper($item)));
|
|
}
|
|
|
|
fclose($file);
|
|
};
|
|
|
|
return response()->stream($callback, 200, $headers);
|
|
}
|
|
|
|
private function sanitizeCsvRow(array $row): array
|
|
{
|
|
return array_map([$this, 'sanitizeCsvValue'], $row);
|
|
}
|
|
|
|
private function sanitizeCsvValue($value)
|
|
{
|
|
if ($value === null) {
|
|
return null;
|
|
}
|
|
|
|
$value = (string) $value;
|
|
$trimmed = ltrim($value);
|
|
|
|
return $trimmed !== '' && in_array($trimmed[0], ['=', '+', '-', '@'], true)
|
|
? "'{$value}"
|
|
: $value;
|
|
}
|
|
}
|