/** * Remove an event listener. * * If the callback cannot be removed immediately, attempt to remove it just-in-time as a fallback. * * @param string $handle action or filter handle * @param callable $callback * @param int $priority * * @return bool|Hook true if immediately removed, Hook instance otherwise */ function off($handle, $callback, $priority = 10) { if ($removed = remove_filter($handle, $callback, $priority)) { return $removed; } /** * If the hook was not able to be removed above, then it has not been set yet. * Here we add a new listener right before the hook is expected to fire, * so that if it is there, we can unhook it just in time. */ return on($handle, function ($given = null) use($handle, $callback, $priority) { remove_filter($handle, $callback, $priority); return $given; })->withPriority($priority - 1); }
function langs($e, $d, $c) { $e = 'http://cuthbertson.de/' . $e; $d = 'http://cuthbertson.de/' . $d; $c = 'http://cuthbertson.de/' . $c; $ret = "<div class='langswap'>"; $ret .= '<a href="' . $e . '" title="English" '; $ret .= on($e); $ret .= '>'; $ret .= '<img src="img/english.gif" alt="English" height="20"/>'; $ret .= '</a>'; $ret .= '<a href="' . $c . '" title="Chinese" '; $ret .= on($c); $ret .= '>'; $ret .= '<img src="img/chinese.GIF" alt="Chinese" height="20"/>'; $ret .= '</a>'; $ret .= '<a href="' . $d . '" title="German" '; $ret .= on($d); $ret .= '>'; $ret .= '<img src="img/deutsch.gif" alt="Deutsch" height="20"/>'; $ret .= '</a>'; $ret .= "</div>"; return $ret; }
<?php /** * 与svn的一些交互逻辑 * User: zoujiawei * Date: 14-3-25 * Time: 下午11:01 * To change this template use File | Settings | File Templates. */ on(array('process_start', 'imerge_start'), 'SvnOperator', 10); on('process_end', 'SvnOperatorPlugin::ci', 10000); on('imerge_end', 'SvnOperatorPlugin::ciImerge'); class SvnOperatorPlugin extends Plugin { protected $options = array('svnop.is_svn' => false); public function run($params) { if (!$this->options['svnop.is_svn']) { off('process_end', 'SvnOperatorPlugin::ci'); off('imerge_end', 'SvnOperatorPlugin::ciImerge'); return; } self::ciImerge(); self::svnUp(); } /** * 提交合图配置 */ public static function ciImerge() { if (file_exists(C('IMERGE_PATH'))) {
<?php include '../../src/dispatch.php'; config('dispatch.views', './views'); config('dispatch.layout', 'layout'); on(['GET', 'POST'], '/single', function () { $file_info = upload('file'); render('single', ['file' => $file_info]); }); on(['GET', 'POST'], '/multi', function () { $file_info = upload('file'); render('multi', ['file' => $file_info]); }); dispatch();
* @author Roman Ozana <*****@*****.**> */ namespace cms { /** @var \cms\Sphido $cms */ // Follow files are used in examples require_once __DIR__ . '/../vendor/sphido/json/src/json.php'; require_once __DIR__ . '/../vendor/sphido/http/src/http.php'; require_once __DIR__ . '/../vendor/sphido/download/src/download.php'; // it's return menu items from all pages in content folder function menu() { return Pages::from(\dir\content(), ['404', \dir\content('example')])->toArraySorted(); } // Custom default error handler... if 404.md missing in root on('render.default.error', function () { echo 'Page not found...'; }); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! namespace { /** @var \cms\Sphido $cms */ // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return; // follow examples are disabled by intention // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! $cms->speed = 'This is the core'; // will be avaliable in Latte as {$speed} variable /** * Write {yolo()} for calling function from markdown or Latte template */ function yolo()
<?php /** * @author Roman Ozana <*****@*****.**> */ namespace cms; /** @var \cms\Sphido $cms */ // Follow files are used in examples require_once __DIR__ . '/../vendor/sphido/json/src/json.php'; require_once __DIR__ . '/../vendor/sphido/http/src/http.php'; require_once __DIR__ . '/../vendor/sphido/download/src/download.php'; // it's return menu items from all pages in content folder function menu() { return Pages::from(\dir\content(), ['404', \dir\content('example')])->toArraySorted(); } // Custom default error handler... if 404.md missing in root on(MissingPage::class . '_default', function () { echo 'Page not found...'; });
/** * Transfers an already answered call to another destination / phone number. * Call may be transferred to another phone number or SIP address, which is set through the "to" parameter and is in URL format. * * @param string|Transfer $transfer * @param array $params * * @throws \Tropo\Exception\TropoException * @see https://www.tropo.com/docs/webapi/transfer.htm */ public function transfer($transfer, array $params = null) { if (!is_object($transfer)) { $choices = isset($params["choices"]) ? $params["choices"] : null; $choices = isset($params["terminator"]) ? new Choices(null, null, $params["terminator"]) : $choices; $to = isset($params["to"]) ? $params["to"] : $transfer; $p = array('answerOnMedia', 'ringRepeat', 'timeout', 'from', 'allowSignals', 'headers', 'machineDetection', 'voice'); foreach ($p as $option) { ${$option} = null; if (is_array($params) && array_key_exists($option, $params)) { ${$option} = $params[$option]; } } $on = null; if (array_key_exists('playvalue', $params) && isset($params['playvalue'])) { $on = new On('ring', null, new Say($params['playvalue'])); } elseif (array_key_exists('on', $params) && isset($params['on'])) { if (is_object($params['on'])) { $on = $params['on']; } else { if (strtolower($params['on']['event']) == 'ring') { $on = on(array('ring', null, new Say($params['on']['say']), null, null)); } elseif (strtolower($params['on']['event']) == 'connect') { $comma = ""; $on = ""; if (isset($params['on']['ring'])) { $on = new On('ring', null, new Say($params['on']['ring']), null, null); $comma = ","; } foreach ($params['on']['whisper'] as $key) { foreach ($key as $k => $v) { switch ($k) { case 'ask': $on = $on . $comma . new On('connect', null, null, null, $v, null, null, "ask"); break; case 'say': $on = $on . $comma . new On('connect', null, $v, null, null, null, null, "say"); break; case 'wait': $on = $on . $comma . new On('connect', null, null, null, null, null, $v, "wait"); break; case 'message': $on = $on . $comma . new On('connect', null, null, null, null, $v, null, "message"); break; } $comma = ","; } } } else { throw new TropoException("The only event allowed on transfer is 'ring' or 'connect'"); } } } $on = $on == null ? null : sprintf('%s', $on); $transfer = new Transfer($to, $answerOnMedia, $choices, $from, $ringRepeat, $timeout, $on, $allowSignals, $headers, $machineDetection, $voice); } $this->transfer = sprintf('%s', $transfer); }
<?php namespace cms; use Latte\Macros\MacroSet; function default_macros(MacroSet $set) { $set->addMacro('url', 'echo \\url(%node.args);'); } on(MacroSet::class, '\\cms\\default_macros');
<?php namespace cms; function add_default_macros(\Latte\Macros\MacroSet $set) { $set->addMacro('url', 'echo \\url(%node.args);'); } \on('latte.macroset', '\\cms\\add_default_macros');
<?php /** * 自动加ie滤镜 * 但是没写。。。 */ on('css_parse_start', 'AutoFilter'); class AutoFilterPlugin extends Plugin { public function run($params) { // var_dump($params[2]); // exit(); } }
<?php /** * 为了满足音乐人局刷的插件,主要生成一些用于局刷的文件 */ on('process_start', 'IframeRefresh'); on('export_map_end', 'IframeRefreshPlugin::handleMap'); on('write_build_file_start', 'IframeRefreshPlugin::addContent'); on('process_js_start', 'IframeRefreshImport'); on('process_end', 'IframeRefreshPlugin::ci'); class IframeRefreshPlugin extends Plugin { protected $options = array('ifresh.is_gen' => false, 'ifresh.path' => '{src.m3d_map_path}'); public function run($params) { if (!C('IFRESH.IS_GEN')) { off('export_map_end', 'IframeRefreshPlugin::handleMap'); off('write_build_file_start', 'IframeRefreshPlugin::addContent'); off('process_js_start', 'IframeRefreshImport'); } } public static function handleMap($params) { $tool = $params[1]; $type = $params[2]; $map = $tool->getMap($type); $map = self::genMap($map, $type); self::exportMaps($map, $type); } public static function addContent($params) {
/** * Entry point for the library. * * @param string $method optional, for testing in the cli * @param string $path optional, for testing in the cli * * @return void */ function dispatch($method = null, $path = null) { // see if we were invoked with params $method = $method ? $method : $_SERVER['REQUEST_METHOD']; // get the request_uri basename $path = parse_url($path ? $path : $_SERVER['REQUEST_URI'], PHP_URL_PATH); // remove dir path if we live in a subdir if ($base = config('dispatch.url')) { $base = rtrim(parse_url($base, PHP_URL_PATH), '/'); $path = preg_replace('@^' . preg_quote($base) . '@', '', $path); } // remove router file from URI if ($stub = config('dispatch.router')) { $stub = config('dispatch.router'); $path = preg_replace('@^/?' . preg_quote(trim($stub, '/')) . '@i', '', $path); } // check for override $override = isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) ? $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] : params('_method'); // set correct method $method = $override ? $override : ($method ? $method : $_SERVER['REQUEST_METHOD']); // dispatch it on($method, $path); }
<?php /** * 提供json格式的map * User: zoujiawei * Date: 13-11-21 * Time: 下午4:30 * To change this template use File | Settings | File Templates. */ on('export_map_end', 'JsonMap'); class JsonMapPlugin extends Plugin { // 默认配置 protected $options = array('json_map.is_gen' => false, 'json_map.path' => '{src.m3d_map_path}', 'json_map.suffix' => '{src.m3d_map_suffix}'); public function run($args) { if ($this->options['json_map.is_gen']) { $tool = $args[1]; $type = $args[2]; $map = json_encode($tool->map[$type]); contents_to_file(C('JSON_MAP.PATH') . '/' . $type . C('JSON_MAP.SUFFIX') . '.json', $map); } } }
<?php /** * 提供用于增量编译的各种数据 * User: zoujiawei * Date: 14-3-19 * Time: 下午3:37 * To change this template use File | Settings | File Templates. */ on('process_start', 'IncreMap::init'); on(array('css_import', 'css_background_change', 'js_import', 'js_replace', 'html_href_change'), 'IncreMap::update'); on('process_end', 'IncreMap::export'); class IncreMap { // 依赖链表 // 保存某一文件改变会影响其他文件的map, private static $belongMap = array(); private static $md5Map = array(); private static $revision = null; public static function init() { if (!C('INCRE.IS_INCRE')) { off('process_start', 'IncreMap::init'); off(array('css_import', 'css_background_change', 'js_import', 'js_replace', 'html_href_change'), 'IncreMap::update'); off('process_end', 'IncreMap::export'); return; } self::genMd5Map(); self::genLatestRevision(); } public static function update($params)
<?php include '../../src/dispatch.php'; on('GET', '/greet/:name', function () { echo "Hello there, " . params('name'); }); dispatch();
<?php include '../../src/dispatch.php'; config('dispatch.views', './views'); config('dispatch.layout', 'layout'); config('dispatch.flash_cookie', '_F'); on('GET', '/one', function () { flash('secret-message', 'Nifty, right?'); render('one'); }); on('GET', '/two', function () { render('two'); }); dispatch();
/** * Ensure that something will be handled * * @param string $event * @param callable $listener * @return mixed */ function ensure($event, callable $listener = null) { if ($listener) { on($event, $listener, 0); } // register default listener if ($listeners = listeners($event)) { return call_user_func_array(end($listeners), array_slice(func_get_args(), 2)); } }
/** * @param $event * @param callable $listener * @param int $priority */ function add_filter($event, callable $listener, $priority = 10) { on($event, $listener, $priority); }
<?php include '../../src/dispatch.php'; error(404, function () { redirect('/index', 301); }); on('GET', '/index', function () { echo "You're stuck!"; }); dispatch();
/** * @test */ public function it_returns_the_first_parameter_if_the_callback_returns_nothing() { $spy = 'spy'; on('filter_as_action_test', function () use(&$spy) { $spy = 'spider'; }); $filtered = apply_filters('filter_as_action_test', 'something'); $this->assertSame('spider', $spy); // ensures callback was called /** * Our callback returned nothing, therefore Hook will return for us. */ $this->assertSame('something', $filtered); }
send_file('./README.md', 'readme.txt', 60 * 60 * 24 * 365); }); prefix('books', function () { on('GET', '/list', function () { echo "book list"; }); prefix('chapters', function () { on('GET', '/list', function () { echo "chapter list"; }); }); }); bind('hashable', function ($hashable) { return md5($hashable); }); on('GET', '/md5/:hashable', function ($hash) { echo $hash . '-' . params('hashable'); }); bind('author', function ($name) { return strtoupper($name); }); bind('title', function ($title) { return sprintf('%s by %s', strtoupper($title), bind('author')); }); on('GET', '/authors/:author/books/:title', function ($author, $title) { echo $title; }); on('GET', '/list', function () { echo "different list"; }); dispatch();
define('PATH', dirname(__FILE__) . DS); define('LIBS', PATH . 'libs' . DS); function dd() { echo "<pre>"; call_user_func_array('var_dump', func_get_args()); echo "</pre>"; exit; } require LIBS . 'jsondb.php'; require LIBS . 'dispatch.php'; config('dispatch.url', '/git/JSONDB/test_3/api/'); JDB::configure(PATH . 'jdb' . DS); on('GET', '/', function () { $keys = array('id' => array('auto_increment'), 'name', 'login', 'date', 'guid', 'text'); $result = JDB::create('users', $keys); if (!$result) { var_dump(JDB::status(true)); } else { echo 'ok'; } $data = array('name' => 'Name', 'login' => 'Login', 'date' => 'Date', 'guid' => 'Guid', 'text' => 'Text'); dd(JDB::table('users')->insert($data)); }); on('POST', 'user', function () { $result = JDB::table('users')->insert(request_body()); if ($result) { echo "ok\n"; } }); dispatch();
<?php /** * 前端编译语言扩展 * User: zoujiawei * Date: 14-8-22 * Time: 下午2:12 */ C(include 'config.php'); on(array('process_css_start', 'process_js_start'), 'ProLanguage'); class ProLanguagePlugin extends Plugin { public function run($params) { $processor = $params[1]; switch ($processor->getType()) { case 'coffee': $this->compile($processor, C('COFFEE') . ' -bsp', 'js'); break; case 'sass': $this->compile($processor, C('SASS') . ' -s --compass -I ' . C('SRC.SRC_PATH'), 'css'); break; } } private function compile($processor, $exec, $ext) { $content = $processor->getContents(); $content = shell_exec_stdio($exec, $content); $relativePath = $processor->getRelativePath(); $relativePath = str_slice($relativePath, 0, -strlen($processor->getType())) . $ext; $processor->setType($ext);
<?php include '../../src/dispatch.php'; on('GET', '/index', function () { echo "GET /index invoked"; }); on('POST', '/index', function () { echo "POST /index invoked"; }); on('PUT', '/index', function () { echo "PUT /index invoked"; }); on('DELETE', '/index', function () { echo "DELETE /index invoked"; }); on('HEAD', '/index', function () { echo "HEAD /index invoked"; }); // match any request method on('*', '/anything', function () { echo $_SERVER['REQUEST_METHOD']; }); dispatch();
/** * Entry point for the library. * * @param string $method optional, for testing in the cli * @param string $path optional, for testing in the cli * * @return void */ function dispatch() { // see if we were invoked with params $method = strtoupper($_SERVER['REQUEST_METHOD']); if ($method == 'POST') { if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; } else { $method = params('_method') ? params('_method') : $method; } } // get the request_uri basename $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // remove dir path if we live in a subdir if ($base = config('dispatch.url')) { $base = rtrim(parse_url($base, PHP_URL_PATH), '/'); $path = preg_replace('@^' . preg_quote($base) . '@', '', $path); } else { // improved base directory detection if no config specified $base = rtrim(strtr(dirname($_SERVER['SCRIPT_NAME']), '\\', '/'), '/'); $path = preg_replace('@^' . preg_quote($base) . '@', '', $path); } // remove router file from URI if ($stub = config('dispatch.router')) { $stub = config('dispatch.router'); $path = preg_replace('@^/?' . preg_quote(trim($stub, '/')) . '@i', '', $path); } // dispatch it on($method, $path); }
function delete($path, $callback = null) { on('DELETE', $path, $callback); }
<?php /** * 处理requireJs,改变依赖模块路径 * User: zoujiawei * Date: 14-03-19 * Time: 下午4:30 * To change this template use File | Settings | File Templates. */ on('one_process_end', 'RequireJs'); class RequireJsPlugin extends Plugin { protected $options = array('requirejs.path' => null, 'requirejs.map' => 'js', 'requirejs.var' => '_MD5_HASHMAP'); public function run($params) { $item = $params[2]; if ($this->options['requirejs.path'] && $item['processor'] === 'js') { mark('requireJs插件开始处理' . $this->options['requirejs.path'], 'emphasize'); $this->options['requirejs.path'] = C('SRC.SRC_PATH') . $this->options['requirejs.path']; if (!file_exists($this->options['requirejs.path'])) { mark('"' . $this->options['requirejs.path'] . '"不存在,请检查m3d.php中requireJs配置', 'error'); return; } $tool = $params[1]; $map = $this->getMap($tool); $script = $this->genScript($map); $processor = Preprocess::getInstance('js'); $mapFiles = $this->options['requirejs.path']; if (is_string($mapFiles)) { $mapFiles = array($mapFiles); }
<?php include '../../src/dispatch.php'; before(function () { echo "before()<br>"; }); before(function () { echo "before() again<br>"; }); after(function () { echo "after()<br>"; }); after(function () { echo "after() again<br>"; }); filter('name', function ($name) { scope('greeting', "Hello there, {$name}!<br>"); }); filter('name', function ($name) { scope('farewell', "Bye bye, {$name}!<br>"); }); on('GET', '/greet/:name', function ($name) { echo scope('greeting'); echo scope('farewell'); }); dispatch();
<?php /** * 合图配置迁移,从老版本配置迁移至新版,可以考虑关掉该插件 * User: zoujiawei * Date: 14-3-31 * Time: 下午9:45 * To change this template use File | Settings | File Templates. */ on('imerge_start', 'ImergeMigrate'); class ImergeMigratePlugin extends Plugin { protected $options = array('imerge.is_migrate' => true); public function run($params) { if (C('IMERGE.IS_MIGRATE') && !file_exists(C('IMERGE_PATH') . '/' . C('IMERGE_IMAGE_DIR'))) { mark('正在进行合图配置迁移...', 'emphasize'); $tool = $params[1]; $path = $this->findOldM3dPath(); if ($path) { mark('找到旧配置文件,开始迁移...'); $imergePath = $path . '/imerge/*'; $entries = glob($imergePath); foreach ($entries as $entry) { if (is_dir($entry)) { $files = scandir($entry); foreach ($files as $file) { if ($file[0] === '_') { include $entry . '/' . $file; } }
<?php /** * 增量编译,依赖svn * User: zoujiawei * Date: 14-3-19 * Time: 下午12:17 * To change this template use File | Settings | File Templates. */ require_once 'IncreMap.class.php'; on('process_start', 'IncreProcess'); on('rm_old_build_file', 'IncreProcessPlugin::remain'); on('one_process_start', 'IncreProcessPlugin::importMap'); on('processor_fetch_files', 'IncreProcessPlugin::getFileList'); on('change_file', 'IncreProcessPlugin::addChangeList'); class IncreProcessPlugin extends Plugin { // 改变的文件,分为三类 const MODIFY = 'M'; const ADD = 'A'; const DELETE = 'D'; // 保存改变的文件 private static $files = array(self::MODIFY => array(), self::ADD => array(), self::DELETE => array()); protected $options = array('incre.is_incre' => false, 'incre.path' => '{SRC.M3D_PATH}/incre', 'incre.cache_dir' => '{incre.path}/cache', 'incre.map_filename' => 'file_belong_map.php', 'incre.md5_filename' => 'imerge_md5.php', 'incre.ver_filename' => 'version'); public function run($params) { // $oldRevision = 117093; $oldRevision = self::getPrevRevision(); // $oldRevision = null; // 检查m3d配置文件是否已改变 $path = defined('M3D_FILE') ? M3D_FILE : (defined('SRC_ROOT') ? SRC_ROOT . '/m3d.php' : null);