public function getSource(string $name) { $library = $this->getLibrary($name); if (empty($library['source'])) { throw new Exception("Reference {$name} source is empty!"); } return substitute($library['source'], $library); }
function select_taunt() { global $session, $badguy; $sql = "SELECT taunt FROM " . db_prefix("taunts") . " ORDER BY rand(" . e_rand() . ") LIMIT 1"; $result = db_query($sql); if ($result) { $row = db_fetch_assoc($result); $taunt = $row['taunt']; } else { $taunt = "`5\"`6%w's mother wears combat boots`5\", screams %W."; } $taunt = substitute($taunt); return $taunt; }
public function buildClass(string $class) { $tpl = __DIR__ . '/Templates/Controller.tp'; $vars = []; list($vars['namespace'], $vars['class']) = parse_class($class); if (!empty($vars['namespace'])) { $vars['namespace'] = "namespace {$vars['namespace']};"; } if (empty($this->extend)) { $vars['extend'] = 'Controller'; $vars['use'] = 'use Ke\\Web\\Controller;'; } else { $vars['extend'] = $this->extend; } return substitute(file_get_contents($tpl), $vars); }
protected function onExecute($argv = null) { $stub = $this->dir . '/stub'; $class = static::class; $pathParam = FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME; try { $phar = new Phar(predir($this->getSavePath()), $pathParam, $this->getFileName()); $phar->buildFromDirectory($this->dir, '/.php|.phtml|.inc|.tp|.txt|.json$/'); $phar->addFromString('pack.txt', $class . " packed in " . date('Y-m-d H:i:s')); if (is_file($stub) && is_readable($stub)) { $phar->setStub(substitute(file_get_contents($stub), ['file' => $this->getFileName()])); } $this->console->println('Pack "' . $this->getFileName() . '" success, file export to "' . $this->getSavePath() . '"!'); } catch (\Throwable $thrown) { $this->console->halt($thrown->getMessage()); } }
/** * 文本字符替换(函数命名源自Mootools)。 * * *原本作为Utils\String包里面的函数,现在将他提取到Common中。* * * ```php * // 基本的使用 * $str = '你好,{name}!'; * $args = ['name' => 'kephp']; * substitute($str, $args); // '你好,kephp!' * * // 如果变量不存在的话: * $str = '你好,{name}!今天是星期{weekDay}。'; * substitute($str, $args); // '你好,kephp!今天是星期。' * * // 他会循环检查 * $str = '你好,{name}!{tail}'; * $args = [ * 'name' => 'kephp', * 'weekDay' => '六', * 'tail' => '今天是星期{weekDay}。', * ]; * * substitute($str, $args); // '你好,kephp!今天是星期六。' * * // 指定第三个参数,可以取得这次文本替换过程中所匹配到的keywords和对应的变量内容 * substitute($str, $args, $matches); // matches将会包含: name, weekDay, tail * ``` * * 本函数支持多层数组、对象的深度查询 * * ```php * $str = '你好,{name}!{tail}{template}'; * $args = [ * 'name' => 'kephp', * 'message' => [ * 'title' => '认识你很高兴!', * 'content' => '我想了解更多的讯息!', * ], * 'template' => '<h1>{message->title}</h1><div>{message->content}</div>', * 'weekDay' => '六', * 'tail' => '今天是星期{weekDay}。', * ]; * substitute($str, $args); * // 返回:你好,kephp!今天是星期六。<h1>认识你很高兴!</h1><div>我想了解更多的讯息!</div> * ``` * * 第四个参数`$regex`,允许设定你自定义的变量的正则匹配表达式。 * * @param string $str * @param array $args * @param string $regex * @param array $matches * @return string */ function substitute(string $str, array $args = [], array &$matches = [], $regex = '#\\{([^\\{\\}\\r\\n]+)\\}#') : string { if (empty($str)) { return ''; } if (empty($args)) { // 没有参数,就表示无需替换了 return $str; } if (empty($regex)) { $regex = '#\\{([^\\{\\}\\r\\n]+)\\}#'; } if (preg_match($regex, $str)) { $str = preg_replace_callback($regex, function ($m) use($args, &$matches) { $key = $m[1]; $matches[$key] = ''; // give a default empty string if (isset($args[$key]) || isset($args->{$key})) { $matches[$key] = $args[$key]; } else { $matches[$key] = depth_query($args, $key, ''); } return $matches[$key]; }, $str); return substitute($str, $args, $matches, $regex); } return $str; }
$msg = "{badguy} flees in panic."; } else { $msg = $badguy['fleesifalone']; } $msg = substitute_array("`5" . $msg . "`0`n"); output($msg); } } else { $newenemies[$index] = $badguy; } } } else { if ($leaderisdead) { if (is_array($badguy['essentialleader'])) { $msg = sprintf_translate($badguy['essentialleader']); $msg = substitute($msg); output_notl($msg); //Here it's already translated } else { if ($badguy['essentialleader'] === true) { $msg = "All other other enemies flee in panic as `^{badguy}`5 falls to the ground."; } else { $msg = $badguy['essentialleader']; } $msg = substitute_array("`5" . $msg . "`0`n"); output($msg); } } } if (is_array($newenemies)) { $enemies = $newenemies;
public static function buildErrorMessage($field, $error) : string { $message = null; $data = ['label' => static::getLabel($field)]; if (empty($error)) { $message = static::getErrorMessage(static::ERR_UNKNOWN); } elseif (is_string($error)) { $message = static::getErrorMessage($error); } elseif (is_array($error)) { $message = static::getErrorMessage(array_shift($error)); if (!empty($error)) { $data += $error; } } return substitute($message, $data); }
function expire_buffs() { global $session, $badguy; tlschema("buffs"); foreach ($session['bufflist'] as $key => $buff) { if (array_key_exists('suspended', $buff) && $buff['suspended']) { continue; } if ($buff['schema']) { tlschema($buff['schema']); } if (array_key_exists('used', $buff) && $buff['used']) { $session['bufflist'][$key]['used'] = 0; if ($session['bufflist'][$key]['rounds'] > 0) { $session['bufflist'][$key]['rounds']--; } if ((int) $session['bufflist'][$key]['rounds'] == 0) { if (isset($buff['wearoff']) && $buff['wearoff']) { if (is_array($buff['wearoff'])) { $buff['wearoff'] = str_replace("`%", "`%%", $buff['wearoff']); $msg = sprintf_translate($buff['wearoff']); $msg = substitute("`5" . $msg . "`0`n"); output_notl($msg); //Here it's already translated } else { $msg = substitute("`5" . $buff['wearoff'] . "`0`n"); output_notl($msg); } } //unset($session['bufflist'][$key]); strip_buff($key); } } if ($buff['schema']) { tlschema(); } } tlschema(); }
} } } else { if ($leaderisdead) { if (is_array($badguy['essentialleader'])) { $msg = sprintf_translate($badguy['essentialleader']); $msg = substitute($msg); output_notl($msg); //Here it's already translated } else { if ($badguy['essentialleader'] === true) { $msg = "All other other enemies flee in panic as `^{badguy}`5 falls to the ground."; } else { $msg = $badguy['essentialleader']; } $msg = substitute("`5" . $msg . "`0`n"); output_notl($msg); } } } if (is_array($newenemies)) { $enemies = $newenemies; } $roundcounter = 0; } while ($count > 0 || $count == -1); $newenemies = $enemies; } else { $newenemies = $enemies; } $newenemies = autosettarget($newenemies); if ($session['user']['hitpoints'] > 0 && count($newenemies) > 0 && ($op == "fight" || $op == "run")) {
public function buildModel(string $table, string $class, string $path) { list($namespace, $pureClass) = parse_class($class); $dir = dirname($path); $tpl = $this->getTplContent(); $forge = $this->adapter->getForge(); $vars = $forge->buildTableProps($table); $vars['namespace'] = $namespace; $vars['class'] = $pureClass; $vars['tableName'] = $table; $vars['datetime'] = date('Y-m-d H:i:s'); if (is_file($path)) { return ['Fail', PHP_EOL, "File {$path} is existing!"]; } if (!is_dir($dir)) { mkdir($dir, 0755, true); } if (file_put_contents($path, substitute($tpl, $vars))) { return ['Success']; } else { return ['Fail', PHP_EOL, 'I/O error, please try again!']; } }
protected function verifyRequire() { foreach (static::$columns as $name => $column) { if ($column['require']) { if (!isset($this->{$name}) || empty($this->{$name})) { static::showHelp(substitute('Must specify the argument "{field}"', ['command' => static::getName(), 'field' => $name])); exit; break; } } continue; } return true; }
public function makeLogText() { $assets = []; foreach ($this->log['assets'] as $row) { $assets[] = substitute($this->tplAssetRow, $row); } $data = ['references' => var_export($this->log['references'] ?? [], true), 'assets' => implode(PHP_EOL, $assets), 'datetime' => date('Y-m-d H:i:s')]; $log = substitute($this->tplLog, $data); return $log; }
/* Example {"title":"test", "subtitle":"x", "vis":"bz", "bz_spec":"bl", "bz_bl": 2, "fac":2, "dec":1, "colors":10, "grad":2, "data" : { "Feldkirchen" : 1, "Hermagor" : 2, "Klagenfurt" : 3, "Klagenfurt-Land" : 4, "Spittal an der Drau" : 5, "St. Veit an der Glan" : 6, "Villach" : 7, "Villach-Stadt" : 8, "Völkermarkt" : 9,"Wolfsberg" : 10} } */ $param = ($_GET) ? $_GET : $_POST; if (empty($param['q'])) die(); $param['q'] = stripslashes($param['q']); $request = json_decode($param['q'], true); if (!$request) die(); $return = sanitize($request['title'], $request['subtitle'], $request['dec'], $request['colors'], $request['grad']); $s = select_svg_file($request); $data = json2data($request, $request['data']); if (!$data) die(); header('Content-type: image/svg+xml; charset=utf-8'); echo substitute($s, $return[0][0], $return[1][0], $return[2][0], $return[3][0], $return[4][0], $data); ?>
public function paginate(Pagination $pagination = null, $attr = null) { if (!isset($pagination)) { return ''; } $linksCount = intval($this->pageLinks); $prevNext = !empty($this->pagePrevNext); $firstLast = !empty($this->pageFirstLast); $goto = $this->pageGoto; $field = $pagination->field; $pageTotal = $pagination->total; $pageCurrent = $pagination->current; $els = ['links' => '', 'prev' => '', 'next' => '', 'first' => '', 'last' => '', 'current' => '', 'total' => '', 'button' => '']; if ($pageTotal > $linksCount) { $half = (int) ($linksCount / 2); $start = $pageCurrent - $half; if ($start < 1) { $start = 1; } $over = $start + $linksCount; // $over = $start + $linksCount - ($firstLast ? ($start == 1 ? 2 : 3) : 1); if ($over > $pageTotal) { $over = $pageTotal; $start = $over - $linksCount; if ($start <= 1) { $start = 1; } } } else { $start = 1; $over = $pageTotal; } $uri = Web::getWeb()->http->newUri(); $ellipsis = $this->paginationLink(self::PAGE_ELLIPSIS, 0); if ($linksCount > 0) { if ($start > 1) { if (!$firstLast) { $els['links'] .= $this->paginationLink(self::PAGE_ITEM, 1, $uri, $field, false); $start += 1; if ($start > 2) { $els['links'] .= $ellipsis; } } else { $els['links'] .= $ellipsis; } } if (!$firstLast && $over < $pageTotal) { $over -= 1; } for ($i = $start; $i <= $over; $i++) { $els['links'] .= $this->paginationLink(self::PAGE_ITEM, $i, $uri, $field, $pageCurrent); } if ($over < $pageTotal) { if (!$firstLast) { if ($over < $pageTotal - 1) { $els['links'] .= $ellipsis; } $els['links'] .= $this->paginationLink(self::PAGE_ITEM, $pageTotal, $uri, $field, false); } else { $els['links'] .= $ellipsis; } } } if ($firstLast) { $els['first'] = $this->paginationLink(self::PAGE_FIRST, 1, $uri, $field, $pageCurrent); $els['last'] = $this->paginationLink(self::PAGE_LAST, $pageTotal, $uri, $field, $pageCurrent); } if ($prevNext) { $els['prev'] = $this->paginationLink(self::PAGE_PREV, $pageCurrent - 1, $uri, $field, 1 - 1); $els['next'] = $this->paginationLink(self::PAGE_NEXT, $pageCurrent + 1, $uri, $field, $pageTotal + 1); } if (!empty($goto)) { if ($goto === 'input') { $el = $this->input('number', $pageCurrent, ['step' => 1, 'min' => 1, 'max' => $pageTotal, 'name' => $field]); } else { $pages = range(1, $pageTotal); $el = $this->select(array_combine($pages, $pages), $pageCurrent, ['name' => $field]); } $els['current'] = $this->tag('page-span:input', sprintf($this->getText(self::PAGE_CUR), $el)); $els['button'] = $this->tag('page-button', $this->getText(self::PAGE_GOTO)); } else { $els['current'] = sprintf($this->getText(self::PAGE_CUR), $pageCurrent); } $els['total'] = sprintf($this->getText(self::PAGE_TOTAL), $pageTotal); $row = substitute($this->pageRow, $els); if (!empty($goto)) { $row .= $this->inputSet($uri->getQueryData(), 'hidden', [$field => 1]); $row = $this->tag('form', $row, ['action' => $uri, 'method' => 'get']); } return $this->tag('page-wrap', $row, $attr); }
protected function createClass() { $class = $this->prepareClasses[$this->selected]; $path = $this->preparePaths[$this->selected]; $cmd = $this->prepareCommands[$this->selected]; $tplFile = $this->isRef ? 'ReflectionCommand.tp' : 'Command.tp'; $tplPath = __DIR__ . '/Templates/' . $tplFile; if (is_file($path)) { return ['Lost!', "The file \"{$path}\" is exists!"]; } if (!is_file($tplPath)) { return ['Lost!', "The template file \"{$tplFile}\" cannot found!"]; } $dir = dirname($path); if (!is_dir($dir)) { mkdir($dir, 0755, true); } $tplContent = file_get_contents($tplPath); list($ns, $cls) = parse_class($class); $vars = ['class' => $cls, 'command' => $this->name, 'namespace' => $ns, 'datetime' => date('Y-m-d H:i')]; if (file_put_contents($path, substitute($tplContent, $vars))) { return ['Success!', 'Please type: "php ' . KE_SCRIPT_FILE . ' ' . $cmd . ' --help"']; } return ['Lost!', "{$path} save error!"]; }
$title = $return[0][0]; $subtitle = $return[1][0]; if ($file_title) $file_title = '-'.$file_title; if ($file_subtitle) $file_subtitle = '-'.$file_subtitle; $dec = $return[2][0]; $colors = $return[3][0]; if (file_exists($image)) { // Create SVG $svg = substitute($image, $title, $subtitle, $dec, $colors, (int)$_POST['grad'], $data); $date = date('Ymd'); $img_path = $location_creation. $date.$file_title.$file_subtitle; $json_data = array($_POST, $title, $subtitle, $dec, $colors, (int)$_POST['grad'], $data); $return = create_file($svg, $img_path, $json_data); if (is_int($return)) { switch ($status) { case -1: $error[] = 'Konnte Datei nicht öffnen. '. 'Keine Zugriffsrechte.';
public function buildContent() : string { $tpl = $this->getTemplatePath(); $content = file_get_contents($tpl); $vars = ['path' => "{$this->controller}/{$this->view}", 'class' => $this->class]; return substitute($content, $vars); }
public function createFile($file, string $tpl = null, array $options) { $this->console->println("create file {$file}"); $tpl = __DIR__ . '/Templates/' . $tpl; if (is_file($tpl)) { $tplContent = file_get_contents($tpl); if (!isset($options['replace']) || $options['replace'] !== false) { $tplContent = substitute($tplContent, $this->context); } if (file_put_contents(predir($file), $tplContent)) { $this->console->println("create file {$file} success!"); } else { $this->console->println("create file {$file} lost!"); } } }