collaborators = $collaborators; } /** * Detector wired to the real WordPress and WooCommerce functions. */ public static function from_wordpress(): self { return new self( array( 'woocommerce_active' => static function (): bool { return class_exists( 'WooCommerce' ); }, // The Store API ships inside WooCommerce core (the StoreApi class, or the // older Blocks namespace). Its routes are NOT in the REST route table inside // wp-admin requests, where Connect runs, so presence is checked by class. 'store_api_available' => static function (): bool { return class_exists( 'Automattic\\WooCommerce\\StoreApi\\StoreApi' ) || class_exists( 'Automattic\\WooCommerce\\Blocks\\StoreApi\\StoreApi' ); }, 'rest_url' => static function ( string $path = '' ) { return rest_url( $path ); }, ) ); } /** * The Store API products URL, or null when this site has no catalog to offer. */ public function detect(): ?string { if ( ! $this->call( 'woocommerce_active' ) ) { return null; } if ( ! $this->call( 'store_api_available' ) ) { return null; } $url = $this->call( 'rest_url', self::STORE_PRODUCTS_ROUTE ); return self::is_https_url( $url ) ? $url : null; } /** * Whether the value is an https URL with a host and no credentials. * * @param mixed $url Candidate URL. */ private static function is_https_url( $url ): bool { if ( ! is_string( $url ) || '' === $url ) { return false; } $parts = wp_parse_url( $url ); if ( ! is_array( $parts ) || ! isset( $parts['scheme'], $parts['host'] ) || '' === $parts['host'] ) { return false; } if ( isset( $parts['user'] ) || isset( $parts['pass'] ) ) { return false; } return 'https' === strtolower( $parts['scheme'] ); } /** * Invoke a collaborator. * * @param string $name Collaborator name. * @param mixed ...$args Arguments. * @return mixed */ private function call( string $name, ...$args ) { return ( $this->collaborators[ $name ] )( ...$args ); } }