/** * @constructor * * @param {array} $rules Redirect rules * @param {callable|string} $rules[][source] Regex, plain string startsWith() or callback matcher func, * @param {string} $rules[][target] String for redirection, can use backreference on regex, * @param {?int} $rules[][options] Redirection $options, or internal by default, * @param {?string} $options[source] Base path to match against requests, defaults to root. * @param {string|callable} $options[target] Redirects to a static target, or function($request) returns a string; */ public function __construct($rules) { // rewrite all URLs if (is_string($rules)) { $rules = array('*' => $rules); } $rules = util::wrapAssoc($rules); $this->rules = array_reduce($rules, function ($result, $rule) { $rule = array_select($rule, array('source', 'target', 'options')); // note: make sure source is callback if (is_string($rule['source'])) { // regex if (@preg_match($rule['source'], null) !== false) { $rule['source'] = matches($rule['source']); if (is_string($rule['target'])) { $rule['target'] = compose(invokes('uri', array('path')), replaces($rule['source'], $rule['target'])); } } else { if (!is_callable($rule['source'])) { $rule['source'] = startsWith($rule['source']); if (is_string($rule['target'])) { $rule['target'] = compose(invokes('uri', array('path')), replaces('/^' . preg_quote($rule['source']) . '/', $rule['target'])); } } } } if (!is_callable($rule['source'])) { throw new InvalidArgumentException('Source must be string, regex or callable.'); } $result[] = $rule; return $result; }, array()); }
function test_two() { $f = $this->f(); $g = $this->g(); $c = compose($f, $g); $x = 3; // sanity check $this->assertTrue($f($g($x)) === $x * 2 + 1); $this->assertTrue($f($g($x)) === $c($x)); }
public function test_compose_passes_results_from_end_to_first() { $makeCool = function ($name) { return $name . ' is cool.'; }; $subject = 'brian:scaturro'; $findNameAndMakeItCool = compose($makeCool, 'ucfirst', partialRight('strstr', true, ':')); $result = $findNameAndMakeItCool($subject); $this->assertEquals('Brian is cool.', $result); }
public function testShouldCallFirstFunctionWithInput() { $firstCall = null; $spy1 = function ($input) use(&$firstCall) { $firstCall = $input; }; $spy2 = function () { }; $f = compose($spy2, $spy1); $f(5); $this->assertEquals($firstCall, 5); }
function test_compose() { $a = function ($x) { return $x . 'a'; }; $b = function ($x) { return $x . 'b'; }; $c = function ($x) { return $x . 'c'; }; $fn = compose($a, $b, $c); return is_identical($fn('d'), 'dcba'); }
/** * @constructor * * @param {array} $options Options * @param {string|array} $options[source] (Required) directory of Javascript source files. * @param {string} $options[output] (Optional) directory for minified Javascript files, web root if omitted. */ public function __construct(array $options) { $options['source'] = (array) @$options['source']; if (!$options['source'] || array_filter(array_map(compose('not', funcAnd('is_string', 'is_dir', 'is_readable')), $options['source']))) { throw new ResolverException('Invalid source directory.'); } $this->srcPath = $options['source']; if (!empty($options['output'])) { if (!is_string($options['output']) || !is_dir($options['output']) || !is_writable($options['output'])) { throw new ResolverException('Invalid output directory.'); } $this->dstPath = $options['output']; } }
public function resolve(Request $request, Response $response) { $commandPath = $this->basePath . '/' . $request->uri(); if (!is_file($commandPath)) { throw new FrameworkException('Target command does not exist.'); } require_once $commandPath; $fx = compose(unshiftsArg('str_replace', ' ', ''), 'ucwords', 'strtolower', unshiftsArg('str_replace', '-', ' ')); $className = $fx($request->uri()); if (!class_exists($className) || is_a($className, 'IExecutableCommand', true)) { throw new FrameworkException("File is loaded, expecting class {$className} from {$commandPath}."); } $command = new $className(); $command->execute($request, $response); }
/** * @test */ public function it_tests_compose() { $string = "Hello I love things and stuff"; $expected = "HELLO-I-LOVE-THINGS-AND-STUFF"; $toUpper = function ($i) { return strtoupper($i); }; $splitBySpaces = function ($i) { return preg_split("/\\s/", $i); }; $mergeWithDash = function ($a) { return implode('-', $a); }; $capitalDashed = compose($mergeWithDash, $splitBySpaces, $toUpper); $this->assertEquals($expected, $capitalDashed($string)); }
public function send(EmailMessage $message, $data = []) { $recipient = function (Email $email) { return $email->getValue(); }; $commaSeparated = curry('implode', ', '); $formatRecipients = compose($commaSeparated, map($recipient)); $recipientsString = $formatRecipients($message->recipients); // Append the original recipients to the end of the email for debug purposes $message->body .= <<<EOT ------------- DEBUG INFO ---------------- Original recipients: {$recipientsString} ---------------------------------------------- EOT; // Alter the recipients to send them all to the dev mailbox $message->recipients = [$this->destinationEmail]; // Send the email using the normal mailer $this->mailer->send($message, $data); }
<table align="center"> <tr> <td class="content"><a href="' . $domain . '/index.php?action=messages&case=compose">Compose</a></td> <td class="content"><a href="' . $domain . '/index.php?action=messages&case=deleteall">Delete All</a></td> <td class="content"><a href="' . $domain . '/index.php?action=messages">Messages Home</a></td> </tr> </table>'; if (!isset($_GET['case'])) { $_GET['case'] = NULL; } switch ($_GET['case']) { default: inbox(); break; case 'compose': compose(); break; case 'reply': reply(); break; case 'read': read(); break; case 'delete': delete(); break; case 'deleteall': deleteall(); break; } ?>
}, 'compose3' => function ($x, $y, $z) { $f = flip('map', [$x, $y]); $c = compose($f, 'plus'); return $c($z) !== [$x + $z, $y + $z]; }, 'compose4' => function ($n) { return call(compose('id', 'id'), $n) !== $n; }, 'compose5' => function ($x, $y, $z) { return call(compose(plus($x), plus($y)), $z) !== $x + $y + $z; }, 'compose6' => function ($x, $y, $z) { return call(compose(flip('plus', $x), plus($y)), $z) !== $x + $y + $z; }, 'compose7' => function ($x, $y, $z) { $f = flip('map', [$x, $y]); $c = compose($f, 'plus'); return $c($z) !== [$x + $z, $y + $z]; }, 'compose8' => function ($x, $y) { $c = compose(with($x), 'plus'); return $c($y) !== $x + $y; }, 'sum' => function () { return sum($xs = range(0, mt_rand(1, 100))) !== array_reduce($xs, 'plus', 0); }, 'random1' => function () { return !is_int(random(null)); }, 'mem1' => function () { return mem('true') <= 0; }, 'upto1' => function ($n) { return count(upto($n % 100)) !== $n % 100; }, 'between1' => function () { return between(5, 10) !== [5, 6, 7, 8, 9, 10]; }, 'b_then' => function ($n) { return branch(thunk($n), null, thunk(true), null) !== $n; }, 'b_else' => function ($n) { return branch(null, thunk($n), thunk(false), null) !== $n;
} chdir($cwd); unset($cwd); // restore working directory return; // then exits. } } unset($res); } unset($fragments); } // static view assets redirection // note; composer.json demands the name to be of format "vendor/name". return @".private/modules/{$instance->name}/views/{$matches['2']}"; }), array('source' => '/^\\/faye\\/client.js/', 'target' => array('uri' => array('port' => 8080, 'path' => '/client.js'), 'options' => array('status' => 307))), array('source' => funcAnd(matches('/^(?!(?:\\/assets|\\/service))/'), compose('not', pushesArg('pathinfo', PATHINFO_EXTENSION))), 'target' => '/'))), 65); // Web Services $resolver->registerResolver(new resolvers\WebServiceResolver(array('prefix' => conf::get('web::resolvers.service.prefix', '/service'))), 60); // Post Processers $resolver->registerResolver(new resolvers\InvokerPostProcessor(array('invokes' => 'invokes', 'unwraps' => 'core\\Utility::unwrapAssoc')), 50); // Template resolver // $templateResolver = new resolvers\TemplateResolver(array( // 'render' => function($path) { // static $mustache; // if ( !$mustache ) { // $mustache = new Mustache_Engine(); // } // $resource = util::getResourceContext(); // return $mustache->render(file_get_contents($path), $resource); // } // , 'extensions' => 'mustache html'
/** * Put the specified command into process queue, optionally spawn a daemon to run it. * * @param {string} $command Command line to be run by the daemon. * * @param {array} $options Array with the following properties: * $options[$spawn] {bool} Whether to spawn a worker daemon immediately, default true. * $options[$singleton] {bool} Whether to skip the queuing when there is already an exact same command * in the process list, default false. * $options[$requeue] {bool} True to remove any previous inactive identical commands before pushing into * queue, default false. * $options[$kill] {int} When provided, a signal to be sent to all active identical commands. * $options[$type] {string} Identifier of command queue groups, commands will be drawn and run randomly * among groups, one at a time, by the daemon. * $options[$weight] {int} The likeliness of a command to be drawn within the same group, default 1. * $options[$capacity] {float} Percentage of occupation within the same group. To limit maximum active * processes within the same group to be 10, set this to 0.1. Default 0.2. * $options[$env] {array} Associative array of properties that will be available when target command starts. * $options[...] Any other values will be set into the process object, which will be accessible by spawn * processes with Process::get() method. */ public static function enqueue($command, $options = array()) { // For backward-compatibility, this parameter is originally $spawnProcess. if (is_bool($options)) { $options = array('$spawn' => $options); } else { $options = (array) $options; } $options = array_filter($options, compose('not', 'is_null')); $options += self::$defaultOptions; $process = array(Node::FIELD_COLLECTION => FRAMEWORK_COLLECTION_PROCESS, 'command' => $command) + array_select($options, array_filter(array_keys($options), compose('not', startsWith('$')))); // Remove identical inactive commands if ($options['$requeue']) { Node::delete(array(Node::FIELD_COLLECTION => FRAMEWORK_COLLECTION_PROCESS, 'command' => $command, 'pid' => null)); } // Sends the specified signal to all active identical commands if (is_int(@$options['$kill'])) { if (!function_exists('posix_kill')) { throw new ProcessException('Platform does not support posix_kill command.', ERR_SUPRT); } $activeProcesses = Node::get(array(Node::FIELD_COLLECTION => FRAMEWORK_COLLECTION_PROCESS, 'command' => $command, 'pid' => '!=null')); foreach ($activeProcesses as $process) { posix_kill($process['pid'], $options['$kill']); } unset($activeProcesses); } // Only pushes the command into queue when there are no identical process. if ($options['$singleton']) { $identicalProcesses = Node::get(array(Node::FIELD_COLLECTION => FRAMEWORK_COLLECTION_PROCESS, 'command' => $command)); // Process object will be updated if ($identicalProcesses) { $process['id'] = $identicalProcesses[0]['id']; } unset($identicalProcesses); } // Copy process related fields. foreach (['type', 'weight', 'capacity'] as $field) { if (isset($options["\${$field}"])) { $process[$field] = $options["\${$field}"]; } } // Default start time to now if (empty($process['start_time']) || !strtotime($process['start_time'])) { $process['start_time'] = date('c'); } // Push or updates target process. $res = Node::set($process); if ($res === false) { throw new ProcessException('Unable to enqueue process.', self::ERR_ENQUE); } if (is_numeric($res)) { $process['id'] = $res; } unset($res); $env = (array) @$options['$env']; if ($env) { $env = array('env' => ContentEncoder::json($env)); } unset($options['$env']); // Only spawn a worker if target process is not already working. if (@$options['$spawn'] && !@$process['pid'] && !self::spawnWorker($env)) { throw new ProcessException('Unable to spawn daemon worker.', self::ERR_SPAWN); } return $process; }
function seldef(array $keys, $list, $filter = null) { $function = compose(filters($filter), selects($keys)); return $function($list); }
<?php /*! HeadlessWorker.php | Takes care of headless process ahead. */ require_once '.private/scripts/Initialize.php'; use core\Database; use core\Log; use framework\Bayeux; use framework\Configuration as conf; use framework\Service; use models\WorkInstance; use models\TaskInstance; $taskInstance = new TaskInstance(); // Consumes Headless tasks ahead. $tasks = Database::fetchArray('SELECT `nextTask` FROM `WorkInstance` WHERE `nextTask` IN (SELECT `uuid` FROM `TaskInstance` WHERE `type` = \'Headless\') AND `state` = \'Open\';'); $tasks = array_map(compose('core\\Utility::unpackUuid', prop('nextTask')), $tasks); if ($tasks) { Log::debug(sprintf('%d headless tasks found!', count($tasks)), $tasks); } $serviceOptions = array('resolver' => new framework\Resolver()); $serviceOptions['resolver']->registerResolver(new resolvers\WebServiceResolver(array('prefix' => conf::get('web::resolvers.service.prefix', '/service')))); foreach ($tasks as $taskUuid) { // renew response object for each call $serviceOptions['response'] = new framework\Response(array('autoOutput' => false)); Service::call('_/WorkInstance', 'process', array($taskUuid), $serviceOptions); // todo: send bayeux update message to notify related users about the task update. }
/** * HTTP request headers * * Subsequent updates to the same header will append to it, to remove a header, * pass a falsy value as $value. * * Usage: * 1. $response->header('Content-Type: text/html'); * 2. $response->header('Content-Length', strlen($content)); * * @param {string} $key Either the whole header string, or the header key. * @param {?string} $value When value is specified, $key will be used as key. * @param {?boolean} Replace previous headers with the same name. */ public function header($key = null, $value = null, $replace = false) { if ($key === null) { return $this->headers; } else { if (!$value) { if (preg_match('/^([\\w-_]+)\\s*:\\s*(.+)$/', trim($key), $matches)) { $key = $matches[1]; $value = $matches[2]; } else { $value = @$this->headers[$key]; if (is_array($value) && count($value) == 1) { return $value[0]; } else { return $value; } } } } // Normalize capitalization of header keys $key = implode('-', array_map(compose('ucfirst', 'strtolower'), explode('-', trim($key)))); if ($value) { if (!$replace) { $this->headers[$key] = array_values(array_unique(array_merge((array) @$this->headers[$key], (array) $value))); } else { $this->headers[$key] = (array) $value; } } else { if ($value === null) { return @$this->headers[$key]; } else { unset($this->headers[$key]); } } return $this; }
public function map($f) { return new self(compose($f, $this->f)); }
/** * Because POST can be JSON, or other formats in the future, we cannot simply * use $_REQUEST. * * Another difference with $_REQUEST is this also counts $_COOKIE. */ public function param($name = null, $type = null) { /*! Note @ 23 Apr, 2015 * POST validation should be simple, just match it with some hash key stored in sessions. */ // TODO: Do form validation, take reference from form key of Magento. $result = $this->_param($type); if (is_array($result)) { // remove meta keys and sensitive values $result = array_filter_keys($result, funcAnd(notIn([ini_get('session.name')]), compose('not', startsWith($this->metaPrefix)))); } if ($name === null) { return $result; } else { $fx = prop($name); return $fx($result); } }
/** * @protected * * Returns all composer.json, this respects list range and list order, but * filtering is not supported. */ function find(array $filter = array()) { // list tasks modules $modules = glob('.private/modules/*/*/composer.json'); $modules = array_map(compose('core\\ContentDecoder::json', 'file_get_contents'), $modules); $modules = array_map(function ($module) { return (new Task($module))->afterLoad(); }, $modules); // @sorter, list order if (isset($filter['@sorter'])) { $sorter = array(); foreach ($filter['@sorter'] as $key => $value) { // numeric key, use value as ASC sorting if (is_numeric($key) && is_string($value)) { $key = $value; $value = true; } $sorter[] = array_map(prop($key), $modules); $sorter[] = $value ? SORT_ASC : SORT_DESC; } $sorter[] =& $modules; call_user_func_array('array_multisort', $sorter); unset($sorter); } // @limits, list range if (isset($filter['@limits'])) { $modules = call_user_func_array('array_slice', array_merge(array($modules), $filter['@limits'])); } return $modules; }
/** * @expectedException InvalidArgumentException */ function testComposeWithJustOneInvalidArg() { $fn = function () { }; compose($fn, 'foo', $fn); }
function writebody() { global $db, $domain, $suserid, $sitename, $cachelife, $template, $gamesfolder, $thumbsfolder, $limitboxgames, $seo_on, $blogentriesshown, $enabledcode_on, $comments_on, $directorypath, $autoapprovecomments, $gamesonpage, $abovegames, $belowgames, $showwebsitelimit, $supportemail, $showblog, $blogentriesshown, $blogcharactersshown, $blogcommentpermissions, $blogcommentsshown, $blogfollowtags, $blogcharactersrss, $usrdata, $userid; if (!isset($suserid)) { echo '<div class="error">Please login.</div>'; exit; } function inbox() { global $db, $domain, $userid; $w = $db->query("SELECT * FROM fas_messages WHERE to_userid='{$userid}' ORDER BY datesent DESC"); echo '<h2>Messages</h2> <table width="100%" border="0" align="center"> <tr> <th class="header">#</th> <th class="header">Details</th> <th class="header">Status</th> <th class="header">Options</th> </tr> '; while ($iw = $db->fetch_row($w)) { if ($iw['status'] == 0) { $status = '<font color="green">Unread</font>'; } else { $status = '<font color="red">Read</font>'; } $gr = $db->fetch_row($db->query("SELECT userid, username FROM fas_users WHERE userid='{$iw['from_userid']}'")); echo ' <tr> <td class="content"><div align="center">' . $iw['ID'] . '</div></td> <td class="content"><small> Subject: ' . $iw['subject'] . '<br /> Date: ' . date('d/m/Y', $iw['datesent']) . '<br /> From: ' . $gr['username'] . '<br /> </small></td> <td class="content"><div align="center">' . $status . '</div></td> <td class="content" align="center"> <div align="center"> [<a href="' . $domain . '/index.php?action=messages&case=delete&ID=' . $iw['ID'] . '">Delete</a> - <a href="' . $domain . '/index.php?action=messages&case=read&ID=' . $iw['ID'] . '">Read</a>]</div></td> </tr>'; } echo '</table> <br /> <div align="center"> <a href="' . $domain . '/index.php?action=messages&case=deleteall">Delete All</a> </div>'; } function read() { global $db, $domain, $template, $userid; $ID = abs((int) $_GET['ID']); $ir = $db->query("SELECT * FROM dd_messages WHERE to_userid='{$userid}' AND ID='{$ID}'"); $or = $db->fetch_row($ir); if (!$db->num_rows($ir)) { echo 'Either you do not own that message or it does not exist.'; include 'templates/' . $template . '/footer.php'; exit; } $db->query("UPDATE fas_messages SET status='1' WHERE ID='{$ID}'"); $ud = $db->fetch_row($db->query("SELECT username, userid FROM fas_users WHERE userid='{$or['from_userid']}'")); $message = str_replace('\\n', '<br />', $or['content']); $replysubject = 'Re: ' . $or['subject']; echo '<table width="95%" border="0" align="center"> <tr> <td class="header" width="30%">Message From:</td> <td class="content">' . $ud['username'] . '</td> </tr> <tr> <td class="header">Subject Details</td> <td class="content">' . $or['subject'] . '<br /><small>' . date('d/m/Y', $or['datesent']) . '</small></td> </tr> <tr> <td class="header" colspan="2"><div align="center">Message</div></td> </tr> <tr> <td class="content" colspan="2" valign="top">' . $message . '</td> </tr> </table> <table width="95%" border="0" align="center"> <tr> <td class="header" colspan="2">Quick Reply</td></tr> <tr> <td class="content" colspan="2"> <form action="' . $domain . '/index.php?action=messages&case=reply&;ID=' . $or['from_userid'] . '" method="post"> <textarea cols="50" rows="6" name="message"></textarea><br> <input name="to" value="' . $or['from_userid'] . '" type="hidden"> <input size="37" name="subject" value="' . $replysubject . '" type="hidden"> <input name="submit" value="Send" type="submit"> </form> </td> </tr> <td class="header" colspan="2">Your Conversation with ' . $ud['username'] . '.</td> </table> <table width="95%" border="0" align="center"> <tr> <th class="header">From/Date</th> <th class="header">Message</th> </tr>'; $senderid = $or['from_userid']; $tt = $db->query("SELECT * FROM fas_messages WHERE to_userid='{$userid}' AND from_userid='{$senderid}' ORDER BY datesent DESC") or die(mysql_error()); while ($row = mysql_fetch_array($tt)) { $op = $db->fetch_row($db->query("select username from fas_users where userid='{$row['from_userid']}'")); echo ' <tr align="center"> <td class="content">' . $op['username'] . ' <br /><small>On: ' . date('d/m/Y', $row['datesent']) . '</small></td> <td class="content">' . $row['content'] . '</td> </tr>'; } echo '</table>'; } function reply() { global $userid, $domain, $db; $to = abs((int) $_POST['to']); $message = clean($_POST['message']); $subject = clean($_POST['subject']); if (!$to || !$message) { echo "All fields must be filled in!"; include 'templates/' . $template . '/footer.php'; exit; } $date = time(); $db->query("INSERT INTO dd_messages SET\nfrom_userid='{$userid}',\nto_userid='{$to}',\nsubject='{$subject}',\ncontent = '{$message}',\nstatus = '0',\ndatesent='{$date}'"); echo 'Message sent.'; } function compose() { global $userid, $domain, $db, $template; if (isset($_POST['submit'])) { $to = abs((int) $_POST['to']); $message = clean($_POST['message']); $subject = clean($_POST['subject']); if (!$to || !$message) { echo "All fields must be filled in!"; include 'templates/' . $template . '/footer.php'; exit; } $date = time(); $db->query("INSERT INTO fas_messages SET\nfrom_userid='{$userid}',\nto_userid='{$to}',\nsubject='{$subject}',\ncontent = '{$message}',\nstatus = '0',\ndatesent='{$date}'"); echo 'Message sent.'; include 'templates/' . $template . '/footer.php'; exit; } if ($to == '') { $to = ''; } else { $to = $ID; } echo ' <form action="' . $domain . '/index.php?action=messages&case=compose" method="POST"> <table width="95%" border="0" align="center"> <tr> <td class="header" width="30%">To (Userid#):</td> <td class="content" width="30%"><input type="text" name="to" value="' . $to . '" size="35"></td> </tr> <tr> <td class="header" width="30%">Subject:</td> <td class="content" width="30%"><input type="text" name="subject" value="[No Subject]" size="35"></td> </tr> <tr> <td colspan="2" class="header" align="center">Message</td> </tr> <tr> <td colspan="2" class="content"> <textarea cols="65" rows="6" name="message"></textarea> </td> </tr> <tr> <td colspan="2" align="center" class="content"><input type="submit" name="submit" value="Send"></td> </tr> </table> </form> '; } function delete() { $ID = abs((int) $_GET['ID']); global $db, $userid; $db->query("DELETE FROM fas_messages WHERE ID='{$ID}' AND to_userid='{$userid}'"); echo 'Deleted.'; } function deleteall() { global $db, $userid; $db->query("DELETE FROM fas_messages WHERE to_userid='{$userid}'"); } $userid = $suserid; echo ' <table align="center"> <tr> <td class="content"><a href="' . $domain . '/index.php?action=messages&case=compose">Compose</a></td> <td class="content"><a href="' . $domain . '/index.php?action=messages&case=deleteall">Delete All</a></td> <td class="content"><a href="' . $domain . '/index.php?action=messages">Messages Home</a></td> </tr> </table>'; switch ($_GET['case']) { default: inbox(); break; case 'compose': compose(); break; case 'reply': reply(); break; case 'read': read(); break; case 'delete': delete(); break; case 'deleteall': deleteall(); break; } }
<?php require '../vendor/autoload.php'; $request = trim(strtok($_SERVER['REQUEST_URI'], '?'), '/'); if (preg_match('/^page\\/[1-9][0-9]*$/', $request)) { $page = (int) explode('/', $request)[1]; $isPage = true; } else { $page = 1; $isPage = false; } $output = cache($request, function () use($request, $page, $isPage) { if ($request && !$isPage) { foreach (posts() as $post) { if (config('post.url') . $post['meta']['slug'] == $request) { $filter = compose('markdown', 'pygments', 'graphviz'); $post['post'] = $filter($post['post']); return tmpl('post', $post); } } } else { $posts = page($page); if ($posts->key() !== null) { return tmpl('main', ['posts' => $posts, 'page' => $page]); } } return false; }); if ($output === false) { header('HTTP/1.0 404 Not Found'); echo tmpl('404');
/** * Determine whether an array is associative. * * To determine a numeric array, inverse the result of this function. */ static function isAssoc($value, $strict = false) { /*! Note * This is the original version found somewhere in the internet, * keeping it to respect the author. * * Problem is numeric arrays with inconsecutive keys will return * as associative, might be a desired outcome when doing json_encode, * but this led to a not very descriptive function name. * * return is_array($value) && count($value) && * count(array_diff_key($value, array_keys(array_keys($value)))); */ $ret = is_array($value) && $value && array_filter(array_keys($value), compose('not', 'is_numeric')); // numeric keys must be consecutive to be NOT assoc (favors json_encode) if ($strict && !$ret) { $ret = $ret || array_sum(array_keys($value)) != (count($value) - 1) / 2 * count($value); } return $ret; }
return $x($z, $y($z)); }, 'zip' => function ($arr1, $arr2) { return foldr(function ($acc, $val) use($arr1, $arr2) { $lookup = subscript($val); $el1 = $lookup($arr1); $el2 = $lookup($arr2); return merge($acc, [[$el1, $el2]]); }, [], keys($arr1)); }, 'dup' => function ($x) { return [$x, $x]; }, 'swap' => function ($arr) { return merge([$arr[1], $arr[0]], array_slice($arr, 2)); }, 'first' => function ($f, $arr) { return cons($f(subscript(0, $arr)), array_slice($arr, 1)); }, 'second' => function ($f) { return compose('swap', first($f), 'swap'); }, 'head' => function ($arr) { return $arr[0]; }, 'delay' => function ($f, $args, $_) { return call_user_func_array($f, $args); }]); defun('format', function ($x) { return is_float($x) ? number_format($x, 6) : (is_array($x) ? map('format', $x) : $x); }); defun('benchmark', function ($f, $x) { $time = microtime(true); $f($x); return microtime(true) - $time; }); defun('tabulate', function ($h1, $h2, $arr) { return key_foldr(function ($str, $row) {
<?php function compose($f, $g) { return create_function('$x', 'return ' . var_export($f, true) . '(' . var_export($g, true) . '($x));'); } $trim_strlen = compose('strlen', 'trim'); echo $result = $trim_strlen(' Test '), "\n"; // prints 4
/** * Inspired by os.networkInterfaces() from node.js. * * @return {array} Returns a brief info of available network interfaces. */ public static function networkInterfaces() { switch (strtoupper(PHP_OS)) { case 'DARWIN': // MAC OS X $res = preg_split('/\\n/', @`ifconfig`); $res = array_filter(array_map('trim', $res)); $result = array(); foreach ($res as $row) { if (preg_match('/^(\\w+\\d+)\\:\\s+(.+)/', $row, $matches)) { $result['__currentInterface'] = $matches[1]; $result[$result['__currentInterface']]['__internal'] = false !== strpos($matches[2], 'LOOPBACK'); } else { if (preg_match('/^inet(6)?\\s+([^\\/\\s]+)(?:%.+)?/', $row, $matches)) { $iface =& $result[$result['__currentInterface']]; @($iface[] = array('address' => $matches[2], 'family' => $matches[1] ? 'IPv6' : 'IPv4', 'internal' => $iface['__internal'])); unset($iface); } } unset($matches); } unset($row, $res); unset($result['__currentInterface']); return array_filter(array_map(compose('array_filter', removes('__internal')), $result)); case 'LINUX': // $ifaces = `ifconfig -a | sed 's/[ \t].*//;/^\(lo\|\)$/d'`; // $ifaces = preg_split('/\s+/', $ifaces); $res = preg_split('/\\n/', @`ip addr`); $res = array_filter(array_map('trim', $res)); $result = array(); foreach ($res as $row) { if (preg_match('/^\\d+\\:\\s+(\\w+)/', $row, $matches)) { $result['__currentInterface'] = $matches[1]; } else { if (preg_match('/^link\\/(\\w+)/', $row, $matches)) { $result[$result['__currentInterface']]['__internal'] = strtolower($matches[1]) == 'loopback'; } else { if (preg_match('/^inet(6)?\\s+([^\\/]+)(?:\\/\\d+)?.+\\s([\\w\\d]+)(?:\\:\\d+)?$/', $row, $matches)) { @($result[$matches[3]][] = array('address' => $matches[2], 'family' => $matches[1] ? 'IPv6' : 'IPv4', 'internal' => Utility::cascade(@$result[$matches[3]]['__internal'], false))); } } } unset($matches); } unset($row, $res); unset($result['__currentInterface']); return array_filter(array_map(compose('array_filter', removes('__internal')), $result)); case 'WINNT': // Currently not supported. // Currently not supported. default: return false; } }