Last active
June 11, 2020 17:22
-
-
Save ProjectOrangeBox/f35ddedf52246c0cec897ba8ffc63402 to your computer and use it in GitHub Desktop.
Clean up files in a folder based on regular expression and days as well as database table based on datetime stamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class cleanUp | |
{ | |
static public function folder(string $folder, string $fileRegEx, int $days, bool $recusive = true): int | |
{ | |
$count = 0; | |
if (!\FS::file_exists($folder)) { | |
throw new \Exception('Folder "' . $folder . '" not found.'); | |
} | |
$fileRegEx = ';' . str_replace(';', '\;', $fileRegEx) . ';'; | |
foreach (FS::glob(rtrim($folder, '/') . '/*', 0, $recusive) as $singleFile) { | |
if (preg_match($fileRegEx, FS::basename($singleFile))) { | |
if (time() - FS::filemtime($singleFile) >= (86400 * $days)) { | |
FS::unlink($singleFile); | |
$count++; | |
} | |
} | |
} | |
return $count; | |
} | |
static public function table(string $pdoDSN, string $username, string $password, string $tableColumn, int $days): int | |
{ | |
$count = 0; | |
try { | |
$pdo = new PDO($pdoDSN, $username, $password); | |
} catch (\PDOException $e) { | |
throw new \PDOException($e->getMessage(), (int) $e->getCode()); | |
} | |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
list($table, $column) = explode('.', $tableColumn, 2); | |
try { | |
$del = $pdo->prepare('delete from `' . $table . '` where `' . $column . '` < NOW() - INTERVAL ? DAY'); | |
$del->execute([$days]); | |
$count = $del->rowCount(); | |
} catch (\PDOException $e) { | |
throw new \PDOException($e->getMessage(), (int) $e->getCode()); | |
} | |
return $count; | |
} | |
} /* end class */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment