Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Washing - Remove arquivos e diretórios recursivamente
- * @version 2.0
- */
- class Washing {
- /**
- * Caminhos críticos bloqueados por segurança
- * Chamadas que apontem para esses diretórios lançam exceção
- */
- private array $blocked = ['/', '/etc', '/var', '/usr', '/bin', '/boot'];
- /**
- * Relatório da última operação
- * ['removed' => [...], 'failed' => [...]]
- */
- private array $report = ['removed' => [], 'failed' => []];
- // -------------------------------------------------------------------------
- /**
- * Aceita qualquer combinação de strings e arrays com caminhos
- * Se chamado sem argumentos, limpa o diretório atual
- *
- * @example
- * new Washing(); // limpa getcwd()
- * new Washing('/tmp/cache'); // limpa um diretório
- * new Washing('/tmp/cache', '/tmp/logs'); // limpa múltiplos
- * new Washing(['/tmp/a', '/tmp/b']); // aceita array também
- */
- public function __construct(mixed ...$items) {
- $this->report = ['removed' => [], 'failed' => []];
- if (empty($items)) {
- $this->process(getcwd());
- return;
- }
- foreach ($items as $item) {
- $this->resolve($item);
- }
- }
- // -------------------------------------------------------------------------
- /**
- * Resolve o tipo do argumento (string ou array) antes de limpar
- */
- private function resolve(mixed $item): void {
- if (is_array($item)) {
- foreach ($item as $path) {
- $this->resolve($path);
- }
- return;
- }
- if (is_string($item) && $item !== '') {
- $this->process($item);
- return;
- }
- // Argumento inválido — limpa diretório atual como fallback
- $this->process(getcwd());
- }
- /**
- * Executa a remoção de um arquivo ou diretório
- *
- * @throws InvalidArgumentException se o caminho for bloqueado
- * @throws RuntimeException se o caminho não existir
- */
- private function process(string $path): void {
- $real = realpath($path);
- // Caminho não existe
- if ($real === false) {
- throw new RuntimeException(
- "Washing: caminho não encontrado — \"{$path}\""
- );
- }
- // Bloqueio de caminhos críticos
- foreach ($this->blocked as $blocked) {
- if ($real === $blocked || str_starts_with($real, $blocked . DIRECTORY_SEPARATOR)) {
- throw new InvalidArgumentException(
- "Washing: caminho bloqueado por segurança — \"{$real}\""
- );
- }
- }
- if (is_file($real)) {
- $this->removeFile($real);
- return;
- }
- if (is_dir($real)) {
- $this->removeDir($real);
- return;
- }
- $this->report['failed'][] = $real;
- }
- /**
- * Remove um arquivo único
- */
- private function removeFile(string $path): void {
- if (unlink($path)) {
- $this->report['removed'][] = $path;
- } else {
- $this->report['failed'][] = $path;
- }
- }
- /**
- * Remove um diretório recursivamente (conteúdo + o próprio diretório)
- */
- private function removeDir(string $path): void {
- $iterator = new RecursiveIteratorIterator(
- new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
- RecursiveIteratorIterator::CHILD_FIRST
- );
- foreach ($iterator as $file) {
- $filepath = $file->getPathname();
- if ($file->isFile() || $file->isLink()) {
- if (unlink($filepath)) {
- $this->report['removed'][] = $filepath;
- } else {
- $this->report['failed'][] = $filepath;
- }
- } elseif ($file->isDir()) {
- if (rmdir($filepath)) {
- $this->report['removed'][] = $filepath;
- } else {
- $this->report['failed'][] = $filepath;
- }
- }
- }
- // Remove o diretório raiz após esvaziar
- if (rmdir($path)) {
- $this->report['removed'][] = $path;
- } else {
- $this->report['failed'][] = $path;
- }
- }
- // -------------------------------------------------------------------------
- // RELATÓRIO
- // -------------------------------------------------------------------------
- /**
- * Retorna o relatório completo da última operação
- *
- * @return array{removed: string[], failed: string[]}
- *
- * @example
- * $w = new Washing('/tmp/cache');
- * $report = $w->getReport();
- * echo count($report['removed']) . " removidos";
- * echo count($report['failed']) . " falhas";
- */
- public function getReport(): array {
- return $this->report;
- }
- /**
- * Retorna true se a operação não teve nenhuma falha
- */
- public function success(): bool {
- return empty($this->report['failed']);
- }
- /**
- * Retorna a lista de itens removidos com sucesso
- */
- public function removed(): array {
- return $this->report['removed'];
- }
- /**
- * Retorna a lista de itens que falharam
- */
- public function failed(): array {
- return $this->report['failed'];
- }
- // -------------------------------------------------------------------------
- // CONFIGURAÇÃO
- // -------------------------------------------------------------------------
- /**
- * Adiciona um caminho à lista de bloqueados
- *
- * @example
- * $w = new Washing();
- * $w->addBlocked('/var/www/producao');
- */
- public function addBlocked(string $path): void {
- $real = realpath($path);
- if ($real && !in_array($real, $this->blocked)) {
- $this->blocked[] = $real;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment