Skip to content

Instantly share code, notes, and snippets.

@stigfaerch
Created January 28, 2016 09:13
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 stigfaerch/16d22bc1c8c56011d86d to your computer and use it in GitHub Desktop.
Save stigfaerch/16d22bc1c8c56011d86d to your computer and use it in GitHub Desktop.
TYPO3 Fluid ViewHelper - StringContains
<?php
name SOME\NAMESPACE;
class StringContainsViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* Returns true depending on $needle in $haystack and which mode is chosen
* @param string $haystack
* @param string $needle
* @param string $mode - contains, beginsWith, endsWith
* @param bool $trim
* @return string bool
* @throws Exception
*/
public function render($haystack, $needle, $mode = 'contains', $trim = true) {
if(!$haystack || !$needle) {
return false;
}
if(method_exists($this, $mode)) {
return $this->$mode($trim ? trim($haystack) : $haystack, $needle);
} else {
// throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception()
throw new Exception("Chosen mode does not exist. Use contains, beginsWith or endsWith.");
// return false;
}
}
/**
* Returns true if $needle is found in $haystack
* @param $haystack
* @param $needle
* @return bool
*/
function contains($haystack, $needle) {
if (strpos($haystack, $needle) !== FALSE) {
return true;
} else {
return false;
}
}
/**
* Returns true if $haystack begins with $needle
* @param $haystack
* @param $needle
* @return bool
*/
function beginsWith($haystack, $needle) {
// search backwards starting from haystack length characters from the end
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
/**
* Returns true if $haystack ends with $needle
* @param $haystack
* @param $needle
* @return bool
*/
function endsWith($haystack, $needle) {
// search forward starting from end minus needle length characters
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment