File LightnCandy.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:  * the major file of LightnCandy compiler
     15:  *
     16:  * @package    LightnCandy
     17:  * @author     Zordius <zordius@gmail.com>
     18:  */
     19:
     20: namespace LightnCandy;
     21:
     22: /**
     23:  * LightnCandy major static class
     24:  */
     25: class LightnCandy extends Flags
     26: {
     27:     protected static $lastContext;
     28:     public static $lastParsed;
     29:
     30:     /**
     31:      * Compile handlebars template into PHP code.
     32:      *
     33:      * @param string $template handlebars template string
     34:      * @param array<string,array|string|integer> $options LightnCandy compile time and run time options, default is array('flags' => LightnCandy::FLAG_BESTPERFORMANCE)
     35:      *
     36:      * @return string|false Compiled PHP code when successed. If error happened and compile failed, return false.
     37:      */
     38:     public static function compile($template, $options = array('flags' => self::FLAG_BESTPERFORMANCE))
     39:     {
     40:         $context = Context::create($options);
     41:
     42:         if (static::handleError($context)) {
     43:             return false;
     44:         }
     45:
     46:         $code = Compiler::compileTemplate($context, SafeString::escapeTemplate($template));
     47:         static::$lastParsed = Compiler::$lastParsed;
     48:
     49:         // return false when fatal error
     50:         if (static::handleError($context)) {
     51:             return false;
     52:         }
     53:
     54:         // Or, return full PHP render codes as string
     55:         return Compiler::composePHPRender($context, $code);
     56:     }
     57:
     58:     /**
     59:      * Compile handlebars partial into PHP function code.
     60:      *
     61:      * @param string $template handlebars template string
     62:      * @param array<string,array|string|integer> $options LightnCandy compile time and run time options, default is array('flags' => LightnCandy::FLAG_BESTPERFORMANCE)
     63:      *
     64:      * @return string|false Compiled PHP code when successed. If error happened and compile failed, return false.
     65:      *
     66:      * @expect false when input '{{"}}', array('flags' => LightnCandy::FLAG_HANDLEBARS)
     67:      */
     68:     public static function compilePartial($template, $options = array('flags' => self::FLAG_BESTPERFORMANCE))
     69:     {
     70:         $context = Context::create($options);
     71:
     72:         if (static::handleError($context)) {
     73:             return false;
     74:         }
     75:
     76:         $code = Partial::compile($context, SafeString::escapeTemplate($template));
     77:
     78:         static::$lastParsed = Compiler::$lastParsed;
     79:
     80:         // return false when fatal error
     81:         if (static::handleError($context)) {
     82:             return false;
     83:         }
     84:
     85:         return $code;
     86:     }
     87:
     88:     /**
     89:      * Handle exists error and return error status.
     90:      *
     91:      * @param array<string,array|string|integer> $context Current context of compiler progress.
     92:      *
     93:      * @throws \Exception
     94:      * @return boolean True when error detected
     95:      *
     96:      * @expect false when input array('error' => array())
     97:      * @expect true when input array('error' => array('some error'), 'flags' => array('errorlog' => 0, 'exception' => 0))
     98:      */
     99:     protected static function handleError(&$context)
    100:     {
    101:         static::$lastContext = $context;
    102:
    103:         if (count($context['error'])) {
    104:             if ($context['flags']['errorlog']) {
    105:                 error_log(implode("\n", $context['error']));
    106:             }
    107:             if ($context['flags']['exception']) {
    108:                 throw new \Exception(implode("\n", $context['error']));
    109:             }
    110:             return true;
    111:         }
    112:         return false;
    113:     }
    114:
    115:     /**
    116:      * Get last compiler context.
    117:      *
    118:      * @return array<string,array|string|integer> Context data
    119:      */
    120:     public static function getContext()
    121:     {
    122:         return static::$lastContext;
    123:     }
    124:
    125:     /**
    126:      * Get a working render function by a string of PHP code. This method may requires php setting allow_url_include=1 and allow_url_fopen=1 , or access right to tmp file system.
    127:      *
    128:      * @param string      $php PHP code
    129:      * @param string|null $tmpDir Optional, change temp directory for php include file saved by prepare() when cannot include PHP code with data:// format.
    130:      * @param boolean     $delete Optional, delete temp php file when set to tru. Default is true, set it to false for debug propose
    131:      *
    132:      * @return Closure|false result of include()
    133:      *
    134:      * @deprecated
    135:      */
    136:     public static function prepare($php, $tmpDir = null, $delete = true)
    137:     {
    138:         $php = "<?php $php ?>";
    139:
    140:         if (!ini_get('allow_url_include') || !ini_get('allow_url_fopen')) {
    141:             if (!is_string($tmpDir) || !is_dir($tmpDir)) {
    142:                 $tmpDir = sys_get_temp_dir();
    143:             }
    144:         }
    145:
    146:         if (is_dir($tmpDir)) {
    147:             $fn = tempnam($tmpDir, 'lci_');
    148:             if (!$fn) {
    149:                 error_log("Can not generate tmp file under $tmpDir!!\n");
    150:                 return false;
    151:             }
    152:             if (!file_put_contents($fn, $php)) {
    153:                 error_log("Can not include saved temp php code from $fn, you should add $tmpDir into open_basedir!!\n");
    154:                 return false;
    155:             }
    156:
    157:             $phpfunc = include($fn);
    158:
    159:             if ($delete) {
    160:                 unlink($fn);
    161:             }
    162:
    163:             return $phpfunc;
    164:         }
    165:
    166:         return include('data://text/plain,' . urlencode($php));
    167:     }
    168: }
    169: