| 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 |
/** |
| 62 |
* Extract payload of a JWT token |
| 63 |
* |
| 64 |
* @param string $jwt JWT token |
| 65 |
* @param bool $associative Convert the payload to associative array or object |
| 66 |
* |
| 67 |
* @return false|mixed Returns the payload in array or object, False on failure |
| 68 |
*/ |
| 69 |
public static function JWTPayload( $jwt, $associative = true ) { |
| 70 |
$tokenParts = explode('.', $jwt); |
| 71 |
// make sure there are header, payload, and signature |
| 72 |
if ( count( $tokenParts ) === 3 && !empty( $tokenParts[1] ) ) { |
| 73 |
$base64UrlPayload = str_replace( ['-', '_'], ['+', '/'], $tokenParts[1] ); |
| 74 |
$jsonPayload = base64_decode( $base64UrlPayload ); |
| 75 |
return json_decode( $jsonPayload, $associative ); |
| 76 |
} else { |
| 77 |
return false; |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
} |
| 82 |
|