Skip to content

[lot] a lot #167

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ yarn-error.log
/.nova
/.vscode
/.zed
/.kanbn
lang/php_*.json
41 changes: 41 additions & 0 deletions app/Console/Commands/CleanCommandLogs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\CommandLog;
use App\Traits\LogsScheduledCommands;
use Carbon\Carbon;

class CleanCommandLogs extends Command
{
use LogsScheduledCommands;

protected $signature = 'grgsdev:logs-command-clean';
protected $description = 'Clean up old command logs';

public function handle()
{
// Obtém o número de dias da configuração

if (!config('app.keep_command_logs_for')) {
$days = 7;
} else {
$days = config('app.keep_command_logs_for', 7);
}

$thresholdDate = Carbon::now()->subDays($days);

try {
$deletedCount = CommandLog::where('executed_at', '<', $thresholdDate)->delete();
$outputMessage = "{$deletedCount} registros antigos de logs foram excluídos. Registros mais antigos que {$days} dias foram excluídos.";

$this->logCommandExecution($outputMessage, true);
$this->info($outputMessage);
} catch (\Exception $e) {
// Registro de falha no log
$this->logCommandExecution($e->getMessage(), false);
$this->error("Falha ao limpar logs de comandos antigos: {$e->getMessage()}");
}
}
}
44 changes: 44 additions & 0 deletions app/Console/Commands/CleanDeletedRecordsBackup.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Traits\LogsScheduledCommands;

class CleanDeletedRecordsBackup extends Command
{
use LogsScheduledCommands;
protected $signature = 'grgsdev:deleted-backup-clean'; // Nome do comando
protected $description = 'Clean up old deleted records backups';

public function handle()
{
// Verifica se a configuração 'keep_deleted_backup' está ativa
if (!config('app.keep_deleted_backup')) {
$this->logCommandExecution("Backup de registros excluídos está desativado. Nenhuma ação necessária.", true);
$this->info('Backup de registros excluídos está desativado. Nenhuma ação necessária.');
return;
}

// Obtém o número de dias configurados
$days = config('app.keep_deleted_backup_for');
$thresholdDate = Carbon::now()->subDays($days); // Data limite

try {
$deletedCount = DB::table('deleted_records')
->where('deleted_at', '<', $thresholdDate)
->delete();
$this->logCommandExecution("{$deletedCount} Backups antigos removidos com sucesso. Registros mais antigos que {$days} dias foram excluídos.", true);
$this->info("{$deletedCount} Backups antigos removidos com sucesso. Registros mais antigos que {$days} dias foram excluídos.");
} catch (\Exception $e) {
// Registro de falha no log
$this->logCommandExecution($e->getMessage(), false);
$this->error("Falha ao limpar backups antigos: {$e->getMessage()}");
}


// Realiza a limpeza de backups antigos
}
}
88 changes: 88 additions & 0 deletions app/Console/Commands/GrgsDev/AppendAttributes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace App\Console\Commands\GrgsDev;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class AppendAttributes extends Command
{
protected $signature = 'grgsdev:append-attributes';
protected $description = 'Append translated attributes to the attributes key in validation.php for each locale';

public function handle()
{
// Caminho do arquivo de traduções gerado pelo comando TranslateAttributes
$inputFilePath = base_path('documentation/translations/appTranslatedAttributes.php');

// Verificar se o arquivo existe
if (!File::exists($inputFilePath)) {
$this->error("O arquivo appTranslatedAttributes.php não foi encontrado.");
return Command::FAILURE;
}

// Incluir o arquivo de traduções
$translatedAttributes = include $inputFilePath;

// Verifica se o array de traduções é válido
if (!is_array($translatedAttributes)) {
$this->error("O arquivo appTranslatedAttributes.php não contém um array válido.");
return Command::FAILURE;
}

// Loop através de cada idioma (locale) e suas traduções
foreach ($translatedAttributes as $locale => $attributes) {
// Caminho do arquivo validation.php para o idioma atual
$validationFilePath = base_path("lang/{$locale}/validation.php");

// Verificar se o arquivo validation.php existe
if (!File::exists($validationFilePath)) {
$this->error("O arquivo validation.php para o idioma '{$locale}' não foi encontrado.");
continue;
}

// Incluir o conteúdo de validation.php
$validationArray = include $validationFilePath;

// Verificar se a chave 'attributes' existe, se não, pula o idioma
if (!isset($validationArray['attributes'])) {
$this->error("A chave 'attributes' não foi encontrada no arquivo validation.php para o idioma '{$locale}'.");
continue;
}

// Pegar os atributos existentes em 'attributes'
$existingAttributes = $validationArray['attributes'];

// Adicionar as chaves novas (que não existem em attributes) ao array existente
foreach ($attributes as $key => $value) {
if (!array_key_exists($key, $existingAttributes)) {
$existingAttributes[$key] = $value;
}
}

// Ordenar o array 'attributes' em ordem alfabética
ksort($existingAttributes);

// Atualizar apenas a chave 'attributes' no array de validation.php
$validationArray['attributes'] = $existingAttributes;

// Lê o conteúdo original do arquivo validation.php para não modificar sua estrutura
$originalContent = File::get($validationFilePath);

// Atualiza somente a chave 'attributes' no arquivo
$updatedAttributesExport = var_export($existingAttributes, true);
$updatedContent = preg_replace(
'/\'attributes\'\s*=>\s*\[[^\]]*\]/s',
"'attributes' => {$updatedAttributesExport}",
$originalContent
);

// Escreve o conteúdo atualizado no arquivo, mantendo o restante da estrutura
File::put($validationFilePath, $updatedContent);

$this->info("Atributos atualizados para o idioma '{$locale}' em lang/{$locale}/validation.php");
}

return Command::SUCCESS;
}
}
88 changes: 88 additions & 0 deletions app/Console/Commands/GrgsDev/ExtractAttributes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace App\Console\Commands\GrgsDev;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;

