the descriptionFilter value the generators accept. * * @var array */ public const GAP_FILTERS = array( 'description' => 'without_full', 'short_description' => 'without_short', 'tags' => 'without_tags', 'seo_meta' => 'without_seo_meta', 'faq' => 'without_faq', ); /** @var bool */ private static $invalidated_this_request = false; /** @var callable */ private $clock; public function __construct( ?callable $clock = null ) { $this->clock = $clock ?? static function (): float { return microtime( true ); }; } /** * Returns the scan, from cache when fresh. A cached partial scan is not served * as is: the request counts the gaps it skipped, so repeated requests converge * on a complete scan. * * @return array|\WP_Error Payload per the catalog-scan contract, or an error. A failure is never cached. */ public function get_scan() { $cached = get_transient( self::CACHE_KEY ); $resume = null; if ( $this->is_valid_payload( $cached ) ) { if ( empty( $cached['partial'] ) ) { $cached['skipped'] = array(); $cached['stale'] = false; return $cached; } if ( isset( $cached['skipped'] ) && is_array( $cached['skipped'] ) ) { $resume = $cached; } } self::$invalidated_this_request = false; $fresh = $this->compute( $resume ); if ( is_array( $fresh ) ) { $ttl = $fresh['partial'] ? self::PARTIAL_TTL : self::FRESH_TTL; set_transient( self::CACHE_KEY, $fresh, $ttl ); if ( ! $fresh['partial'] ) { set_transient( self::LAST_GOOD_KEY, $fresh, WEEK_IN_SECONDS ); } return $fresh; } $last_good = get_transient( self::LAST_GOOD_KEY ); if ( $this->is_valid_payload( $last_good ) ) { $last_good['skipped'] = array(); $last_good['stale'] = true; return $last_good; } return $fresh; } /** * Returns the best scan that is already stored, and never computes or queries the catalog. * * Order: a complete fresh scan, then the last complete scan, then a partial scan. * A scan older than CACHED_MAX_AGE is not served. * * @return array|null Payload per the catalog-scan contract, or null when nothing usable is stored. */ public function get_cached_scan(): ?array { $fresh = get_transient( self::CACHE_KEY ); $last_good = get_transient( self::LAST_GOOD_KEY ); if ( $this->is_servable( $fresh ) && empty( $fresh['partial'] ) ) { $fresh['skipped'] = array(); $fresh['stale'] = false; return $fresh; } if ( $this->is_servable( $last_good ) && empty( $last_good['partial'] ) ) { $last_good['skipped'] = array(); $last_good['stale'] = true; return $last_good; } if ( $this->is_servable( $fresh ) ) { $fresh['stale'] = false; return $fresh; } return null; } /** * @param mixed $payload Value read back from a transient. */ private function is_servable( $payload ): bool { if ( ! $this->is_valid_payload( $payload ) || ! is_array( $payload['gaps'] ) ) { return false; } $scanned_at = strtotime( (string) $payload['scannedAt'] ); return false !== $scanned_at && time() - $scanned_at <= self::CACHED_MAX_AGE; } /** * Runs the counts. Returns an error when any count query fails. * * Every run counts at least one gap that has no count yet, even when the total * already used up the budget, so a slow catalog still makes progress. A gap that * is not counted because the budget ran out is listed in `skipped`; a gap that * cannot be counted at all (no supported SEO plugin) stays null and is not. * * @param array|null $resume A cached partial payload to complete: its total and counts are reused and only its skipped gaps are counted. * @return array|\WP_Error */ private function compute( ?array $resume = null ) { $started = (float) call_user_func( $this->clock ); $budget = (float) apply_filters( 'aipt_catalog_scan_budget_seconds', self::DEFAULT_BUDGET_SECONDS ); $gaps = array_fill_keys( array_keys( self::GAP_FILTERS ), null ); if ( null === $resume ) { $total = ( new ProductFilterBuilder() )->countProducts(); $pending = self::GAP_FILTERS; } else { $total = (int) $resume['total']; $pending = array_intersect_key( self::GAP_FILTERS, array_flip( $resume['skipped'] ) ); foreach ( array_diff_key( self::GAP_FILTERS, $pending ) as $gap => $filter ) { $gaps[ $gap ] = isset( $resume['gaps'][ $gap ] ) ? (int) $resume['gaps'][ $gap ] : null; } } if ( null === $total ) { return $this->failure(); } $seo_plugin = SeoPluginDetector::detect(); $skipped = array(); $counted = 0; foreach ( $pending as $gap => $filter ) { if ( 'seo_meta' === $gap && null === SeoPluginDetector::get_description_gap_source() ) { continue; } $elapsed = (float) call_user_func( $this->clock ) - $started; if ( $counted > 0 && $elapsed > $budget ) { $skipped[] = $gap; continue; } $count = ( new ProductFilterBuilder() )->contentFilters( array( $filter ) )->countProducts(); if ( null === $count ) { return $this->failure(); } $gaps[ $gap ] = $count; ++$counted; } return array( 'total' => $total, 'gaps' => $gaps, 'skipped' => $skipped, 'seoPlugin' => null === $seo_plugin ? null : array( 'slug' => (string) $seo_plugin['plugin_slug'], 'name' => (string) $seo_plugin['plugin_name'], ), 'scannedAt' => gmdate( 'Y-m-d\TH:i:s\Z' ), 'stale' => false, 'partial' => array() !== $skipped, ); } private function failure(): \WP_Error { return new \WP_Error( self::ERROR_CODE, __( 'The catalog scan could not be completed. Please try again.', 'ai-product-tools' ), array( 'status' => 500 ) ); } /** * @param mixed $payload Value read back from a transient. */ private function is_valid_payload( $payload ): bool { return is_array( $payload ) && isset( $payload['total'], $payload['gaps'], $payload['scannedAt'] ); } /** * Drops the fresh cache so the next request rescans. The last good scan stays as the stale fallback. */ public static function invalidate(): void { if ( self::$invalidated_this_request ) { return; } delete_transient( self::CACHE_KEY ); self::$invalidated_this_request = true; } /** * Invalidates on product writes and on every input the counts read. Safe to call more than once. */ public static function register_invalidation_hooks(): void { if ( has_action( 'save_post_product', array( __CLASS__, 'invalidate' ) ) ) { return; } add_action( 'save_post_product', array( __CLASS__, 'invalidate' ) ); add_action( 'trashed_post', array( __CLASS__, 'on_post_changed' ) ); add_action( 'untrashed_post', array( __CLASS__, 'on_post_changed' ) ); add_action( 'deleted_post', array( __CLASS__, 'invalidate' ) ); add_action( 'added_post_meta', array( __CLASS__, 'on_meta_changed' ), 10, 3 ); add_action( 'updated_post_meta', array( __CLASS__, 'on_meta_changed' ), 10, 3 ); add_action( 'deleted_post_meta', array( __CLASS__, 'on_meta_changed' ), 10, 3 ); add_action( 'set_object_terms', array( __CLASS__, 'on_terms_changed' ), 10, 4 ); add_action( 'deleted_term_relationships', array( __CLASS__, 'on_relationships_deleted' ), 10, 3 ); add_action( 'activated_plugin', array( __CLASS__, 'invalidate' ) ); add_action( 'deactivated_plugin', array( __CLASS__, 'invalidate' ) ); add_action( 'aipt_product_filter_cache_flushed', array( __CLASS__, 'invalidate' ) ); } /** * Trash and restore: only products matter. * * @param int $post_id Post that was trashed or restored. */ public static function on_post_changed( $post_id ): void { if ( 'product' === get_post_type( (int) $post_id ) ) { self::invalidate(); } } /** * @param mixed $meta_id Meta row id or ids. * @param int $object_id Post id. * @param string $meta_key Meta key. */ public static function on_meta_changed( $meta_id, $object_id, $meta_key ): void { if ( in_array( $meta_key, self::watched_meta_keys(), true ) ) { self::invalidate(); } } /** * @param int $object_id Post id. * @param mixed $terms Terms as passed to wp_set_object_terms(). * @param mixed $tt_ids Term taxonomy ids. * @param string $taxonomy Taxonomy name. */ public static function on_terms_changed( $object_id, $terms = null, $tt_ids = null, $taxonomy = '' ): void { if ( 'product_tag' === $taxonomy ) { self::invalidate(); } } /** * @param int $object_id Post id. * @param mixed $tt_ids Term taxonomy ids. * @param string $taxonomy Taxonomy name. */ public static function on_relationships_deleted( $object_id, $tt_ids = null, $taxonomy = '' ): void { if ( 'product_tag' === $taxonomy ) { self::invalidate(); } } /** * @return string[] */ private static function watched_meta_keys(): array { return array_merge( array( '_aipt_faq_data' ), SeoPluginDetector::get_description_meta_keys() ); } }