From 33936fafe1e9a03817f4594e7ac379df5f50b7a4 Mon Sep 17 00:00:00 2001 From: Manzoor Wani Date: Thu, 19 Dec 2024 10:49:59 +0530 Subject: [PATCH] Create connections class for caching --- .../publicize/src/class-connections.php | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 projects/packages/publicize/src/class-connections.php diff --git a/projects/packages/publicize/src/class-connections.php b/projects/packages/publicize/src/class-connections.php new file mode 100644 index 0000000000000..36de3b630cdf8 --- /dev/null +++ b/projects/packages/publicize/src/class-connections.php @@ -0,0 +1,78 @@ +is_wpcom_simple(); + + if ( $is_wpcom ) { + // We don't need to cache connections for simple sites. + return Connections_Controller::get_connections( $run_tests ); + } + + $clear_cache = $args['clear_cache'] ?? false; + + if ( $clear_cache || $run_tests ) { + self::clear_transient(); + } + + $connections = get_transient( self::CONNECTIONS_TRANSIENT ); + + // This can be an empty array, so we need to check for false. + if ( false === $connections ) { + $connections = self::fetch_and_cache_connections( $run_tests ); + } + + return $connections; + } + + /** + * Fetch connections from the REST API and cache them. + * + * @param bool $run_tests Whether to run connection tests. + * + * @return array + */ + public static function fetch_and_cache_connections( $run_tests = false ) { + $connections = Connections_Controller::get_connections( $run_tests ); + + if ( is_array( $connections ) ) { + set_transient( self::CONNECTIONS_TRANSIENT, $connections, HOUR_IN_SECONDS * 4 ); + } + + return $connections; + } + + /** + * Delete the transient. + */ + public static function clear_transient() { + delete_transient( self::CONNECTIONS_TRANSIENT ); + } +}