Completed
Push — master ( c69376...444d31 )
by David
02:14
created
src/includes/class-wordlift-remote-image-service.php 2 patches
Indentation   +138 added lines, -138 removed lines patch added patch discarded remove patch
@@ -8,143 +8,143 @@
 block discarded – undo
8 8
  */
9 9
 class Wordlift_Remote_Image_Service {
10 10
 
11
-	/**
12
-	 * Save the image with the specified URL locally.
13
-	 *
14
-	 * @param string $url The image remote URL.
15
-	 *
16
-	 * @return array|false|WP_Error An array with information about the saved image (*path*: the local path to the image, *url*: the local
17
-	 * url, *content_type*: the image content type) or false on error.
18
-	 * @since 3.18.0
19
-	 * @since 3.23.4 the function may return a WP_Error.
20
-	 */
21
-	public static function save_from_url( $url ) {
22
-
23
-		// Required for REST API calls
24
-		if ( ! function_exists( 'WP_Filesystem' ) ) {
25
-			require_once( ABSPATH . 'wp-admin/includes/file.php' );
26
-		}
27
-
28
-		// Load `WP_Filesystem`.
29
-		WP_Filesystem();
30
-		global $wp_filesystem;
31
-
32
-		// Parse the url.
33
-		$parts = wp_parse_url( $url );
34
-
35
-		// Get the bare filename (filename w/o the extension).
36
-		$basename = str_replace( DIRECTORY_SEPARATOR, '_', rawurldecode(
37
-			pathinfo( $parts['path'], PATHINFO_FILENAME )
38
-		) );
39
-
40
-		// Get the base dir.
41
-		$wp_upload_dir = wp_upload_dir();
42
-
43
-		// Set the upload directory and URL.
44
-		$upload_dir = $wp_upload_dir['basedir'] . '/wl' . $wp_upload_dir['subdir'];
45
-		$upload_url = $wp_upload_dir['baseurl'] . '/wl' . $wp_upload_dir['subdir'];
46
-
47
-		// Get the full path to the local filename.
48
-		$image_full_path = $upload_dir . '/' . $basename;
49
-		$image_full_url  = $upload_url . '/' . $basename;
50
-
51
-		// Create custom directory and bail on failure.
52
-		if ( ! wp_mkdir_p( $upload_dir ) ) {
53
-			Wordlift_Log_Service::get_logger( 'Wordlift_Remote_Image_Service' )
54
-			                    ->warn( "save_image_from_url : failed creating upload dir $upload_dir \n" );
55
-
56
-			return new WP_Error( 'image_error', "save_image_from_url : failed creating upload dir $upload_dir \n" );
57
-		};
58
-
59
-		$response = self::get_response( $url );
60
-
61
-		// Bail if the response is not set.
62
-		if ( false === $response ) {
63
-			Wordlift_Log_Service::get_logger( 'Wordlift_Remote_Image_Service' )
64
-			                    ->warn( "save_image_from_url : failed to fetch the response from: $url \n" );
65
-
66
-			return new WP_Error( 'image_error', "save_image_from_url : failed to fetch the response from: $url \n" );
67
-		}
68
-
69
-		// Get the content type of response.
70
-		$content_type = wp_remote_retrieve_header( $response, 'content-type' );
71
-
72
-		// Get the file extension.
73
-		$extension = self::get_extension_from_content_type( $content_type );
74
-
75
-		// Bail if the content type is not supported.
76
-		if ( empty( $extension ) ) {
77
-			return new WP_Error( 'image_error', 'Unsupported content type.' );
78
-		}
79
-
80
-		// Complete the local filename.
81
-		$image_full_path .= $extension;
82
-		$image_full_url  .= $extension;
83
-
84
-		// Store the data locally.
85
-		$wp_filesystem->put_contents( $image_full_path, wp_remote_retrieve_body( $response ) );
86
-
87
-		// Return the path.
88
-		return array(
89
-			'path'         => $image_full_path,
90
-			'url'          => $image_full_url,
91
-			'content_type' => $content_type,
92
-		);
93
-	}
94
-
95
-	/**
96
-	 * Returns the file extension using the content type.
97
-	 *
98
-	 * @param string $content_type File content type.
99
-	 *
100
-	 * @return string|bool The file extension on success and
101
-	 * false on fail or if the content type is not supported.
102
-	 * @since 3.18.0
103
-	 *
104
-	 */
105
-	private static function get_extension_from_content_type( $content_type ) {
106
-
107
-		// Return the extension if match.
108
-		switch ( $content_type ) {
109
-			case 'image/jpeg':
110
-			case 'image/jpg':
111
-				return '.jpg';
112
-			case 'image/gif':
113
-				return '.gif';
114
-			case 'image/png':
115
-				return '.png';
116
-		}
117
-
118
-		// Otherwise return false.
119
-		return false;
120
-	}
121
-
122
-	/**
123
-	 * Retrieve the response from url and sets the response.
124
-	 *
125
-	 * @param string $url The url to retrieve.
126
-	 *
127
-	 * @return false|array True on success and false on failure.
128
-	 * @since 3.18.0
129
-	 *
130
-	 */
131
-	private static function get_response( $url ) {
132
-		// Request the remote file.
133
-		$response = wp_remote_get( $url );
134
-
135
-		// Bail out if the response is not ok.
136
-		if (
137
-			is_wp_error( $response )
138
-			|| 200 !== (int) $response['response']['code']
139
-			|| ! isset( $response['body'] )
140
-		) {
141
-			wl_write_log( "save_image_from_url : error fetching image $url \n" );
142
-
143
-			return false;
144
-		}
145
-
146
-		// Set the response.
147
-		return $response;
148
-	}
11
+    /**
12
+     * Save the image with the specified URL locally.
13
+     *
14
+     * @param string $url The image remote URL.
15
+     *
16
+     * @return array|false|WP_Error An array with information about the saved image (*path*: the local path to the image, *url*: the local
17
+     * url, *content_type*: the image content type) or false on error.
18
+     * @since 3.18.0
19
+     * @since 3.23.4 the function may return a WP_Error.
20
+     */
21
+    public static function save_from_url( $url ) {
22
+
23
+        // Required for REST API calls
24
+        if ( ! function_exists( 'WP_Filesystem' ) ) {
25
+            require_once( ABSPATH . 'wp-admin/includes/file.php' );
26
+        }
27
+
28
+        // Load `WP_Filesystem`.
29
+        WP_Filesystem();
30
+        global $wp_filesystem;
31
+
32
+        // Parse the url.
33
+        $parts = wp_parse_url( $url );
34
+
35
+        // Get the bare filename (filename w/o the extension).
36
+        $basename = str_replace( DIRECTORY_SEPARATOR, '_', rawurldecode(
37
+            pathinfo( $parts['path'], PATHINFO_FILENAME )
38
+        ) );
39
+
40
+        // Get the base dir.
41
+        $wp_upload_dir = wp_upload_dir();
42
+
43
+        // Set the upload directory and URL.
44
+        $upload_dir = $wp_upload_dir['basedir'] . '/wl' . $wp_upload_dir['subdir'];
45
+        $upload_url = $wp_upload_dir['baseurl'] . '/wl' . $wp_upload_dir['subdir'];
46
+
47
+        // Get the full path to the local filename.
48
+        $image_full_path = $upload_dir . '/' . $basename;
49
+        $image_full_url  = $upload_url . '/' . $basename;
50
+
51
+        // Create custom directory and bail on failure.
52
+        if ( ! wp_mkdir_p( $upload_dir ) ) {
53
+            Wordlift_Log_Service::get_logger( 'Wordlift_Remote_Image_Service' )
54
+                                ->warn( "save_image_from_url : failed creating upload dir $upload_dir \n" );
55
+
56
+            return new WP_Error( 'image_error', "save_image_from_url : failed creating upload dir $upload_dir \n" );
57
+        };
58
+
59
+        $response = self::get_response( $url );
60
+
61
+        // Bail if the response is not set.
62
+        if ( false === $response ) {
63
+            Wordlift_Log_Service::get_logger( 'Wordlift_Remote_Image_Service' )
64
+                                ->warn( "save_image_from_url : failed to fetch the response from: $url \n" );
65
+
66
+            return new WP_Error( 'image_error', "save_image_from_url : failed to fetch the response from: $url \n" );
67
+        }
68
+
69
+        // Get the content type of response.
70
+        $content_type = wp_remote_retrieve_header( $response, 'content-type' );
71
+
72
+        // Get the file extension.
73
+        $extension = self::get_extension_from_content_type( $content_type );
74
+
75
+        // Bail if the content type is not supported.
76
+        if ( empty( $extension ) ) {
77
+            return new WP_Error( 'image_error', 'Unsupported content type.' );
78
+        }
79
+
80
+        // Complete the local filename.
81
+        $image_full_path .= $extension;
82
+        $image_full_url  .= $extension;
83
+
84
+        // Store the data locally.
85
+        $wp_filesystem->put_contents( $image_full_path, wp_remote_retrieve_body( $response ) );
86
+
87
+        // Return the path.
88
+        return array(
89
+            'path'         => $image_full_path,
90
+            'url'          => $image_full_url,
91
+            'content_type' => $content_type,
92
+        );
93
+    }
94
+
95
+    /**
96
+     * Returns the file extension using the content type.
97
+     *
98
+     * @param string $content_type File content type.
99
+     *
100
+     * @return string|bool The file extension on success and
101
+     * false on fail or if the content type is not supported.
102
+     * @since 3.18.0
103
+     *
104
+     */
105
+    private static function get_extension_from_content_type( $content_type ) {
106
+
107
+        // Return the extension if match.
108
+        switch ( $content_type ) {
109
+            case 'image/jpeg':
110
+            case 'image/jpg':
111
+                return '.jpg';
112
+            case 'image/gif':
113
+                return '.gif';
114
+            case 'image/png':
115
+                return '.png';
116
+        }
117
+
118
+        // Otherwise return false.
119
+        return false;
120
+    }
121
+
122
+    /**
123
+     * Retrieve the response from url and sets the response.
124
+     *
125
+     * @param string $url The url to retrieve.
126
+     *
127
+     * @return false|array True on success and false on failure.
128
+     * @since 3.18.0
129
+     *
130
+     */
131
+    private static function get_response( $url ) {
132
+        // Request the remote file.
133
+        $response = wp_remote_get( $url );
134
+
135
+        // Bail out if the response is not ok.
136
+        if (
137
+            is_wp_error( $response )
138
+            || 200 !== (int) $response['response']['code']
139
+            || ! isset( $response['body'] )
140
+        ) {
141
+            wl_write_log( "save_image_from_url : error fetching image $url \n" );
142
+
143
+            return false;
144
+        }
145
+
146
+        // Set the response.
147
+        return $response;
148
+    }
149 149
 
150 150
 }
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -18,11 +18,11 @@  discard block
 block discarded – undo
