| 1 |
<?php |
| 2 |
|
| 3 |
namespace FlyWP\StaticSite\Engine\Discovery; |
| 4 |
|
| 5 |
/** |
| 6 |
* Moves WordPress links from the home URL to the origin URL that the engine fetches. |
| 7 |
* |
| 8 |
* WordPress builds links with home_url(). The build can fetch another origin (--origin-url). |
| 9 |
* Links on other hosts are not part of the site, so rebase() returns null for them. |
| 10 |
* |
| 11 |
* @since 1.8.0 |
| 12 |
*/ |
| 13 |
class OriginUrl { |
| 14 |
|
| 15 |
/** |
| 16 |
* Home URL without scheme and trailing slash. |
| 17 |
* |
| 18 |
* @var string |
| 19 |
*/ |
| 20 |
private $home; |
| 21 |
|
| 22 |
/** |
| 23 |
* Origin URL without trailing slash. |
| 24 |
* |
| 25 |
* @var string |
| 26 |
*/ |
| 27 |
private $origin; |
| 28 |
|
| 29 |
/** |
| 30 |
* @param string $home_url WordPress home URL. |
| 31 |
* @param string|null $origin_url Origin URL. Null or empty to use the home URL. |
| 32 |
*/ |
| 33 |
public function __construct( $home_url, $origin_url = null ) { |
| 34 |
$this->home = self::without_scheme( rtrim( $home_url, '/' ) ); |
| 35 |
$this->origin = rtrim( $origin_url ? $origin_url : $home_url, '/' ); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* @param string $url Absolute URL. |
| 40 |
* |
| 41 |
* @return string|null URL on the origin without fragment, or null when the URL is not on the site. |
| 42 |
*/ |
| 43 |
public function rebase( $url ) { |
| 44 |
$url = (string) $url; |
| 45 |
$fragment = strpos( $url, '#' ); |
| 46 |
|
| 47 |
if ( false !== $fragment ) { |
| 48 |
$url = substr( $url, 0, $fragment ); |
| 49 |
} |
| 50 |
|
| 51 |
$bare = self::without_scheme( $url ); |
| 52 |
|
| 53 |
foreach ( [ self::without_scheme( $this->origin ), $this->home ] as $base ) { |
| 54 |
if ( '' === $base || 0 !== stripos( $bare, $base ) ) { |
| 55 |
continue; |
| 56 |
} |
| 57 |
|
| 58 |
$rest = (string) substr( $bare, strlen( $base ) ); |
| 59 |
|
| 60 |
if ( '' === $rest ) { |
| 61 |
return $this->origin . '/'; |
| 62 |
} |
| 63 |
|
| 64 |
if ( '/' === $rest[0] || '?' === $rest[0] ) { |
| 65 |
return $this->origin . $rest; |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
return null; |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* @param string $url URL. |
| 74 |
* |
| 75 |
* @return string |
| 76 |
*/ |
| 77 |
private static function without_scheme( $url ) { |
| 78 |
return (string) preg_replace( '#^([a-z][a-z0-9+.-]*:)?//#i', '', $url ); |
| 79 |
} |
| 80 |
} |
| 81 |
|