tinybutstrong icon indicating copy to clipboard operation
tinybutstrong copied to clipboard

Allow using callables as a value for fields

Open hackeresq opened this issue 1 year ago • 4 comments

This allows the use of a callable as a value for merged fields. For example in your PHP code:

$TBS->MergeField('callable_field', fn() => Carbon::now()->addMonths(12)->toDateString());

Then in your HTML template you can use merge field like [callable_field], which would resolve the callable to a string.

This is useful when you have many "magic fields" that require evaluating a callable. In my case, I have "magic links" that can be generated and included in the template (e.g. one time use login links). I don't want to process those methods every time I merge a doc, rather, this dynamically calls the method just in time.

hackeresq avatar Dec 22 '23 15:12 hackeresq

@Skrol29 curious whether this is something that fits within TBS?

hackeresq avatar Jan 05 '24 01:01 hackeresq

Hello @hackerESQ ,

Thanks for your Pull Request, Sorry for having been long to reply.

The feature is quite interesting, it is useful for Closure functions, but also for invokable Objects (having a magic __invoke function ). Nevertheless, the implementation is not at the right place according to me. The purpose of meth_Misc_ToStr() is to ensure that the final item value is a string. While your feature should be, I think, to support callable objects, even if i returns another object, or an array, or other...

For example: [callable_field.my_key] should work if your Closure function returns an array such as ['my_key' => 29].

According to me, the place should be at the beginning of meth_Locator_Replace(), shortly after } elseif (is_object($Value)) {

I've not tested yet, but it seems good. I also have to check if the feature is compliant with the security methods_allowed option.

Would you like to change the Pull Request? Or I can do it for the next release.

Regards,

Skrol29 avatar Jan 08 '24 19:01 Skrol29

@Skrol29 , tinkered with this a bit more, but wasn't able to succeed with your suggestion. Happy to update the PR myself, but I'm definitely stuck.

Would appreciate any further suggestions.

hackeresq avatar Feb 04 '24 06:02 hackeresq

@Skrol29 Are you able to guide me a bit more. Happy to help move this to the right place in the class.

hackeresq avatar Mar 30 '24 01:03 hackeresq