| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
namespace Jet_Form_Builder\Classes\Resources; |
| 5 |
|
| 6 |
// If this file is called directly, abort. |
| 7 |
if ( ! defined( 'WPINC' ) ) { |
| 8 |
die; |
| 9 |
} |
| 10 |
|
| 11 |
class File_Tools { |
| 12 |
|
| 13 |
public static function get_uploaded( File $file, $preset ) { |
| 14 |
if ( $preset instanceof Uploaded_File && self::is_same_file( $file, $preset ) ) { |
| 15 |
return $preset; |
| 16 |
} |
| 17 |
|
| 18 |
if ( ! is_array( $preset ) ) { |
| 19 |
return false; |
| 20 |
} |
| 21 |
|
| 22 |
/** @var Uploaded_File $uploaded */ |
| 23 |
foreach ( $preset as $uploaded ) { |
| 24 |
if ( self::is_same_file( $file, $uploaded ) ) { |
| 25 |
return $uploaded; |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
return false; |
| 30 |
} |
| 31 |
|
| 32 |
protected static function is_same_file( File $file, Uploaded_File $uploaded_file ): bool { |
| 33 |
$preset_path = $uploaded_file->get_attachment_file(); |
| 34 |
|
| 35 |
if ( ! $preset_path ) { |
| 36 |
return false; |
| 37 |
} |
| 38 |
|
| 39 |
$info = pathinfo( $preset_path ); |
| 40 |
|
| 41 |
return $file->get_name() === ( $info['basename'] ?? '' ); |
| 42 |
} |
| 43 |
|
| 44 |
public static function is_same_ext( string $file_name, string $need_ext ): bool { |
| 45 |
$ext = self::get_file_ext( $file_name ); |
| 46 |
|
| 47 |
if ( 0 === strpos( $need_ext, '.' ) ) { |
| 48 |
$need_ext = substr( $need_ext, 1, strlen( $need_ext ) - 1 ); |
| 49 |
} |
| 50 |
|
| 51 |
return $ext === $need_ext; |
| 52 |
} |
| 53 |
|
| 54 |
public static function get_file_ext( string $file_name ): string { |
| 55 |
$file_parts = explode( '.', $file_name ); |
| 56 |
|
| 57 |
return end( $file_parts ); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* @param string|int $file_data |
| 62 |
* |
| 63 |
* @return Uploaded_File|false |
| 64 |
*/ |
| 65 |
public static function create_uploaded_file( $file_data ) { |
| 66 |
if ( is_numeric( $file_data ) ) { |
| 67 |
$uploaded = new Uploaded_File(); |
| 68 |
|
| 69 |
return $uploaded->set_attachment_id( $file_data ); |
| 70 |
} |
| 71 |
|
| 72 |
if ( ! empty( $file_data['id'] ) && is_numeric( $file_data['id'] ) ) { |
| 73 |
return self::create_uploaded_file( $file_data['id'] ); |
| 74 |
} |
| 75 |
|
| 76 |
// phpcs:ignore WordPress.WP.AlternativeFunctions |
| 77 |
if ( ! is_string( $file_data ) || false === parse_url( $file_data ) ) { |
| 78 |
return false; |
| 79 |
} |
| 80 |
|
| 81 |
$attachment_id = attachment_url_to_postid( $file_data ); |
| 82 |
|
| 83 |
return $attachment_id ? self::create_uploaded_file( $attachment_id ) : false; |
| 84 |
} |
| 85 |
|
| 86 |
} |
| 87 |
|