class ExtractAttributes extends Command
{
protected $signature = 'grgsdev:attributes';
protected $description = 'Extract attribute keys from rules() method in Request classes';

public function handle()
{
// Diretório de onde iremos buscar os arquivos PHP
$directory = app_path('Http/Requests');

// Verificar se o diretório existe
if (!File::isDirectory($directory)) {
$this->error("O diretório 'app/Http/Requests' não foi encontrado.");
return Command::FAILURE;
}

// Função para ler todos os arquivos .php recursivamente
$phpFiles = $this->getPhpFiles($directory);

$attributes = [];

// Percorrer todos os arquivos encontrados
foreach ($phpFiles as $file) {
$content = File::get($file);

// Usar regex para encontrar o método rules()
if (preg_match('/public function rules\(\)\s*\{(.*?)\}/s', $content, $matches)) {
$rulesContent = $matches[1];

// Encontrar as chaves dentro do array de rules()
if (preg_match_all('/\'([^\']+)\'\s*=>/', $rulesContent, $ruleMatches)) {
$keys = $ruleMatches[1];
$attributes = array_merge($attributes, $keys);
}
}
}

// Remover duplicatas e ordenar o array
$attributes = array_unique($attributes);
sort($attributes);

// Gerar o arquivo de saída no formato esperado
$output = "<?php\n\nreturn [\n";
foreach ($attributes as $attribute) {
$output .= " '$attribute',\n";
}
$output .= "];\n";

// Salvar o arquivo appAttributes.php no diretório app_path('documentation/translations')
$outputFilePath = base_path('documentation/translations/appAttributes.php');

// Criar o diretório se não existir
if (!File::isDirectory(base_path('documentation/translations'))) {
File::makeDirectory(base_path('documentation/translations'), 0755, true);
}

// Escrever o arquivo com os atributos extraídos
File::put($outputFilePath, $output);

$this->info("Atributos extraídos com sucesso em " . base_path('documentation/translations/appAttributes.php'));

return Command::SUCCESS;
}

// Função para obter todos os arquivos .php recursivamente
protected function getPhpFiles($directory)
{
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
$regexIterator = new RegexIterator($iterator, '/^.+\.php$/i', RegexIterator::GET_MATCH);

$files = [];
foreach ($regexIterator as $file) {
$files[] = $file[0];
}

return $files;
}
}
Loading
Loading