| 1 |
<?php |
| 2 |
/** |
| 3 |
* WCPOS sync read surface. |
| 4 |
* |
| 5 |
* @package WCPOS\WooCommercePOS\Sync |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WCPOS\WooCommercePOS\Sync; |
| 9 |
|
| 10 |
/** |
| 11 |
* Serves medium product images across catalog read surfaces. |
| 12 |
*/ |
| 13 |
final class Product_Images { |
| 14 |
/** |
| 15 |
* THE image augmentation, registered ONCE with {@see Augmentation_Pipeline} |
| 16 |
* and projected onto both read lanes: replace full-size product image URLs |
| 17 |
* with their WordPress medium size. |
| 18 |
* |
| 19 |
* @param mixed $payload Serialized product record. |
| 20 |
* @param null|mixed $object Product object, when the lane has one loaded. |
| 21 |
* @param null|mixed $request Request context. |
| 22 |
*/ |
| 23 |
public static function augment_record( $payload, $object = null, $request = null ) { |
| 24 |
if ( ! \is_array( $payload ) ) { |
| 25 |
return $payload; |
| 26 |
} |
| 27 |
|
| 28 |
return self::downsize_images( $payload ); |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Replace each image source with its medium URL when available. |
| 33 |
* |
| 34 |
* @param array $record Product response record. |
| 35 |
*/ |
| 36 |
private static function downsize_images( array $record ): array { |
| 37 |
// A VARIATION carries `image` (singular) — WooCommerce's variations controller has no |
| 38 |
// `images` array, and its `src` is the FULL SIZE file. Without this branch the medium |
| 39 |
// downsizing silently stops applying to variations and every till pulls full-resolution |
| 40 |
// originals (#1710). Mirrors what the v1 lane has always done in |
| 41 |
// `API\V1\Product_Variations_Controller::wcpos_variation_response()`. |
| 42 |
if ( isset( $record['image'] ) && \is_array( $record['image'] ) && isset( $record['image']['id'] ) ) { |
| 43 |
$medium = image_downsize( (int) $record['image']['id'], 'medium' ); |
| 44 |
if ( $medium ) { |
| 45 |
$record['image']['src'] = $medium[0]; |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
if ( ! isset( $record['images'] ) || ! \is_array( $record['images'] ) ) { |
| 50 |
return $record; |
| 51 |
} |
| 52 |
foreach ( $record['images'] as $index => $entry ) { |
| 53 |
if ( ! \is_array( $entry ) || ! isset( $entry['id'] ) || 0 >= (int) $entry['id'] ) { |
| 54 |
continue; |
| 55 |
} |
| 56 |
$medium = image_downsize( (int) $entry['id'], 'medium' ); |
| 57 |
if ( $medium ) { |
| 58 |
$entry['src'] = $medium[0]; |
| 59 |
$record['images'][ $index ] = $entry; |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
return $record; |
| 64 |
} |
| 65 |
} |
| 66 |
|