a in seconds from the current time, used if an object is retrieved from datastore and cached. * @param callable|null $get_from_datastore_callback Optional callback to get the object if it's not cached, it must return an object/array or null. * @return object|array|null Cached object, or null if it's not cached and can't be retrieved from datastore or via callback. * @throws CacheException Invalid id parameter. */ public function get( $id, int $expiration = self::DEFAULT_EXPIRATION, callable $get_from_datastore_callback = null ) { if ( ! is_string( $id ) && ! is_int( $id ) ) { throw new CacheException( "Object id must be an int or a string for 'get'", $this ); } $this->verify_expiration_value( $expiration ); $data = $this->get_cache_engine()->get_cached_object( $id, $this->get_object_type() ); if ( null === $data ) { $object = null; if ( $get_from_datastore_callback ) { $object = $get_from_datastore_callback( $id ); } if ( null === $object ) { return null; } $this->set( $object, $id, $expiration ); $data = $this->last_cached_data; } return $data; } /** * Remove an object from the cache. * * @param int|string $id The id of the object to remove. * @return bool True if the object is removed from the cache successfully, false otherwise (because the object wasn't cached or for other reason). */ public function remove( $id ): bool { return $this->get_cache_engine()->delete_cached_object( $id, $this->get_object_type() ); } /** * Remove all the objects from the cache. * * @return bool True on success, false on error. */ public function flush(): bool { return $this->get_cache_engine()->delete_cache_group( $this->get_object_type() ); } /** * Is a given object cached? * * @param int|string $id The id of the object to check. * @return bool True if there's a cached object with the specified id. */ public function is_cached( $id ): bool { return $this->get_cache_engine()->is_cached( $id, $this->get_object_type() ); } /** * Get the id of an object. This is used by 'set' when a null id is passed. * If the object id can't be determined the method must return null. * * @param array|object $object The object to get the id for. * @return int|string|null */ abstract protected function get_object_id( $object ); /** * Validate an object before it's cached. * * @param array|object $object Object to validate. * @return array|null An array with validation error messages, null or an empty array if there are no errors. */ abstract protected function validate( $object ): ?array; /** * Get the instance of the cache engine to use. * * @return CacheEngine */ protected function get_cache_engine_instance(): CacheEngine { return wc_get_container()->get( WPCacheEngine::class ); } /** * Get a random string to be used to compose the cache key prefix. * It should return a different string each time. * * @return string */ protected function get_random_string(): string { return dechex( microtime( true ) * 1000 ) . bin2hex( random_bytes( 8 ) ); } }