prefix . 'tp_memory'; } public static function hash( string $text, string $source, string $target ): string { return md5( $source . '|' . $target . '|' . $text ); } /** * @param string[] $texts Source texts. * @return array source text => translation for hits. */ public static function lookup( array $texts, string $source, string $target ): array { if ( ! $texts ) { return array(); } global $wpdb; $by_hash = array(); foreach ( $texts as $t ) { $by_hash[ self::hash( $t, $source, $target ) ] = $t; } $out = array(); foreach ( array_chunk( array_keys( $by_hash ), 500 ) as $chunk ) { $in = implode( ',', array_fill( 0, count( $chunk ), '%s' ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT hash, translation FROM %i WHERE hash IN ($in)", array_merge( array( $wpdb->tp_memory ), $chunk ) ), ARRAY_A ); // phpcs:ignore WordPress.DB foreach ( $rows as $r ) { $out[ $by_hash[ $r['hash'] ] ] = $r['translation']; } } if ( $out ) { $hit = array_map( function ( $t ) use ( $source, $target ) { return self::hash( $t, $source, $target ); }, array_keys( $out ) ); $in = implode( ',', array_fill( 0, count( $hit ), '%s' ) ); $wpdb->query( $wpdb->prepare( "UPDATE %i SET hits = hits + 1 WHERE hash IN ($in)", array_merge( array( $wpdb->tp_memory ), $hit ) ) ); // phpcs:ignore WordPress.DB } return $out; } /** * @param array $pairs source text => translation. */ public static function save( array $pairs, string $source, string $target ): void { if ( ! $pairs ) { return; } global $wpdb; $now = current_time( 'mysql', true ); foreach ( $pairs as $src => $tr ) { $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->prepare( "INSERT INTO %i (hash, source_lang, target_lang, source, translation, hits, created_at) VALUES (%s, %s, %s, %s, %s, 0, %s) ON DUPLICATE KEY UPDATE translation = VALUES(translation)", $wpdb->tp_memory, self::hash( (string) $src, $source, $target ), $source, $target, (string) $src, (string) $tr, $now ) ); } } public static function forget( array $texts, string $source, string $target ): void { global $wpdb; foreach ( $texts as $t ) { $wpdb->delete( self::table(), array( 'hash' => self::hash( $t, $source, $target ) ) ); // phpcs:ignore WordPress.DB } } public static function stats(): array { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT COUNT(*) entries, COALESCE(SUM(hits),0) hits, COALESCE(SUM(CHAR_LENGTH(source) * hits),0) saved_chars FROM %i', $wpdb->tp_memory ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery return array( 'entries' => (int) $row['entries'], 'hits' => (int) $row['hits'], 'saved_chars' => (int) $row['saved_chars'], ); } public static function clear(): void { global $wpdb; $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', $wpdb->tp_memory ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } }