Skip to content

Instantly share code, notes, and snippets.

@pixelbrackets
Created September 13, 2016 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelbrackets/c53a130ca86ad3962a5f6941fcfaebe2 to your computer and use it in GitHub Desktop.
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…”)
<?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