Created
September 13, 2016 13:58
-
-
Save pixelbrackets/c53a130ca86ad3962a5f6941fcfaebe2 to your computer and use it in GitHub Desktop.
TYPO3 ViewHelper to return domain of a given link - usefull eg. for conditions with domain names (“if link points to »twitter.com«, then…”)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Pixelbrackets\AcmeExtension\ViewHelpers; | |
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper; | |
/** | |
* Returns the domain of a given link | |
* | |
* = Examples = | |
* | |
* <code title="Default"> | |
* <p:domainByLink link="http://www.example.com/foo/bar" /> | |
* </code> | |
* <output> | |
* example.com | |
* </output> | |
* | |
* <code title="Domain with Subdomain"> | |
* <p:domainByLink link="https://www.Example.com" showSubdomain="TRUE" /> | |
* </code> | |
* <output> | |
* www.example.com | |
* </output> | |
* | |
* <code title="Inline notation"> | |
* {p:domainByLink(link: 'www2.example.co.uk')} | |
* </code> | |
* <output> | |
* example.co.uk | |
* </output> | |
* | |
*/ | |
class DomainByLinkViewHelper extends AbstractViewHelper { | |
/** | |
* Get Domain | |
* | |
* @param string $link Link (e.g. example.com or https://example.com/foo/bar) | |
* @param boolean $showSubdomain Include subdomain in result (default FALSE) | |
* @return string | |
*/ | |
public function render($link = NULL, $showSubdomain = FALSE) { | |
if ($link === NULL) { | |
$link = $this->renderChildren(); | |
} | |
$parsedUrl = parse_url(strtolower(trim($link))); | |
// fix for PHP < 5.4.7 if URL scheme is missing | |
$domain = trim($parsedUrl['host'] ? $parsedUrl['host'] : array_shift(explode('/', $parsedUrl['path'], 2))); | |
if($showSubdomain == FALSE) { | |
preg_match('/[a-z0-9\-]{1,63}\.[a-z\.]{2,6}$/', $domain, $domainParts); | |
$domain = $domainParts[0]; | |
} | |
return $domain; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment