Поля ответа GET products/{id}/images. */ public static function state( WC_Product $product ): array { $main_id = (int) $product->get_image_id( 'edit' ); $gallery_ids = array_map( 'intval', $product->get_gallery_image_ids( 'edit' ) ); $images = Attachment_Info::image_ids( array_merge( $main_id > 0 ? array( $main_id ) : array(), $gallery_ids ), Images_Layout::MAX_GALLERY + 1 ); $main = $main_id > 0 && in_array( $main_id, $images, true ) ? $main_id : 0; $gallery = array_values( array_filter( $images, static fn ( int $id ): bool => $id !== $main ) ); $made = Image_Importer::image_ids( array_merge( $main > 0 ? array( $main ) : array(), $gallery ) ); $describe = static fn ( int $attachment_id ): array => self::describe( $attachment_id, isset( $made[ $attachment_id ] ) ); $variations = array_map( static fn ( array $row ): array => array( 'id' => $row['id'], 'label' => $row['label'], 'attachmentId' => $row['attachmentId'], 'thumbUrl' => $row['attachmentId'] > 0 ? Attachment_Info::thumb_url( (int) $row['attachmentId'] ) : '', ), Product_State::variation_rows( $product ) ); $total = ( $main > 0 ? 1 : 0 ) + count( $gallery ); $count_texts = array(); for ( $n = 0; $n <= $total; $n++ ) { $count_texts[] = sprintf( /* translators: %s: number of photos. */ _n( '%s photo', '%s photos', $n, 'aimodelka' ), number_format_i18n( $n ) ); } Logger::info( 'Product images listed for the photos popup', array( 'product_id' => $product->get_id(), 'main_image' => $main, 'gallery' => count( $gallery ), 'variations' => count( $variations ), ) ); return array( 'main' => $main > 0 ? $describe( $main ) : null, 'gallery' => array_map( $describe, $gallery ), 'variations' => $variations, 'countTexts' => $count_texts, 'limits' => array( 'maxGallery' => Images_Layout::MAX_GALLERY ), // Строка «N photos in the product · дата» для блока aiModelka в редакторе: после // записи из окошка число фото aiModelka в товаре могло измениться. '' — фото // aiModelka в товар ещё не сохранялись. 'savedText' => Saved_Photos::product_box_text( $product->get_id() ), ); } /** * Вложения, которые сейчас у товара: изображение, галерея и изображения вариаций — только * картинки из медиатеки. Это и есть набор, из которого окошко вправе собирать новую * карточку (Images_Layout::check). * * @param WC_Product $product Товар. * @return int[] */ public static function known_ids( WC_Product $product ): array { $ids = array_merge( array( (int) $product->get_image_id( 'edit' ) ), array_map( 'intval', $product->get_gallery_image_ids( 'edit' ) ), array_map( static fn ( array $row ): int => $row['attachmentId'], Product_State::variation_rows( $product ) ) ); return Attachment_Info::image_ids( array_filter( $ids ), count( $ids ) ); } /** * Id вариаций товара — для проверки, что окошко называет вариации этого товара. * * @param WC_Product $product Товар. * @return int[] */ public static function variation_ids( WC_Product $product ): array { return array_map( static fn ( array $row ): int => $row['id'], Product_State::variation_rows( $product ) ); } /** * Записывает новый порядок карточки — уже проверенный (Images_Layout::check). * * Товар сохраняется, только если изображение или галерея изменились; вариации — только те, * у которых изображение другое: лишние записи дёргают хуки WooCommerce и кеши зря. * Счётчик «N фото в товаре» (Admin\Saved_Photos) пересчитывается по новому составу * изображения и галереи; дата последнего сохранения не трогается — это перестановка, * а не сохранение фото из aiModelka. В конце — сброс кешей товара (Product_Caches), * иначе плагины кеша и галереи показывали бы на странице прежний порядок. * * @param WC_Product $product Товар. * @param int $main_id Новое изображение товара. * @param int[] $gallery_ids Новая галерея по порядку. * @param array $variation_images Вариация → вложение; 0 — снять изображение. * @return array Новое состояние — как state(). */ public static function apply( WC_Product $product, int $main_id, array $gallery_ids, array $variation_images ): array { $product_id = $product->get_id(); $old_main = (int) $product->get_image_id( 'edit' ); $old_gallery = array_map( 'intval', $product->get_gallery_image_ids( 'edit' ) ); if ( $main_id !== $old_main || $gallery_ids !== $old_gallery ) { $product->set_image_id( $main_id ); $product->set_gallery_image_ids( $gallery_ids ); $product->save(); } $changed_variations = array(); foreach ( $variation_images as $variation_id => $attachment_id ) { $variation = wc_get_product( $variation_id ); if ( ! $variation || ! $variation->is_type( 'variation' ) || (int) $variation->get_parent_id() !== $product_id ) { continue; } if ( (int) $variation->get_image_id( 'edit' ) === $attachment_id ) { continue; } // Пустая строка — «изображения нет», как записывает сам WooCommerce. $variation->set_image_id( $attachment_id > 0 ? $attachment_id : '' ); $variation->save(); $changed_variations[] = $variation_id; } $saved_count = count( Image_Importer::made_by_aimodelka( array_merge( array( $main_id ), $gallery_ids ) ) ); update_post_meta( $product_id, Meta::SAVED_COUNT, $saved_count ); // Страница товара должна показать новый порядок сразу, а не после «Обновить» в редакторе. Product_Caches::clear( $product_id ); Logger::info( 'Product images rearranged from the photos popup', array( 'product_id' => $product_id, 'main_image' => $main_id, 'gallery' => $gallery_ids, 'variations' => $changed_variations, 'aimodelka_photos' => $saved_count, ) ); // Состояние — по свежему товару: объект в руках уже записан, но вариации читаются заново. $fresh = wc_get_product( $product_id ); return self::state( $fresh ? $fresh : $product ); } /** * Что окошко знает о вложении. * * @param int $attachment_id Id вложения. * @param bool $made_by_aimodelka Сделано ли фото aiModelka. * @return array{attachmentId: int, thumbUrl: string, fileName: string, madeByAimodelka: bool, width: int, height: int} */ private static function describe( int $attachment_id, bool $made_by_aimodelka ): array { $meta = wp_get_attachment_metadata( $attachment_id ); return array( 'attachmentId' => $attachment_id, 'thumbUrl' => Attachment_Info::thumb_url( $attachment_id ), 'fileName' => Attachment_Info::file_name( $attachment_id ), 'madeByAimodelka' => $made_by_aimodelka, 'width' => is_array( $meta ) ? (int) ( $meta['width'] ?? 0 ) : 0, 'height' => is_array( $meta ) ? (int) ( $meta['height'] ?? 0 ) : 0, ); } }