I moved this thread from "General Discussion" to this place. Sorry for the inconvenience....
Edit: I changed the title and added some stuff to the snippet block.
Hi there fellow MODx users,
I just had this idea for an all-purpose snippet:
<?php
/* runFn Snippet
* by [email protected]
*
* 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: ".$fn." does not exist";
if($debug == 1){
return $msg;
}
else {
return false;
}
}
You can find the latest version of this snippet here:
https://gist.github.com/3957784
Now we can call many php functions without bothering to write a special snippet.
Example:
/* Use str_replace on a string and put the result into a placeholder. */
[[!runFn?
&fn=`str_replace`
&args=`This||MODx||This CMS is awesome`
&ph=`test`
]]
[[+test]]
/* Result: MODx CMS is awesome*/
or
/* Return the current date in a specific format */
[[!runFn?
&fn=`date`
&args=`'l jS \of F Y h:i:s A'`
]]
/* Result: 'Thursday 25th of October 2012 03:39:38 PM' */
or
/* Return a timestamp and format it with a MODx output filter */
[[!runFn?
&fn=`time`
&args=``
&ph=`time`
]]
[[+time:date=`%Y`]]
/* Result: 2012 */
The snippet requires some error handling, but I think you get the idea.
What do you think? Should I work on this a little bit more, or should I forget about it because it is a really bad idea?
Somehow this feels wrong...
Regards,
pepebe
[ed. note: pepebe last edited this post 13 years, 11 months ago.]