PluginProbe
Image Optimizer – Compress Images and Convert to WebP or AVIF / 1.0.1
Image Optimizer – Compress Images and Convert to WebP or AVIF v1.0.1
1.7.7 1.7.6 1.7.5 1.7.4 trunk 1.0.0 1.0.1 1.0.2 1.1.0 1.2.0 1.2.1 1.3.0 1.4.0 1.4.1 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 1.6.5 All 33 releases
image-optimization / modules / optimization / classes / validate-image.php

validate-image.php in Image Optimizer – Compress Images and Convert to WebP or AVIF 1.0.1, at modules/optimization/classes/validate-image.php

84 lines 2.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace ImageOptimizer\Modules\Optimization\Classes;
4
5 use ImageOptimizer\Classes\Image\{
6 Exceptions\Invalid_Image_Exception,
7 Image,
8 WP_Image_Meta,
9 };
10 use ImageOptimizer\Classes\File_Utils;
11 use ImageOptimizer\Modules\Optimization\Classes\Exceptions\Image_Validation_Error;
12
13 if ( ! defined( 'ABSPATH' ) ) {
14 exit; // Exit if accessed directly.
15 }
16
17 class Validate_Image {
18 public const MAX_FILE_SIZE = 10 * 1024 * 1024;
19
20 /**
21 * Returns true if $image_id provided associated with an image that can be optimized.
22 *
23 * @param int $image_id Attachment id.
24 *
25 * @return true
26 * @throws Image_Validation_Error
27 * @throws Invalid_Image_Exception
28 */
29 public static function is_valid( int $image_id ): bool {
30 $attachment_object = get_post( $image_id );
31
32 if ( ! $attachment_object ) {
33 throw new Image_Validation_Error(
34 __( 'Can\'t optimize this file. If the issue persists, Contact Support', 'image-optimizer' )
35 );
36 }
37
38 if (
39 ! wp_attachment_is_image( $attachment_object ) ||
40 ! in_array( $attachment_object->post_mime_type, Image::get_supported_mime_types(), true )
41 ) {
42 throw new Image_Validation_Error( self::prepare_supported_formats_list_error() );
43 }
44
45 if ( ! file_exists( get_attached_file( $image_id ) ) ) {
46 throw new Image_Validation_Error(
47 esc_html__( 'File is missing. Verify the upload', 'image-optimizer' )
48 );
49 }
50
51 $wp_meta = new WP_Image_Meta( $image_id );
52 $image_size = $wp_meta->get_file_size( Image::SIZE_FULL );
53
54 if ( $image_size > self::MAX_FILE_SIZE ) {
55 throw new Image_Validation_Error(
56 sprintf(
57 __( 'File is too large. Max size is %s', 'image-optimizer' ),
58 File_Utils::format_file_size( self::MAX_FILE_SIZE, 0 ),
59 )
60 );
61 }
62
63 return true;
64 }
65
66 /**
67 * Prepares the error message for the unsupported file formats.
68 *
69 * @return string The error message.
70 */
71 private static function prepare_supported_formats_list_error(): string {
72 $formats = Image::get_supported_formats();
73 $last_item = strtoupper( array_pop( $formats ) );
74
75 $formats_list = join( ', ', array_map( 'strtoupper', $formats ) );
76
77 return sprintf(
78 __( 'Wrong file format. Only %1$s, or %2$s are accepted', 'image-optimizer' ),
79 $formats_list,
80 $last_item
81 );
82 }
83 }
84