key = $key; $this->taxonomy = $taxonomy; $this->byName = $byName; } /** * @return string */ public function key(): string { return $this->key; } /** * Term id => name. * * @param int $productId Product id. * @return array|null */ public function read( int $productId ) { $terms = wp_get_object_terms( $productId, $this->taxonomy, array( 'fields' => 'id=>name' ) ); if ( ! is_array( $terms ) ) { return null; } $read = array(); foreach ( $terms as $id => $name ) { $read[ (int) $id ] = (string) $name; } return $read; } /** * By name: order, case, entities and blanks do not matter. By id: order * does not. * * @param mixed $value Term id => name. * @return string */ public function fingerprint( $value ): string { $terms = is_array( $value ) ? $value : array(); if ( ! $this->byName ) { $ids = array_values( array_unique( array_map( 'intval', array_keys( $terms ) ) ) ); sort( $ids ); return md5( implode( ',', $ids ) ); } return self::nameFingerprint( array_values( $terms ) ); } /** * @param int $productId Product id. * @param mixed $value Term id => name. * @return void * @throws \RuntimeException When WordPress refused the terms. */ public function restore( int $productId, $value ): void { $ids = array_map( 'intval', array_keys( is_array( $value ) ? $value : array() ) ); $result = wp_set_object_terms( $productId, $ids, $this->taxonomy ); if ( is_wp_error( $result ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Caught and logged by the guard, never shown. throw new \RuntimeException( $result->get_error_message() ); } } /** * The tag fingerprint forms opened before 2.8.4 carry: keep it byte for * byte, so such a form is still guarded. * * @param array $names Tag names. * @return string */ public static function nameFingerprint( array $names ): string { $normalized = array(); foreach ( $names as $name ) { $name = trim( html_entity_decode( (string) $name, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ); if ( '' !== $name ) { $normalized[] = function_exists( 'mb_strtolower' ) ? mb_strtolower( $name, 'UTF-8' ) : strtolower( $name ); } } $normalized = array_values( array_unique( $normalized ) ); sort( $normalized ); return md5( implode( "\n", $normalized ) ); } }