snapshots = $snapshots ?? new SnapshotStore(); $this->attachments = $attachments ?? new AttachmentContextBuilder(); } /** * @inheritDoc */ public function findings( int $product_id, WC_Product $product, array $definition ): array { $images = $this->attachments->imagesForProduct( $product ); if ( empty( $images ) ) { return array(); } $max_chars = isset( $definition['structure']['maxChars'] ) ? (int) $definition['structure']['maxChars'] : 125; $missing = 0; $too_long = 0; $image_of = 0; foreach ( $images as $image ) { $attachment_id = (int) ( $image['attachmentId'] ?? 0 ); $alt = trim( (string) ( $this->snapshots->readCurrentFieldValue( $product_id, 'image_alt', $attachment_id ) ?? '' ) ); if ( '' === $alt ) { $missing++; continue; } if ( TextMetrics::charCount( $alt ) > $max_chars ) { $too_long++; } if ( 1 === preg_match( '/^image\s+of\b/i', $alt ) ) { $image_of++; } } $findings = array(); if ( $missing > 0 ) { $findings[] = array( 'code' => 'alt_missing', 'severity' => 'warning', 'field' => 'image_alt', /* translators: %d: number of images with no alt text. */ 'message' => sprintf( _n( '%d image has no alt text.', '%d images have no alt text.', $missing, 'ai-product-tools' ), $missing ), 'label' => __( 'missing alt text', 'ai-product-tools' ), 'measured' => $missing, ); } if ( $too_long > 0 ) { $findings[] = array( 'code' => 'alt_too_long', 'severity' => 'warning', 'field' => 'image_alt', /* translators: %1$d: number of images with alt text over the limit. %2$d: the template's allowed character count. */ 'message' => sprintf( _n( '%1$d image\'s alt text is over this template\'s %2$d character limit.', '%1$d images\' alt text is over this template\'s %2$d character limit.', $too_long, 'ai-product-tools' ), $too_long, $max_chars ), 'label' => __( 'alt text too long', 'ai-product-tools' ), 'measured' => $too_long, 'limit' => $max_chars, ); } if ( $image_of > 0 ) { $findings[] = array( 'code' => 'alt_image_of', 'severity' => 'info', 'field' => 'image_alt', /* translators: %d: number of images whose alt text starts with "Image of". */ 'message' => sprintf( _n( '%d image\'s alt text starts with "Image of".', '%d images\' alt text starts with "Image of".', $image_of, 'ai-product-tools' ), $image_of ), 'label' => __( 'alt text starts with "image of"', 'ai-product-tools' ), 'measured' => $image_of, ); } return $findings; } /** * @inheritDoc */ public function provenanceFieldMap(): array { return array( 'image_alt' => 'image_alt' ); } }