File Context.php

      1: <?php
      2: /*
      3:
      4: MIT License
      5: Copyright 2013-2019 Zordius Chen. All Rights Reserved.
      6: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      7: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      8: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      9:
     10: Origin: https://github.com/zordius/lightncandy
     11: */
     12:
     13: /**
     14:  * file to handle LightnCandy Context
     15:  *
     16:  * @package    LightnCandy
     17:  * @author     Zordius <zordius@gmail.com>
     18:  */
     19:
     20: namespace LightnCandy;
     21:
     22: /**
     23:  * LightnCandy class to handle Context
     24:  */
     25: class Context extends Flags
     26: {
     27:     /**
     28:      * Create a context from options
     29:      *
     30:      * @param array<string,array|string|integer> $options input options
     31:      *
     32:      * @return array<string,array|string|integer> Context from options
     33:      */
     34:     public static function create($options)
     35:     {
     36:         if (!is_array($options)) {
     37:             $options = array();
     38:         }
     39:
     40:         $flags = isset($options['flags']) ? $options['flags'] : static::FLAG_BESTPERFORMANCE;
     41:
     42:         $context = array(
     43:             'flags' => array(
     44:                 'errorlog' => $flags & static::FLAG_ERROR_LOG,
     45:                 'exception' => $flags & static::FLAG_ERROR_EXCEPTION,
     46:                 'skippartial' => $flags & static::FLAG_ERROR_SKIPPARTIAL,
     47:                 'standalone' => $flags & static::FLAG_STANDALONEPHP,
     48:                 'noesc' => $flags & static::FLAG_NOESCAPE,
     49:                 'jstrue' => $flags & static::FLAG_JSTRUE,
     50:                 'jsobj' => $flags & static::FLAG_JSOBJECT,
     51:                 'jslen' => $flags & static::FLAG_JSLENGTH,
     52:                 'hbesc' => $flags & static::FLAG_HBESCAPE,
     53:                 'this' => $flags & static::FLAG_THIS,
     54:                 'nohbh' => $flags & static::FLAG_NOHBHELPERS,
     55:                 'parent' => $flags & static::FLAG_PARENT,
     56:                 'echo' => $flags & static::FLAG_ECHO,
     57:                 'advar' => $flags & static::FLAG_ADVARNAME,
     58:                 'namev' => $flags & static::FLAG_NAMEDARG,
     59:                 'spvar' => $flags & static::FLAG_SPVARS,
     60:                 'slash' => $flags & static::FLAG_SLASH,
     61:                 'else' => $flags & static::FLAG_ELSE,
     62:                 'exhlp' => $flags & static::FLAG_EXTHELPER,
     63:                 'lambda' => $flags & static::FLAG_HANDLEBARSLAMBDA,
     64:                 'mustlok' => $flags & static::FLAG_MUSTACHELOOKUP,
     65:                 'mustlam' => $flags & static::FLAG_MUSTACHELAMBDA,
     66:                 'mustsec' => $flags & static::FLAG_MUSTACHESECTION,
     67:                 'noind' => $flags & static::FLAG_PREVENTINDENT,
     68:                 'debug' => $flags & static::FLAG_RENDER_DEBUG,
     69:                 'prop' => $flags & static::FLAG_PROPERTY,
     70:                 'method' => $flags & static::FLAG_METHOD,
     71:                 'runpart' => $flags & static::FLAG_RUNTIMEPARTIAL,
     72:                 'rawblock' => $flags & static::FLAG_RAWBLOCK,
     73:                 'partnc' => $flags & static::FLAG_PARTIALNEWCONTEXT,
     74:                 'nostd' => $flags & static::FLAG_IGNORESTANDALONE,
     75:                 'strpar' => $flags & static::FLAG_STRINGPARAMS,
     76:                 'knohlp' => $flags & static::FLAG_KNOWNHELPERSONLY,
     77:             ),
     78:             'delimiters' => array(
     79:                 isset($options['delimiters'][0]) ? $options['delimiters'][0] : '{{',
     80:                 isset($options['delimiters'][1]) ? $options['delimiters'][1] : '}}',
     81:             ),
     82:             'level' => 0,
     83:             'stack' => array(),
     84:             'currentToken' => null,
     85:             'error' => array(),
     86:             'elselvl' => array(),
     87:             'elsechain' => false,
     88:             'tokens' => array(
     89:                 'standalone' => true,
     90:                 'ahead' => false,
     91:                 'current' => 0,
     92:                 'count' => 0,
     93:                 'partialind' => '',
     94:             ),
     95:             'usedPartial' => array(),
     96:             'partialStack' => array(),
     97:             'partialCode' => array(),
     98:             'usedFeature' => array(
     99:                 'rootthis' => 0,
    100:                 'enc' => 0,
    101:                 'raw' => 0,
    102:                 'sec' => 0,
    103:                 'isec' => 0,
    104:                 'if' => 0,
    105:                 'else' => 0,
    106:                 'unless' => 0,
    107:                 'each' => 0,
    108:                 'this' => 0,
    109:                 'parent' => 0,
    110:                 'with' => 0,
    111:                 'comment' => 0,
    112:                 'partial' => 0,
    113:                 'dynpartial' => 0,
    114:                 'inlpartial' => 0,
    115:                 'helper' => 0,
    116:                 'delimiter' => 0,
    117:                 'subexp' => 0,
    118:                 'rawblock' => 0,
    119:                 'pblock' => 0,
    120:                 'lookup' => 0,
    121:                 'log' => 0,
    122:             ),
    123:             'usedCount' => array(
    124:                 'var' => array(),
    125:                 'helpers' => array(),
    126:                 'runtime' => array(),
    127:             ),
    128:             'compile' => false,
    129:             'parsed' => array(),
    130:             'partials' => (isset($options['partials']) && is_array($options['partials'])) ? $options['partials'] : array(),
    131:             'partialblock' => array(),
    132:             'inlinepartial' => array(),
    133:             'helpers' => array(),
    134:             'renderex' => isset($options['renderex']) ? $options['renderex'] : '',
    135:             'prepartial' => (isset($options['prepartial']) && is_callable($options['prepartial'])) ? $options['prepartial'] : false,
    136:             'helperresolver' => (isset($options['helperresolver']) && is_callable($options['helperresolver'])) ? $options['helperresolver'] : false,
    137:             'partialresolver' => (isset($options['partialresolver']) && is_callable($options['partialresolver'])) ? $options['partialresolver'] : false,
    138:             'runtime' => isset($options['runtime']) ? $options['runtime'] : '\\LightnCandy\\Runtime',
    139:             'runtimealias' => 'LR',
    140:             'safestring' => '\\LightnCandy\\SafeString',
    141:             'safestringalias' => isset($options['safestring']) ? $options['safestring'] : 'LS',
    142:             'rawblock' => false,
    143:             'funcprefix' => uniqid('lcr'),
    144:         );
    145:
    146:         $context['ops'] = $context['flags']['echo'] ? array(
    147:             'seperator' => ',',
    148:             'f_start' => 'echo ',
    149:             'f_end' => ';',
    150:             'op_start' => 'ob_start();echo ',
    151:             'op_end' => ';return ob_get_clean();',
    152:             'cnd_start' => ';if ',
    153:             'cnd_then' => '{echo ',
    154:             'cnd_else' => ';}else{echo ',
    155:             'cnd_end' => ';}echo ',
    156:             'cnd_nend' => ';}',
    157:         ) : array(
    158:             'seperator' => '.',
    159:             'f_start' => 'return ',
    160:             'f_end' => ';',
    161:             'op_start' => 'return ',
    162:             'op_end' => ';',
    163:             'cnd_start' => '.(',
    164:             'cnd_then' => ' ? ',
    165:             'cnd_else' => ' : ',
    166:             'cnd_end' => ').',
    167:             'cnd_nend' => ')',
    168:         );
    169:
    170:         $context['ops']['enc'] = $context['flags']['hbesc'] ? 'encq' : 'enc';
    171:         $context['ops']['array_check'] = '$inary=is_array($in);';
    172:         static::updateHelperTable($context, $options);
    173:
    174:         if ($context['flags']['partnc'] && ($context['flags']['runpart'] == 0)) {
    175:             $context['error'][] = 'The FLAG_PARTIALNEWCONTEXT requires FLAG_RUNTIMEPARTIAL! Fix your compile options please';
    176:         }
    177:
    178:         return $context;
    179:     }
    180:
    181:     /**
    182:      * update specific custom helper table from options
    183:      *
    184:      * @param array<string,array|string|integer> $context prepared context
    185:      * @param array<string,array|string|integer> $options input options
    186:      * @param string $tname helper table name
    187:      *
    188:      * @return array<string,array|string|integer> context with generated helper table
    189:      *
    190:      * @expect array() when input array(), array()
    191:      * @expect array('flags' => array('exhlp' => 1), 'helpers' => array('abc' => 1)) when input array('flags' => array('exhlp' => 1)), array('helpers' => array('abc'))
    192:      * @expect array('error' => array('You provide a custom helper named as \'abc\' in options[\'helpers\'], but the function abc() is not defined!'), 'flags' => array('exhlp' => 0)) when input array('error' => array(), 'flags' => array('exhlp' => 0)), array('helpers' => array('abc'))
    193:      * @expect array('flags' => array('exhlp' => 1), 'helpers' => array('\\LightnCandy\\Runtime::raw' => '\\LightnCandy\\Runtime::raw')) when input array('flags' => array('exhlp' => 1), 'helpers' => array()), array('helpers' => array('\\LightnCandy\\Runtime::raw'))
    194:      * @expect array('flags' => array('exhlp' => 1), 'helpers' => array('test' => '\\LightnCandy\\Runtime::raw')) when input array('flags' => array('exhlp' => 1), 'helpers' => array()), array('helpers' => array('test' => '\\LightnCandy\\Runtime::raw'))
    195:      */
    196:     protected static function updateHelperTable(&$context, $options, $tname = 'helpers')
    197:     {
    198:         if (isset($options[$tname]) && is_array($options[$tname])) {
    199:             foreach ($options[$tname] as $name => $func) {
    200:                 $tn = is_int($name) ? $func : $name;
    201:                 if (is_callable($func)) {
    202:                     $context[$tname][$tn] = $func;
    203:                 } else {
    204:                     if (is_array($func)) {
    205:                         $context['error'][] = "I found an array in $tname with key as $name, please fix it.";
    206:                     } else {
    207:                         if ($context['flags']['exhlp']) {
    208:                             // Regist helper names only
    209:                             $context[$tname][$tn] = 1;
    210:                         } else {
    211:                             $context['error'][] = "You provide a custom helper named as '$tn' in options['$tname'], but the function $func() is not defined!";
    212:                         }
    213:                     }
    214:                 }
    215:             }
    216:         }
    217:         return $context;
    218:     }
    219:
    220:     /**
    221:      * Merge a context into another
    222:      *
    223:      * @param array<string,array|string|integer> $context master context
    224:      * @param array<string,array|string|integer> $tmp another context will be overwrited into master context
    225:      */
    226:     public static function merge(&$context, $tmp)
    227:     {
    228:         $context['error'] = $tmp['error'];
    229:         $context['helpers'] = $tmp['helpers'];
    230:         $context['partials'] = $tmp['partials'];
    231:         $context['partialCode'] = $tmp['partialCode'];
    232:         $context['partialStack'] = $tmp['partialStack'];
    233:         $context['usedCount'] = $tmp['usedCount'];
    234:         $context['usedFeature'] = $tmp['usedFeature'];
    235:         $context['usedPartial'] = $tmp['usedPartial'];
    236:     }
    237: }
    238: