So due to some nasty framework issues, I'm a little stuck here. Basically, I'm taking a string from user input, and replacing it with a value from my model that is only known at call time.
My structures are like so:
static public $placeholders = array("[REPLACE_STRING_1]"=>'firstName',
"[REPLACE_STRING_2]"=>'DateTime->format(\'aa,bb\')');
//Problem line above. Very messy, format is an arm long and painful
public function myfunction(ModelClass $master) {
$body = $this->sampleService->get('samplebody'); // populate body from DB
foreach(static::$placeholders as $key => $value){
$body = str_replace($key, $master->value, $body);
}
return $body;
}
So this makes for some very ugly code. My boss would like to edit it to make for a function to be part of the array, assigned to each entry, that would run to filter/edit the code. Something like
function dateFormat($prop){
return $prop->format('aa,bb');
}
function asIs($prop){
return $prop;
}
static public $placeholders = array("[REPLACE_STRING_1]"=>['firstName', asIs]
"[REPLACE_STRING_2]"=>['DateTime', dateFormat]);
Are there any existing structures or functions in PHP which make this possible, or is his code desire just a pipedream?
EDIT: I figured out a solution very similar to the answer posted below, but with a few modifications necessary to pass along variables.
function dateFormat ($prop, $master) {
return $master->$prop->format('aabb');
}
function asIs ($prop, $master) {
return $appointment->$prop;
}
static public $placeholders = array("[REPLACE_STRING_1]"=>['firstname','asIs'],
"[REPLACE_STRING_2]"=>['DateTime', dateFormat];
//instatiate service to get sampleService values
//main difference here
public function buildBody(ModelClass $master) {
$body = $this->sampleService->get('samplebody');
foreach(static::$placeholders as $key => $value){
$body = preg_replace_callback('/'.preg_quote($key).'/',
//Use closure here to pass in $master, otherwise laravel gets angry about strings instead of objects
function ($matches) use ($master) {
$placeholder = static::placeholders[$matches[0]];
$func = $placeholder[1];
$prop = $placeholder[0];
return call_user_func(array($this, $func), $prop, $appointment);
}, $body);
}
return $body;
}
All in all this was a very interesting problem for me, and I'm trying to find a way to clean it up even further. Going to mark your answer as correct, since it greatly helped get here.