Skatch Skatch - 5 months ago 65
PHP Question

Custom shortcode parser

I am trying to create a custom parser for shortcodes in PHP, but I need directions on which php function (or maybe even php library) to use. Note that I am using Laravel 5, so packages are welcome too.

For example, I have a string in this format:

Hello {{user.first_name}}, your ID is {{user.id}}


I have a
$user
object containing these parameters. I'd like to check if all shortcode parameters within the string exist in the object, if not, I'd like to return an error, and if yes, I'd like to return the parsed string which would equal to:

Hello John, your ID is 123.


UPDATE



Please note that I'm building a REST API and this would be used in an automated email system. I need the result in a string within the controller so I can use it in my mailing function before the json response is returned.

Answer

According to your template style Mustache.php is the right library to achieve your goal.

Use Composer. Add mustache/mustache to your project's composer.json:

{
    "require": {
        "mustache/mustache": "~2.5"
    }
}

Usage:

if(isset($user->first_name) && isset($user->id)) {
    $m = new Mustache_Engine;
    return $m->render("Hello {{user.first_name}}, your ID is {{user.id}}", $user);
    //will return: Hello John, your ID is 123.
}else {
    //trigger error
}

Update 1:

If your data object is an Eloquent instance, you can use the following class to automatically throw errors in case of missing variables:

class MustacheData {

  private $model;

  public function __construct($model) {
    $this->model = $model;
  }

  public function __isset($name) {
    if (!isset($this->model->{$name})) {
      throw new InvalidArgumentException("Missing $name");
    }

    return true;
  }

  public function __get($name) {
    return $this->model->{$name};
  }
}

Usage:

try {
    $m = new Mustache_Engine;
    return $m->render("Hello {{user.first_name}}, your ID is {{user.id}}", new MustacheData($user));
}catch(InvalidArgumentException $e) {
    //Handle the error
}
Comments