Skip to content

Instantly share code, notes, and snippets.

@pepebe
Created October 26, 2012 09:12
Show Gist options
  • Save pepebe/3957784 to your computer and use it in GitHub Desktop.
Save pepebe/3957784 to your computer and use it in GitHub Desktop.
MODx - All-purpose-snippet
<?php
/* runFn Snippet
* by info@pepebe.de
*
* Pass the snippet a php function name and pipe delimited list of parameters.
*
* Example: Format a large number with number_format()
* See: www.php.net/manual/en/function.number-format.php
*
* [[!runFn? &fn=`number_format` &args=`123456789||2||,||.`]]
* Result: 123.456.789,00
*
* Parameters:
* &fn = name of php function
* &args = Double-pipe delimited list of function parameters.
* &ph = if set will create a placeholder instead of returning the output.
*
* 2do:
* Handle functions with array parameters...
* Add some error handling
* Think about a whitelist of usable functions
* */
$msg = "";
$args = (!empty($args)) ? explode("||",$args) : array();
if ( function_exists($fn) )
{
$output = call_user_func_array($fn, $args );
if($output !== false){
if(!empty($ph))
{
if($debug == 1)
{
$msg .= "Result: ".$output;
$modx->setPlaceholder($ph, $msg);
return;
}
else {
$modx->setPlaceholder($ph, $output);
return;
}
}
else
{
if($debug == 1)
{
$msg .= "Result: ".$output;
return $msg;
}
else {
return $output;
}
}
}
else {
$msg .= "call_user_func_array returned false. You called fn: $fn with args: ".implode("||",$args).".";
if($debug == 1)
{
return $msg;
}
else
{
return false;
}
}
}
else
{
$msg .= "function $nf does not exist";
if($debug == 1){
return $msg;
}
else {
return false;
}
}
@pepebe
Copy link
Author

pepebe commented Oct 26, 2012

Call many php functions without bothering to write a special snippet.

Example:

[[!runFn? 
   &fn=`str_replace` 
 &args=`A||B||Abakus`
   &ph=`test`
]]

[[+test]]

/* Result: Bbakus*/

or

[[!runFn? 
   &fn=`date` 
 &args=`'l jS \of F Y h:i:s A'` 
]]
/* Result: 'Thursday 25th of October 2012 03:39:38 PM' */

or

[[!runFn? 
   &fn=`time` 
 &args=``
 &ph=`time`
]]

[[+time:date=`%Y`]]

/* Result: 2012 - Output filters work on this too! */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment