Automattic\WooCommerce\Internal\Admin\Logging\FileV2
FileController::delete_stale_files
Delete files of a given source that were last modified before a given time.
Files are enumerated lazily and are neither sorted nor turned into File instances, so this stays cheap on directories holding a large number of files, unlike get_files().
Method of the class: FileController{}
No Hooks.
Returns
Int. The number of files that were deleted.
Usage
$FileController = new FileController(); $FileController->delete_stale_files( $source, $modified_before, $limit ): int;
- $source(string) (required)
- Match files whose name begins with this source.
- $modified_before(int) (required)
- Only delete files modified before this Unix timestamp.
- $limit(int) (required)
- The maximum number of files to delete.
FileController::delete_stale_files() FileController::delete stale files code WC 11.0.1
public function delete_stale_files( string $source, int $modified_before, int $limit ): int {
if ( '' === $source || $limit < 1 ) {
return 0;
}
try {
$filesystem = FilesystemUtil::get_wp_filesystem_direct();
$iterator = new \FilesystemIterator(
Settings::get_log_directory(),
\FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::KEY_AS_FILENAME
);
} catch ( Exception $exception ) {
// Surface this so a persistent failure to reach the log directory doesn't stay silent.
wc_get_logger()->warning(
sprintf(
'Could not enumerate the log directory to delete stale "%1$s" files: %2$s',
$source,
$exception->getMessage()
),
array( 'source' => 'wc-logs-cleanup' )
);
return 0;
}
$deleted = 0;
foreach ( $iterator as $basename => $path ) {
if ( ! str_starts_with( (string) $basename, $source ) || ! str_ends_with( (string) $basename, '.log' ) ) {
continue;
}
$path = (string) $path;
$modified = $filesystem->mtime( $path );
if ( false === $modified || $modified >= $modified_before ) {
continue;
}
if ( $filesystem->delete( $path, false, 'f' ) ) {
++$deleted;
}
if ( $deleted >= $limit ) {
break;
}
}
if ( $deleted > 0 ) {
$this->invalidate_cache();
}
return $deleted;
}