| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('ABSPATH')) die('No direct access allowed'); |
| 4 |
|
| 5 |
if (!class_exists('WPO_WebP_Convert')) : |
| 6 |
|
| 7 |
/** |
| 8 |
* Handles WebP conversion by iterating through available converters. |
| 9 |
*/ |
| 10 |
class WPO_WebP_Convert { |
| 11 |
|
| 12 |
/** |
| 13 |
* @var array<string> |
| 14 |
*/ |
| 15 |
private $converters = array(); |
| 16 |
|
| 17 |
private function __construct() { |
| 18 |
$webp_converters = WP_Optimize()->get_options()->get_option('webp_converters'); |
| 19 |
$this->converters = false === $webp_converters ? array() : $webp_converters; |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Singleton instance |
| 24 |
* |
| 25 |
* @return WPO_WebP_Convert |
| 26 |
*/ |
| 27 |
public static function get_instance(): self { |
| 28 |
static $instance = null; |
| 29 |
if (null === $instance) { |
| 30 |
$instance = new self(); |
| 31 |
} |
| 32 |
return $instance; |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Convert an image file to WebP format using the first available converter that succeeds. |
| 37 |
* |
| 38 |
* @param string $source Path of the source file. |
| 39 |
* @return bool True if conversion succeeded, false otherwise. |
| 40 |
*/ |
| 41 |
public function convert($source): bool { |
| 42 |
if (empty($this->converters)) { |
| 43 |
return false; |
| 44 |
} |
| 45 |
|
| 46 |
$destination = WPO_WebP_Utils::get_destination_path($source); |
| 47 |
|
| 48 |
return $this->attempt_conversion($source, $destination); |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Try each configured converter in order until one produces a WebP file. |
| 53 |
* |
| 54 |
* @param string $source Path of the source file. |
| 55 |
* @param string $destination Path of the destination file. |
| 56 |
* @return bool True if a converter produced the destination file. |
| 57 |
*/ |
| 58 |
private function attempt_conversion($source, $destination): bool { |
| 59 |
foreach ($this->converters as $converter) { |
| 60 |
WPO_WebP_Utils::perform_webp_conversion($converter, $source, $destination); |
| 61 |
if (is_file($destination)) { |
| 62 |
return true; |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
return false; |
| 67 |
} |
| 68 |
} |
| 69 |
endif; |
| 70 |
|