File Partial.php

      1: <?php
      2: /*
      3:
      4: Copyright 2013-2019 Zordius Chen. All Rights Reserved.
      5: 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:
      6: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      7: 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.
      8:
      9: Origin: https://github.com/zordius/lightncandy
     10: */
     11:
     12: /**
     13:  * file to keep LightnCandy partial methods
     14:  *
     15:  * @package    LightnCandy
     16:  * @author     Zordius <zordius@gmail.com>
     17:  */
     18:
     19: namespace LightnCandy;
     20:
     21: /**
     22:  * LightnCandy Partial handler
     23:  */
     24: class Partial
     25: {
     26:     public static $TMP_JS_FUNCTION_STR = "!!\aFuNcTiOn\a!!";
     27:
     28:     /**
     29:      * Include all partials when using dynamic partials
     30:      */
     31:     public static function handleDynamic(&$context)
     32:     {
     33:         if ($context['usedFeature']['dynpartial'] == 0) {
     34:             return;
     35:         }
     36:
     37:         foreach ($context['partials'] as $name => $code) {
     38:             static::read($context, $name);
     39:         }
     40:     }
     41:
     42:     /**
     43:      * Read partial file content as string and store in context
     44:      *
     45:      * @param array<string,array|string|integer> $context Current context of compiler progress.
     46:      * @param string $name partial name
     47:      *
     48:      * @return string|null $code compiled PHP code when success
     49:      */
     50:     public static function read(&$context, $name)
     51:     {
     52:         $isPB = ($name === '@partial-block');
     53:         $context['usedFeature']['partial']++;
     54:
     55:         if (isset($context['usedPartial'][$name])) {
     56:             return;
     57:         }
     58:
     59:         $cnt = static::resolve($context, $name);
     60:
     61:         if ($cnt !== null) {
     62:             $context['usedPartial'][$name] = SafeString::escapeTemplate($cnt);
     63:             return static::compileDynamic($context, $name);
     64:         }
     65:
     66:         if (!$context['flags']['skippartial'] && !$isPB) {
     67:             $context['error'][] = "Can not find partial for '$name', you should provide partials or partialresolver in options";
     68:         }
     69:     }
     70:
     71:     /**
     72:      * preprocess partial template before it be stored into context
     73:      *
     74:      * @param array<string,array|string|integer> $context Current context of compiler progress.
     75:      * @param string $tmpl partial template
     76:      * @param string $name partial name
     77:      *
     78:      * @return string|null $content processed partial template
     79:      *
     80:      * @expect 'hey' when input array('prepartial' => false), 'hey', 'haha'
     81:      * @expect 'haha-hoho' when input array('prepartial' => function ($cx, $tmpl, $name) {return "$name-$tmpl";}), 'hoho', 'haha'
     82:      */
     83:     protected static function prePartial(&$context, $tmpl, &$name)
     84:     {
     85:         return $context['prepartial'] ? $context['prepartial']($context, $tmpl, $name) : $tmpl;
     86:     }
     87:
     88:     /**
     89:      * resolve partial, return the partial content
     90:      *
     91:      * @param array<string,array|string|integer> $context Current context of compiler progress.
     92:      * @param string $name partial name
     93:      *
     94:      * @return string|null $content partial content
     95:      */
     96:     public static function resolve(&$context, &$name)
     97:     {
     98:         if ($name === '@partial-block') {
     99:             $name = "@partial-block{$context['usedFeature']['pblock']}";
    100:         }
    101:         if (isset($context['partials'][$name])) {
    102:             return static::prePartial($context, $context['partials'][$name], $name);
    103:         }
    104:
    105:         return static::resolver($context, $name);
    106:     }
    107:
    108:     /**
    109:      * use partialresolver to resolve partial, return the partial content
    110:      *
    111:      * @param array<string,array|string|integer> $context Current context of compiler progress.
    112:      * @param string $name partial name
    113:      *
    114:      * @return string|null $content partial content
    115:      */
    116:     public static function resolver(&$context, &$name)
    117:     {
    118:         if ($context['partialresolver']) {
    119:             $cnt = $context['partialresolver']($context, $name);
    120:             return static::prePartial($context, $cnt, $name);
    121:         }
    122:     }
    123:
    124:     /**
    125:      * compile a partial to static embed PHP code
    126:      *
    127:      * @param array<string,array|string|integer> $context Current context of compiler progress.
    128:      * @param string $name partial name
    129:      *
    130:      * @return string|null $code PHP code string
    131:      */
    132:     public static function compileStatic(&$context, $name)
    133:     {
    134:         // Check for recursive partial
    135:         if (!$context['flags']['runpart']) {
    136:             $context['partialStack'][] = $name;
    137:             $diff = count($context['partialStack']) - count(array_unique($context['partialStack']));
    138:             if ($diff) {
    139:                 $context['error'][] = 'I found recursive partial includes as the path: ' . implode(' -> ', $context['partialStack']) . '! You should fix your template or compile with LightnCandy::FLAG_RUNTIMEPARTIAL flag.';
    140:             }
    141:         }
    142:
    143:         $code = Compiler::compileTemplate($context, preg_replace('/^/m', $context['tokens']['partialind'], $context['usedPartial'][$name]));
    144:
    145:         if (!$context['flags']['runpart']) {
    146:             array_pop($context['partialStack']);
    147:         }
    148:
    149:         return $code;
    150:     }
    151:
    152:     /**
    153:      * compile partial as closure, stored in context
    154:      *
    155:      * @param array<string,array|string|integer> $context Current context of compiler progress.
    156:      * @param string $name partial name
    157:      *
    158:      * @return string|null $code compiled PHP code when success
    159:      */
    160:     public static function compileDynamic(&$context, $name)
    161:     {
    162:         if (!$context['flags']['runpart']) {
    163:             return;
    164:         }
    165:
    166:         $func = static::compile($context, $context['usedPartial'][$name], $name);
    167:
    168:         if (!isset($context['partialCode'][$name]) && $func) {
    169:             $context['partialCode'][$name] = "'$name' => $func";
    170:         }
    171:
    172:         return $func;
    173:     }
    174:
    175:     /**
    176:      * compile a template into a closure function
    177:      *
    178:      * @param array<string,array|string|integer> $context Current context of compiler progress.
    179:      * @param string $template template string
    180:      * @param string|integer $name partial name or 0
    181:      *
    182:      * @return string $code compiled PHP code
    183:      */
    184:     public static function compile(&$context, $template, $name = 0)
    185:     {
    186:         if ((end($context['partialStack']) === $name) && (substr($name, 0, 14) === '@partial-block')) {
    187:             return;
    188:         }
    189:
    190:         $tmpContext = $context;
    191:         $tmpContext['inlinepartial'] = array();
    192:         $tmpContext['partialblock'] = array();
    193:
    194:         if ($name !== 0) {
    195:             $tmpContext['partialStack'][] = $name;
    196:         }
    197:
    198:         $code = Compiler::compileTemplate($tmpContext, str_replace('function', static::$TMP_JS_FUNCTION_STR, $template));
    199:         Context::merge($context, $tmpContext);
    200:         if (!$context['flags']['noind']) {
    201:             $sp = ', $sp';
    202:             $code = preg_replace('/^/m', "'{$context['ops']['seperator']}\$sp{$context['ops']['seperator']}'", $code);
    203:             // callbacks inside partial should be aware of $sp
    204:             $code = preg_replace('/\bfunction\s*\(([^\(]*?)\)\s*{/', 'function(\\1)use($sp){', $code);
    205:             $code = preg_replace('/function\(\$cx, \$in, \$sp\)use\(\$sp\){/', 'function($cx, $in)use($sp){', $code);
    206:         } else {
    207:             $sp = '';
    208:         }
    209:         $code = str_replace(static::$TMP_JS_FUNCTION_STR, 'function', $code);
    210:         return "function (\$cx, \$in{$sp}) {{$context['ops']['array_check']}{$context['ops']['op_start']}'$code'{$context['ops']['op_end']}}";
    211:     }
    212: }
    213: