| 1 |
<?php |
| 2 |
namespace Averta\Core\Utility; |
| 3 |
|
| 4 |
|
| 5 |
class Extract |
| 6 |
{ |
| 7 |
|
| 8 |
/** |
| 9 |
* Extracts domain from absolute url |
| 10 |
* |
| 11 |
* @param string $url |
| 12 |
* |
| 13 |
* @return mixed|string |
| 14 |
*/ |
| 15 |
public static function domain( $url ) { |
| 16 |
|
| 17 |
if ( empty( $url ) ) { |
| 18 |
return ''; |
| 19 |
} |
| 20 |
|
| 21 |
$parsedUrl = parse_url( $url ); |
| 22 |
|
| 23 |
$host = ''; |
| 24 |
|
| 25 |
if( isset( $parsedUrl['host'] ) ){ |
| 26 |
$host = $parsedUrl['host']; |
| 27 |
|
| 28 |
// if it was a plain url without schema |
| 29 |
} elseif( isset( $parsedUrl['path'] ) ){ |
| 30 |
$host = $parsedUrl['path']; |
| 31 |
} |
| 32 |
|
| 33 |
$hostParts = explode(".", $host); |
| 34 |
$domainExtensions = []; |
| 35 |
|
| 36 |
if( count( $hostParts ) > 2 ){ |
| 37 |
$domainExtensions = array_slice( $hostParts, -2 ); |
| 38 |
} |
| 39 |
|
| 40 |
if( count( $hostParts ) === 3 ){ |
| 41 |
if( strlen( implode( '', $domainExtensions ) ) > 5 ){ |
| 42 |
$hostParts = $domainExtensions; |
| 43 |
} |
| 44 |
|
| 45 |
} elseif( count( $hostParts ) > 3 ){ |
| 46 |
// skip ips |
| 47 |
if( ! is_numeric( implode( '', $hostParts ) ) ){ |
| 48 |
// if one of the last two parts is domain |
| 49 |
if( strlen( implode( '', $domainExtensions ) ) > 5 ){ |
| 50 |
$hostParts = $domainExtensions; |
| 51 |
} else { |
| 52 |
$hostParts = array_slice( $hostParts, -3 ); |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
$host = implode( '.', $hostParts ); |
| 58 |
return trim( $host, '/' ); |
| 59 |
} |
| 60 |
} |
| 61 |
|