18 18
 	 * @since 3.18.0
19 19
 	 * @since 3.23.4 the function may return a WP_Error.
20 20
 	 */
21
-	public static function save_from_url( $url ) {
21
+	public static function save_from_url($url) {
22 22
 
23 23
 		// Required for REST API calls
24
-		if ( ! function_exists( 'WP_Filesystem' ) ) {
25
-			require_once( ABSPATH . 'wp-admin/includes/file.php' );
24
+		if ( ! function_exists('WP_Filesystem')) {
25
+			require_once(ABSPATH.'wp-admin/includes/file.php');
26 26
 		}
27 27
 
28 28
 		// Load `WP_Filesystem`.
@@ -30,51 +30,51 @@  discard block
 block discarded – undo
30 30
 		global $wp_filesystem;
31 31
 
32 32
 		// Parse the url.
33
-		$parts = wp_parse_url( $url );
33
+		$parts = wp_parse_url($url);
34 34
 
35 35
 		// Get the bare filename (filename w/o the extension).
36
-		$basename = str_replace( DIRECTORY_SEPARATOR, '_', rawurldecode(
37
-			pathinfo( $parts['path'], PATHINFO_FILENAME )
38
-		) );
36
+		$basename = str_replace(DIRECTORY_SEPARATOR, '_', rawurldecode(
37
+			pathinfo($parts['path'], PATHINFO_FILENAME)
38
+		));
39 39
 
40 40
 		// Get the base dir.
41 41
 		$wp_upload_dir = wp_upload_dir();
42 42
 
43 43
 		// Set the upload directory and URL.
44
-		$upload_dir = $wp_upload_dir['basedir'] . '/wl' . $wp_upload_dir['subdir'];
45
-		$upload_url = $wp_upload_dir['baseurl'] . '/wl' . $wp_upload_dir['subdir'];
44
+		$upload_dir = $wp_upload_dir['basedir'].'/wl'.$wp_upload_dir['subdir'];
45
+		$upload_url = $wp_upload_dir['baseurl'].'/wl'.$wp_upload_dir['subdir'];
46 46
 
47 47
 		// Get the full path to the local filename.
48
-		$image_full_path = $upload_dir . '/' . $basename;
49
-		$image_full_url  = $upload_url . '/' . $basename;
48
+		$image_full_path = $upload_dir.'/'.$basename;
49
+		$image_full_url  = $upload_url.'/'.$basename;
50 50
 
51 51
 		// Create custom directory and bail on failure.
52
-		if ( ! wp_mkdir_p( $upload_dir ) ) {
53
-			Wordlift_Log_Service::get_logger( 'Wordlift_Remote_Image_Service' )
54
-			                    ->warn( "save_image_from_url : failed creating upload dir $upload_dir \n" );
52
+		if ( ! wp_mkdir_p($upload_dir)) {
53
+			Wordlift_Log_Service::get_logger('Wordlift_Remote_Image_Service')
54
+			                    ->warn("save_image_from_url : failed creating upload dir $upload_dir \n");
55 55
 
56
-			return new WP_Error( 'image_error', "save_image_from_url : failed creating upload dir $upload_dir \n" );
56
+			return new WP_Error('image_error', "save_image_from_url : failed creating upload dir $upload_dir \n");
57 57
 		};
58 58
 
59
-		$response = self::get_response( $url );
59
+		$response = self::get_response($url);
60 60
 
61 61
 		// Bail if the response is not set.
62
-		if ( false === $response ) {
63
-			Wordlift_Log_Service::get_logger( 'Wordlift_Remote_Image_Service' )
64
-			                    ->warn( "save_image_from_url : failed to fetch the response from: $url \n" );
62
+		if (false === $response) {
63
+			Wordlift_Log_Service::get_logger('Wordlift_Remote_Image_Service')
64
+			                    ->warn("save_image_from_url : failed to fetch the response from: $url \n");
65 65
 
66
-			return new WP_Error( 'image_error', "save_image_from_url : failed to fetch the response from: $url \n" );
66
+			return new WP_Error('image_error', "save_image_from_url : failed to fetch the response from: $url \n");
67 67
 		}
68 68
 
69 69
 		// Get the content type of response.
70
-		$content_type = wp_remote_retrieve_header( $response, 'content-type' );
70
+		$content_type = wp_remote_retrieve_header($response, 'content-type');
71 71
 
72 72
 		// Get the file extension.
73
-		$extension = self::get_extension_from_content_type( $content_type );
73
+		$extension = self::get_extension_from_content_type($content_type);
74 74
 
75 75
 		// Bail if the content type is not supported.
76
-		if ( empty( $extension ) ) {
77
-			return new WP_Error( 'image_error', 'Unsupported content type.' );
76
+		if (empty($extension)) {
77
+			return new WP_Error('image_error', 'Unsupported content type.');
78 78
 		}
79 79
 
80 80
 		// Complete the local filename.
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 		$image_full_url  .= $extension;
83 83
 
84 84
 		// Store the data locally.
85
-		$wp_filesystem->put_contents( $image_full_path, wp_remote_retrieve_body( $response ) );
85
+		$wp_filesystem->put_contents($image_full_path, wp_remote_retrieve_body($response));
86 86
 
87 87
 		// Return the path.
88 88
 		return array(
@@ -102,10 +102,10 @@  discard block
 block discarded – undo
102 102
 	 * @since 3.18.0
103 103
 	 *
104 104
 	 */
105
-	private static function get_extension_from_content_type( $content_type ) {
105
+	private static function get_extension_from_content_type($content_type) {
106 106
 
107 107
 		// Return the extension if match.
108
-		switch ( $content_type ) {
108
+		switch ($content_type) {
109 109
 			case 'image/jpeg':
110 110
 			case 'image/jpg':
111 111
 				return '.jpg';
@@ -128,17 +128,17 @@  discard block
 block discarded – undo
128 128
 	 * @since 3.18.0
129 129
 	 *
130 130
 	 */
131
-	private static function get_response( $url ) {
131
+	private static function get_response($url) {
132 132
 		// Request the remote file.
133
-		$response = wp_remote_get( $url );
133
+		$response = wp_remote_get($url);
134 134
 
135 135
 		// Bail out if the response is not ok.
136 136
 		if (
137
-			is_wp_error( $response )
137
+			is_wp_error($response)
138 138
 			|| 200 !== (int) $response['response']['code']
139
-			|| ! isset( $response['body'] )
139
+			|| ! isset($response['body'])
140 140
 		) {
141
-			wl_write_log( "save_image_from_url : error fetching image $url \n" );
141
+			wl_write_log("save_image_from_url : error fetching image $url \n");
142 142
 
143 143
 			return false;
144 144
 		}
Please login to merge, or discard this patch.