*/ public const REQUIRED_SCOPES = [ 'contacts:write', 'campaigns:read', 'segments:read', 'orders:write', 'subscriptions:write', ]; /** * Dependency-closed request matching the exact scope set Aivie returns. * * @var list */ public const REQUESTED_SCOPES = [ 'contacts:read', 'contacts:write', 'campaigns:read', 'segments:read', 'orders:read', 'orders:write', 'subscriptions:read', 'subscriptions:write', ]; private SharedConnection $shared; private LegacyConnection $legacy; public function __construct(?SharedConnection $shared = null, ?LegacyConnection $legacy = null) { $this->shared = $shared ?? new SharedConnection(self::REQUIRED_SCOPES); $this->legacy = $legacy ?? new LegacyConnection(); } /** * Append WooCommerce scopes to the marketing plugin's fixed base contract. * * @param mixed $scopes Existing contributed scopes. * @return list */ public static function addRequiredScopes(mixed $scopes): array { $scopes = is_array($scopes) ? array_filter($scopes, 'is_string') : []; $scopes = array_filter( $scopes, static fn (string $scope): bool => ! in_array($scope, self::REQUESTED_SCOPES, true) ); return array_values(array_merge($scopes, self::REQUESTED_SCOPES)); } public function isConfigured(): bool { return $this->shared->isReady() || $this->legacy->isConfigured(); } public function baseUrl(): string { return $this->shared->isReady() ? $this->shared->baseUrl() : $this->legacy->baseUrl(); } public function source(): string { if ($this->shared->isReady()) { return 'shared'; } return $this->legacy->isConfigured() ? 'legacy' : 'none'; } /** * @return array{available: bool, connected: bool, ready: bool, settings_url: string} */ public function sharedStatus(): array { return [ 'available' => $this->shared->isAvailable(), 'connected' => $this->shared->isConnected(), 'ready' => $this->shared->isReady(), 'settings_url' => $this->shared->settingsUrl(), ]; } /** * Resolve credentials once, before an HTTP request is sent. * * @return array{base_url: string, access_token: string, source: string}|\WP_Error */ public function credentials(): array|\WP_Error { $sharedReady = $this->shared->isReady(); $sharedBaseUrl = $sharedReady ? rtrim($this->shared->baseUrl(), '/') : ''; $shared = $this->shared->credentials(); if (! is_wp_error($shared)) { return $shared; } // A temporary shared-token failure must never redirect a request to a // legacy connection belonging to another tenant. if ($sharedReady && $sharedBaseUrl !== rtrim($this->legacy->baseUrl(), '/')) { return $shared; } $legacy = $this->legacy->credentials(); if (! is_wp_error($legacy)) { return $legacy; } return $this->shared->isAvailable() ? $shared : $legacy; } }