| 1 |
<?php |
| 2 |
|
| 3 |
namespace ElementorOne\Connect\Classes; |
| 4 |
|
| 5 |
use ElementorOne\Connect\Facade; |
| 6 |
|
| 7 |
if ( ! defined( 'ABSPATH' ) ) { |
| 8 |
exit; // Exit if accessed directly |
| 9 |
} |
| 10 |
|
| 11 |
/** |
| 12 |
* Class HomeUrl |
| 13 |
*/ |
| 14 |
class HomeUrl { |
| 15 |
|
| 16 |
/** |
| 17 |
* Facade instance |
| 18 |
* @var Facade |
| 19 |
*/ |
| 20 |
private Facade $facade; |
| 21 |
|
| 22 |
/** |
| 23 |
* HomeUrl constructor |
| 24 |
* @param Facade $facade |
| 25 |
*/ |
| 26 |
public function __construct( Facade $facade ) { |
| 27 |
$this->facade = $facade; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Ensure home URL is set |
| 32 |
* @return string|null |
| 33 |
*/ |
| 34 |
public function get_saved(): ?string { |
| 35 |
$data = $this->facade->data(); |
| 36 |
$home_url = $data->get_home_url(); |
| 37 |
|
| 38 |
if ( ! empty( $home_url ) ) { |
| 39 |
return (string) $home_url; |
| 40 |
} |
| 41 |
|
| 42 |
$home_url = $this->fetch_home_url(); |
| 43 |
if ( ! empty( $home_url ) ) { |
| 44 |
$data->set_home_url( $home_url ); |
| 45 |
} |
| 46 |
|
| 47 |
return $home_url; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Fetch home URL from client |
| 52 |
* @return string|null |
| 53 |
*/ |
| 54 |
private function fetch_home_url(): ?string { |
| 55 |
try { |
| 56 |
$client = $this->facade->service()->get_client(); |
| 57 |
$redirect_uri = $client['redirect_uris'][0] ?? ''; |
| 58 |
return self::extract_home_url( $redirect_uri ); |
| 59 |
} catch ( \Throwable $_th ) { |
| 60 |
return null; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Extract home URL from redirect URI |
| 66 |
* Removes the callback path (e.g., /wp-admin/admin.php?...) from the redirect URI |
| 67 |
* Example: https://example.com/wp-admin/admin.php?page=callback -> https://example.com |
| 68 |
* @param string $redirect_uri |
| 69 |
* @return string |
| 70 |
*/ |
| 71 |
private static function extract_home_url( string $redirect_uri ): string { |
| 72 |
return preg_replace( '/\/[^\/]+\/[^\/]+\.php.*$/', '', $redirect_uri ) ?? ''; |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* Get current home URL |
| 77 |
* @return string |
| 78 |
*/ |
| 79 |
public function get_current(): string { |
| 80 |
if ( defined( 'ICL_SITEPRESS_VERSION' ) ) { |
| 81 |
return get_site_url(); |
| 82 |
} |
| 83 |
return home_url(); |
| 84 |
} |
| 85 |
|
| 86 |
/** |
| 87 |
* Check if home URL is valid |
| 88 |
* @return bool |
| 89 |
*/ |
| 90 |
public function is_valid(): bool { |
| 91 |
$saved = $this->get_saved(); |
| 92 |
$current = $this->get_current(); |
| 93 |
|
| 94 |
return empty( $saved ) || $current === $saved; |
| 95 |
} |
| 96 |
} |
| 97 |
|