SizeResolver.php
75 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Helper\Image; |
| 6 | |
| 7 | use AC\Helper\Creatable; |
| 8 | |
| 9 | class SizeResolver extends Creatable |
| 10 | { |
| 11 | /** |
| 12 | * @param string|array $size |
| 13 | */ |
| 14 | public function get_dimensions($size): array |
| 15 | { |
| 16 | if (is_string($size)) { |
| 17 | $sizes = $this->get_sizes_by_name($size); |
| 18 | |
| 19 | if ($sizes) { |
| 20 | return [ |
| 21 | (int)$sizes['width'], |
| 22 | (int)$sizes['height'], |
| 23 | ]; |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | $pair = $this->normalize_pair($size); |
| 28 | |
| 29 | if ($pair !== null) { |
| 30 | return $pair; |
| 31 | } |
| 32 | |
| 33 | return [60, 60]; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Normalize a numeric width/height pair (e.g. [300, 200]) or return null when the input is not such a pair. |
| 38 | * |
| 39 | * @param string|array $size |
| 40 | */ |
| 41 | public function normalize_pair($size): ?array |
| 42 | { |
| 43 | if ( |
| 44 | is_array($size) |
| 45 | && isset($size[0], $size[1]) |
| 46 | && is_numeric($size[0]) |
| 47 | && is_numeric($size[1]) |
| 48 | && $size[0] > 0 |
| 49 | && $size[1] > 0 |
| 50 | ) { |
| 51 | return [ |
| 52 | (int)$size[0], |
| 53 | (int)$size[1], |
| 54 | ]; |
| 55 | } |
| 56 | |
| 57 | return null; |
| 58 | } |
| 59 | |
| 60 | public function get_sizes_by_name(string $name): array |
| 61 | { |
| 62 | $available_sizes = wp_get_additional_image_sizes(); |
| 63 | |
| 64 | foreach (['thumbnail', 'medium', 'large'] as $key) { |
| 65 | $available_sizes[$key] = [ |
| 66 | 'width' => (int)get_option($key . '_size_w'), |
| 67 | 'height' => (int)get_option($key . '_size_h'), |
| 68 | ]; |
| 69 | } |
| 70 | |
| 71 | return $available_sizes[$name] ?? []; |
| 72 | } |
| 73 | |
| 74 | } |
| 75 |