settings_store->load(); $found = array(); if ( null !== $post && $this->is_checked( $post, $settings ) ) { $found = $this->wanted_addresses( $post->post_content, $settings ); } $this->query_runner->delete( $this->tables->uses(), array( 'post_id' => $post_id ) ); foreach ( $found as $address ) { $this->query_runner->insert( $this->tables->uses(), array( 'link_id' => $this->link_id_for( $address ), 'post_id' => $post_id, 'text' => $address->text, 'before_text' => $address->before, 'after_text' => $address->after, ) ); } $this->delete_unused_links(); $this->data_version->bump(); return count( $found ); } public function is_checked( WP_Post $post, Settings $settings ): bool { if ( self::READ_STATUS !== $post->post_status ) { return false; } $wanted_types = array_keys( array_filter( array( 'post' => $settings->check_posts, 'page' => $settings->check_pages, ) ) ); return in_array( $post->post_type, $wanted_types, true ); } /** @return list */ private function wanted_addresses( string $content, Settings $settings ): array { $wanted = array(); $found = $this->address_finder->find_in( $content ); foreach ( $found as $address ) { $is_link = LinkKind::Link === $address->kind; if ( $settings->check_media || $is_link ) { $wanted[] = $address; } } return $wanted; } private function link_id_for( FoundAddress $address ): int { $hash = md5( $address->url ); $existing_id = $this->query_runner->value( $this->query_runner->prepare( 'SELECT id FROM ' . $this->tables->links() . ' WHERE url_hash = %s', $hash ) ); if ( null !== $existing_id ) { return (int) $existing_id; } $is_internal = $this->address_rules->is_internal( $address->url ); return $this->query_runner->insert( $this->tables->links(), array( 'url' => $address->url, 'url_hash' => $hash, 'host' => $this->address_rules->host_of( $address->url ), 'kind' => $address->kind->value, 'internal' => $is_internal ? 1 : 0, ) ); } private function delete_unused_links(): void { $this->query_runner->execute( $this->query_runner->prepare( 'DELETE FROM ' . $this->tables->links() . ' WHERE outcome = %s AND NOT EXISTS ( SELECT 1 FROM ' . $this->tables->uses() . ' uses WHERE uses.link_id = ' . $this->tables->links() . '.id )', Outcome::Listed->value ) ); } }