slug_of( $missing_url ); if ( '' === $slug ) { return null; } $best_post_id = null; $best_distance = PHP_INT_MAX; foreach ( $this->candidates_for( $slug ) as $candidate ) { $post_name = RowColumns::text( $candidate, 'post_name' ); $distance = levenshtein( $slug, strtolower( $post_name ) ); if ( $distance < $best_distance ) { $best_distance = $distance; $best_post_id = RowColumns::whole_number( $candidate, 'ID' ); } } if ( null === $best_post_id ) { return null; } return $this->permalink_of( $best_post_id ); } private function slug_of( string $url ): string { $path = (string) wp_parse_url( $url, PHP_URL_PATH ); $segments = array_filter( explode( '/', $path ), static fn( string $segment ): bool => '' !== $segment ); return strtolower( (string) end( $segments ) ); } /** @return list> */ private function candidates_for( string $slug ): array { $words = explode( self::SLUG_SEPARATOR, $slug ); $longest_word = ''; foreach ( $words as $word ) { if ( strlen( $word ) > strlen( $longest_word ) ) { $longest_word = $word; } } $escaped_word = $this->query_runner->escape_like( $longest_word ); $pattern = '%' . $escaped_word . '%'; return $this->query_runner->rows( $this->query_runner->prepare( 'SELECT ID, post_name FROM ' . $this->posts_table . " WHERE post_status = 'publish' AND post_type IN ('post', 'page') AND post_name LIKE %s ORDER BY ID LIMIT %d", $pattern, self::CANDIDATE_LIMIT ) ); } private function permalink_of( int $post_id ): string|null { $permalink = get_permalink( $post_id ); return false === $permalink ? null : $permalink; } }