<?php
class WATemplate {

  private static function dotGet($arr, $path, $default=''){
    $parts = explode('.', $path);
    $v = $arr;
    foreach($parts as $p){
      if(is_array($v) && array_key_exists($p, $v)){
        $v = $v[$p];
      }else{
        return $default;
      }
    }
    return (string)$v;
  }

  /**
   * Render with:
   *   - {{name}}
   *   - {{contact.name}}, {{contact.phone}}
   *   - {{account.name}}
   *   - {{today}}
   *   - Defaults: {{account.name|default:Customer}}
   */
  public static function render($body, array $vars = []) {
    if (!isset($vars['today'])) $vars['today'] = date('Y-m-d');

    return preg_replace_callback('/\{\{\s*([a-zA-Z0-9_\.]+)(?:\|default:(.*?))?\s*\}\}/', function($m) use ($vars){
      $key = $m[1];
      $def = isset($m[2]) ? $m[2] : '';
      if(array_key_exists($key, $vars)) return (string)$vars[$key];
      return self::dotGet($vars, $key, $def);
    }, $body);
  }
}
