Improve file path validation

This commit is contained in:
Corey McKrill 2023-10-30 11:55:26 -07:00
parent 2fe04da8f4
commit 7ecb9dfaee
No known key found for this signature in database
GPG Key ID: 84BBFE669C4D97B8
2 changed files with 26 additions and 8 deletions

View File

@ -102,6 +102,24 @@ class File {
}
}
/**
* Check if the file represented by the class instance is a file and is readable.
*
* @return bool
*/
public function is_readable(): bool {
return is_file( $this->path ) && is_readable( $this->path );
}
/**
* Check if the file represented by the class instance is a file and is writable.
*
* @return bool
*/
public function is_writable(): bool {
return is_file( $this->path ) && is_writable( $this->path );
}
/**
* Get the name of the file, with extension, but without full path.
*

View File

@ -176,11 +176,8 @@ class FileController {
private function convert_paths_to_objects( array $paths ): array {
$files = array_map(
function( $path ) {
if ( ! is_readable( $path ) ) {
return null;
}
return new File( $path );
$file = new File( $path );
return $file->is_readable() ? $file : null;
},
$paths
);
@ -205,12 +202,12 @@ class FileController {
$all_sources = array_map(
function( $path ) {
$file = new File( $path );
return $file->get_source();
return $file->is_readable() ? $file->get_source() : null;
},
$paths
);
return array_unique( $all_sources );
return array_unique( array_filter( $all_sources ) );
}
/**
@ -225,7 +222,10 @@ class FileController {
$files = $this->get_files_by_id( $file_ids );
foreach ( $files as $file ) {
$result = $file->delete();
$result = false;
if ( $file->is_readable() ) {
$result = $file->delete();
}
if ( true === $result ) {
$deleted ++;