Example #1
0
 /**
  * Parses a variable token and its optional filters (all as a single string),
  * and return a list of tuples of the filter name and arguments.
  * Sample::
  *
  * >>> token = 'variable|default:"Default value"|date:"Y-m-d"'
  * >>> p = Parser('')
  * >>> fe = FilterExpression(token, p)
  * >>> len(fe.filters)
  * 2
  * >>> fe.var
  * <Variable: 'variable'>
  *
  * This class should never be instantiated outside of the
  * get_filters_from_token helper function.
  *
  * @param Token $token
  * @param Parser $parser
  * @throws TemplateSyntaxError
  */
 public function __construct($token, $parser)
 {
     $this->token = $token;
     $matches = new PyReFinditer(DjaBase::getReFilter(), $token);
     $var_obj = null;
     $filters = array();
     $upto = 0;
     /** @var $match pyReMatchObject */
     foreach ($matches as $match) {
         $start = $match->start();
         if ($upto != $start) {
             throw new TemplateSyntaxError('Could not parse some characters: ' . py_slice($token, null, $upto) . '|' . py_slice($token, $upto, $start) . '|' . py_slice($token, $start) . '');
         }
         if ($var_obj === null) {
             list($var, $constant) = $match->group(array('var', 'constant'));
             if ($constant) {
                 try {
                     $var_obj = new Variable($constant);
                     $var_obj = $var_obj->resolve(array());
                 } catch (VariableDoesNotExist $e) {
                     $var_obj = null;
                 }
             } elseif ($var === null) {
                 throw new TemplateSyntaxError('Could not find variable at start of ' . $token . '.');
             } else {
                 $var_obj = new Variable($var);
             }
         } else {
             $filter_name = $match->group('filter_name');
             $args = array();
             list($constant_arg, $var_arg) = $match->group(array('constant_arg', 'var_arg'));
             if (trim($constant_arg) != '') {
                 $tmp = new Variable($constant_arg);
                 $tmp = $tmp->resolve(array());
                 $args[] = array(False, $tmp);
                 unset($tmp);
             } elseif (trim($var_arg) != '') {
                 $args[] = array(True, new Variable($var_arg));
             }
             $filter_func = $parser->findFilter($filter_name);
             self::argsCheck($filter_name, $filter_func->closure, $args);
             $filters[] = array($filter_func, $args, $filter_name);
             // Deliberately add filter name as the third element (used in `filter` tag).
         }
         $upto = $match->end();
     }
     if ($upto != mb_strlen($token, 'utf-8')) {
         throw new TemplateSyntaxError("Could not parse the remainder: '" . py_slice($token, $upto) . "' from '" . $token . "'");
     }
     $this->filters = $filters;
     $this->var = $var_obj;
 }