atk4/atk4 — pull request #238 by DarkSide666 (2013-01-29 20:17:43+00:00)
Title: API Utility methods

Here is two new utility methods and their implementation in all ATK4 files where I could find something like this. I guess there are more, but ... enough for a start I guess :)

Here is testcase (sorry, not ATK4 file, but plain PHP):
```
//API->utility
//============
echo "

";
foreach(array('Foo Bar BAz','F01 ba$z','Multi spaces','multi space 3','at the end ',' _ in beginning','UTF8 āčīķš chars') as $a){
echo "[$a] => [".normalizeName($a)."], [".normalizeName($a,'-')."]
";
}
echo "

";

/**
* Normalize field or identifier name. Can also be used in URL normalization.
* This will replace all non alpha-numeric characters with separator.
* Multiple separators in a row is replaced with one.
* Separators in beginning and at the end of name are removed.
*
* @param string $name String to process
* @param string $separator Character acting as separator
* @return string Normalized string
*/
function normalizeName($name,$separator='_')
{
if(strlen($separator)==0) {
return preg_replace('|[^a-z0-9]|i','',$name);
}
$s = $separator[0];
$name = preg_replace('|[^a-z0-9\\'.$s.']|i',$s,$name);
$name = trim($name,$s);
$name = preg_replace('|\\'.$s.'{2,}|',$s,$name);
return $name;
}

echo "

";
foreach(array('data','Data','Model_Foo','model_Foo','controller_data','MyClass','Vendor/Addon/Sub/Min','Vendor\Addon\Sub','Vendor_Addon_Sub') as $a){
echo "[$a] => [".normalizeClassName($a,'Model')."], [".normalizeClassName($a,'Grid_Basic')."]
";
}
echo "

";

/**
* Normalize class name.
* This will add specified prefix to class name if it's not already existing.
* Class name can have namespaces and they are treated prefectly.
*
* @param string|object $name Name of class or object which classname we'll extract
* @param string $prefix Prefix for class name
* @return string Full class name
*/
function normalizeClassName($name,$prefix)
{
if(is_object($name)) $name = get_class($name);
$prefix = ucfirst($prefix);
$name = str_replace('/','\\',$name);
$class = ltrim(strrchr($name,'\\'),'\\');
if(!$class) $class=$name;
if (strpos($class,$prefix)!==0) {
$name = preg_replace('|^(.*\\\)?(.*)$|', '\1'.$prefix.'_\2', $name);
}
return $name;
}
```