Skip to content

Instantly share code, notes, and snippets.

@alixaxel
Last active October 13, 2016 12:41
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alixaxel/5562152 to your computer and use it in GitHub Desktop.
Save alixaxel/5562152 to your computer and use it in GitHub Desktop.
Why...
<?php
namespace alixaxel;
class y
{
public static function Coalesce()
{
foreach (func_get_args() as $argument) {
if (isset($argument) === true) {
return $argument;
}
}
return null;
}
public static function cURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $attempts = 3)
{
$result = false;
if (is_resource($curl = curl_init()) === true) {
$default = [
CURLOPT_AUTOREFERER => true,
CURLOPT_ENCODING => '',
CURLOPT_FAILONERROR => true,
CURLOPT_FORBID_REUSE => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
];
if (strpos($url, '#') !== false) {
$url = strstr($url, '#', true);
}
$url = rtrim($url, '?&');
if (preg_match('~^(?:POST|PUT)$~i', $method) > 0) {
if (is_array($data) === true) {
foreach (preg_grep('~^@~', $data) as $key => $value) {
$data[$key] = sprintf('@%s', realpath(ltrim($value, '@')));
}
if (count($data) != count($data, COUNT_RECURSIVE)) {
$data = http_build_query($data, '', '&');
}
}
$default += [CURLOPT_POSTFIELDS => $data];
} else if ((is_array($data) === true) && (strlen($data = http_build_query($data, '', '&')) > 0)) {
$url = sprintf('%s%s%s', $url, (strpos($url, '?') === false) ? '?' : '&', $data);
}
if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0) {
$default += [CURLOPT_HEADER => true, CURLOPT_NOBODY => true];
}
$default += [CURLOPT_URL => $url, CURLOPT_CUSTOMREQUEST => strtoupper($method)];
if (isset($cookie) === true) {
if ($cookie === true) {
$cookie = sprintf('%s.txt', parse_url($url, PHP_URL_HOST));
}
if (strcmp('.', dirname($cookie)) === 0) {
$cookie = sprintf('%s/%s', realpath(sys_get_temp_dir()), $cookie);
}
$default += array_fill_keys([CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE], $cookie);
}
if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false)) {
$default += [CURLOPT_MAXREDIRS => 3, CURLOPT_FOLLOWLOCATION => true];
}
curl_setopt_array($curl, (array) $options + $default);
if (empty($attempts) === true) {
return $curl;
}
for ($i = 1; $i <= $attempts; ++$i) {
$result = curl_exec($curl);
if (($i == $attempts) || ($result !== false)) {
break;
}
usleep(pow(2, $i - 2) * 1000000);
}
curl_close($curl);
}
return $result;
}
public static function DB($query = null)
{
static $db = null;
static $result = [];
try {
if (isset($db, $query) === true) {
if (empty($result[$hash = crc32($query)]) === true) {
$result[$hash] = $db->prepare($query);
}
$data = array_slice(func_get_args(), 1);
if (count($data, COUNT_RECURSIVE) > count($data)) {
$data = iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($data)), false);
}
if ($result[$hash]->execute($data) === true) {
switch (strstr($query, ' ', true)) {
case 'INSERT':
case 'REPLACE':
return $db->lastInsertId();
case 'UPDATE':
case 'DELETE':
return $result[$hash]->rowCount();
case 'SELECT':
case 'EXPLAIN':
case 'PRAGMA':
case 'SHOW':
return $result[$hash];
}
return true;
}
return false;
} else if (isset($query) === true) {
$options = [
\PDO::ATTR_CASE => \PDO::CASE_NATURAL,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_OBJ,
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_ORACLE_NULLS => \PDO::NULL_NATURAL,
\PDO::ATTR_STRINGIFY_FETCHES => false,
];
if (preg_match('~^sqlite://([[:print:]]++)$~i', $query, $dsn) > 0) {
$options += [
\PDO::ATTR_TIMEOUT => 3,
];
$db = new \PDO(sprintf('sqlite:%s', $dsn[1]), null, null, $options);
$pragmas = [
'automatic_index' => 'ON',
'cache_size' => '32768',
'foreign_keys' => 'ON',
'journal_size_limit' => '0',
'locking_mode' => 'NORMAL',
'page_size' => '4096',
'recursive_triggers' => 'ON',
'secure_delete' => 'ON',
'synchronous' => 'NORMAL',
'temp_store' => 'FILE',
'journal_mode' => 'WAL',
'wal_autocheckpoint' => '16384',
];
if (strncasecmp('WIN', PHP_OS, 3) !== 0) {
$memory = 131072;
if (($page = intval(shell_exec('getconf PAGESIZE'))) > 0) {
$pragmas['page_size'] = $page;
}
if (is_readable('/proc/meminfo') === true) {
if (is_resource($handle = fopen('/proc/meminfo', 'rb')) === true) {
while (($line = fgets($handle, 1024)) !== false) {
if (sscanf($line, 'MemTotal: %d kB', $memory) == 1) {
$memory = round($memory / 131072) * 131072; break;
}
}
fclose($handle);
}
}
$pragmas['cache_size'] = intval($memory * 0.25 / ($pragmas['page_size'] / 1024));
$pragmas['wal_autocheckpoint'] = $pragmas['cache_size'] / 2;
}
foreach ($pragmas as $key => $value) {
$db->exec(sprintf('PRAGMA %s=%s;', $key, $value));
}
$db->sqliteCreateFunction('geo',
function ()
{
if (count($data = func_get_args()) < 4) {
$data = explode(',', implode(',', $data));
}
if (count($data = array_map('deg2rad', array_filter($data, 'is_numeric'))) != 4) {
return null;
}
return round(6378.14 * acos(sin($data[0]) * sin($data[2]) + cos($data[0]) * cos($data[2]) * cos($data[1] - $data[3])), 3);
}
);
$db->sqliteCreateFunction('json',
function ($data, $key)
{
if (preg_match('~^\x78[\x01\x5E\x9C\xDA]~', $data) > 0) {
$data = gzuncompress($data);
}
$data = json_decode($data, true);
foreach (array_filter(explode('.', $key), 'ord') as $key) {
if (isset($data[$key]) !== true) {
return null;
}
$data = $data[$key];
}
return (is_array($data) === true) ? json_encode($data) : $data;
},
2);
$db->sqliteCreateFunction('locale',
function ($data, $locale = 'root')
{
static $collators = [];
if (isset($collators[$locale]) !== true) {
$attributes = [
\Collator::NUMERIC_COLLATION => \Collator::ON,
];
$collators[$locale] = new \Collator($locale);
foreach ($attributes as $key => $value) {
$collators[$locale]->setAttribute($key, $value);
}
}
return $collators[$locale]->getSortKey($data);
}
);
$db->sqliteCreateFunction('php',
function ($callback)
{
return call_user_func_array($callback, array_slice(func_get_args(), 1));
}
);
$db->sqliteCreateFunction('regexp',
function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS')
{
if (isset($pattern, $data) !== true) {
return null;
}
return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
}
);
$db->sqliteCreateFunction('okapi_bm25f',
function ($data)
{
$b = 0.75;
$k1 = 2.0;
$data = str_split($data, 4);
foreach ($data as $key => $value) {
$data[$key] = current(unpack('L', $value));
}
$phrases = array_shift($data);
$columns = array_shift($data);
$weights = array_slice(func_get_args(), 1);
$data = [
'p' => $phrases,
'c' => $columns,
'x' => array_chunk(array_chunk(array_splice($data, 0, 3 * $columns * $phrases), 3), $columns),
'n' => array_shift($data),
'a' => array_splice($data, 0, $columns),
'l' => array_splice($data, 0, $columns),
's' => array_splice($data, 0, $columns),
];
$averageLength = 0;
$documentLength = 0;
for ($i = 0; $i < $columns; ++$i) {
$averageLength += $data['a'][$i];
$documentLength += $data['l'][$i];
if (array_key_exists($i, $weights) !== true) {
$weights[$i] = 1;
}
}
$result = 0;
$epsilon = 1 / ($data['n'] * $averageLength);
for ($i = 0; $i < $phrases; ++$i) {
for ($j = 0; $j < $columns; ++$j) {
$idf = log(($data['n'] - $data['x'][$i][$j][2] + 0.5) / ($data['x'][$i][$j][2] + 0.5));
$beta = 1 + (($data['x'][$i][$j][0] * ($k1 + 1)) / ($data['x'][$i][$j][0] + ($k1 * (1 - $b + ($b * ($documentLength / $averageLength))))));
if ($idf < 0) {
$idf = $epsilon;
}
$result += ($idf * $beta) * $weights[$j];
}
}
return $result;
}
);
$db->sqliteCreateAggregate('stddev_pop',
function (&$context, $row, $data)
{
if (isset($context) !== true) {
$context = [
'k' => 0,
'm' => 0,
's' => 0,
];
}
if (isset($data) === true) {
$context['s'] += ($data - $context['m']) * ($data - ($context['m'] += ($data - $context['m']) / ++$context['k']));
}
return $context;
},
function (&$context, $row)
{
if (empty($context['k']) === true) {
return null;
}
return sqrt($context['s'] / $context['k']);
},
1);
$db->sqliteCreateAggregate('var_pop',
function (&$context, $row, $data)
{
if (isset($context) !== true) {
$context = [
'k' => 0,
'm' => 0,
's' => 0,
];
}
if (isset($data) === true) {
$context['s'] += ($data - $context['m']) * ($data - ($context['m'] += ($data - $context['m']) / ++$context['k']));
}
return $context;
},
function (&$context, $row)
{
if (empty($context['k']) === true) {
return null;
}
return $context['s'] / $context['k'];
},
1);
$db->sqliteCreateCollation('UCA', function ($a, $b)
{
static $collator = null;
if (isset($collator) !== true) {
$collator = new \Collator('root');
foreach ([\Collator::NUMERIC_COLLATION => \Collator::ON] as $key => $value) {
$collator->setAttribute($key, $value);
}
}
return $collator->compare($a, $b);
});
} else if (preg_match('~^mysql://(?:(.+?)(?::(.+?))?@)?([^/:@]++)(?::(\d++))?/(\w++)/?$~i', $query, $dsn) > 0) {
$options += [
\PDO::ATTR_AUTOCOMMIT => true,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8" COLLATE "utf8_unicode_ci", time_zone = "+00:00";',
\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
];
$db = new \PDO(sprintf('mysql:host=%s;port=%s;dbname=%s', $dsn[3], $dsn[4], $dsn[5]), $dsn[1], $dsn[2], $options);
}
}
} catch (\PDOException $exception) {
if (is_null($db) === true) {
return false;
}
throw $exception;
}
return (isset($db) === true) ? $db : false;
}
public static function DOM($html, $xpath = null, $key = null, $default = false)
{
if (is_string($html) === true) {
$dom = new \DOMDocument();
if (libxml_use_internal_errors(true) === true) {
libxml_clear_errors();
}
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
if ((empty($html) !== true) && ($dom->loadHTML($html) === true) && (empty($dom->documentElement) !== true)) {
return self::DOM(simplexml_import_dom($dom), $xpath, $key, $default);
}
} else if (is_object($html) === true) {
if (isset($xpath) === true) {
$html = $html->xpath($xpath);
}
if (isset($key) === true) {
if (is_array($key) !== true) {
$key = explode('.', $key);
}
foreach ((array) $key as $value) {
$html = (is_object($html) === true) ? get_object_vars($html) : $html;
if ((is_array($html) !== true) || (array_key_exists($value, $html) !== true)) {
return $default;
}
$html = $html[$value];
}
}
return $html;
}
return $default;
}
public static function Dump()
{
foreach (func_get_args() as $argument) {
switch (gettype($argument)) {
case 'array':
case 'object':
$argument = rtrim(print_r($argument, true));
break;
case 'resource':
$argument = sprintf('%s (#%u)', get_resource_type($argument), $argument);
break;
default:
$argument = stripslashes(preg_replace("~^'|'$~", '', var_export($argument, true)));
break;
}
if (strcmp('cli', PHP_SAPI) !== 0) {
$style = [
'background: #ecf0f1',
'border: 1px solid #34495e',
'font: bold 12px monospace',
'margin: 0.6em',
'padding: 0.6em',
'text-align: left',
];
if (strpbrk($argument, '&<>') !== false) {
$argument = str_replace(['&', '<', '>'], ['&amp;', '&lt;', '&gt;'], $argument);
}
$argument = '<pre style="' . implode('; ', $style) . '">' . $argument . '</pre>';
} else if (strncasecmp('WIN', PHP_OS, 3) !== 0) {
$argument = sprintf('%c[%s;%u;%um%s%c[0m', 27, 0, 36, 49, $argument, 27);
}
echo $argument . "\n";
}
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
}
public static function Filter($data, $control = true, $encoding = null)
{
if (is_array($data) === true) {
foreach ($data as $key => $value) {
$data[$key] = self::Filter($value, $control, $encoding);
}
} else if (is_string($data) === true) {
if (preg_match('~[^\x00-\x7F]~', $data) > 0) {
if ((empty($encoding) === true) && (function_exists('mb_detect_encoding') === true)) {
$encoding = mb_detect_encoding($data, 'ASCII,ISO-8859-15,UTF-8', true);
}
$data = @iconv((empty($encoding) === true) ? 'UTF-8' : $encoding, 'UTF-8//IGNORE', $data);
}
return ($control === true) ? preg_replace('~\p{C}+~u', '', $data) : preg_replace(['~\R~u', '~[^\P{C}\t\n]+~u'], ["\n", ''], $data);
}
return $data;
}
public static function Flatten($data, $offset = null, $length = null)
{
try {
if ((isset($offset) === true) && (is_array($data) === true)) {
$data = array_slice($data, intval($offset), $length);
}
$data = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($data));
} catch (\Exception $exception) {
return [];
}
return iterator_to_array($data, false);
}
public static function JSON($data)
{
static $bitmask = null;
if (is_null($bitmask) === true) {
$options = [
'JSON_PRETTY_PRINT',
'JSON_UNESCAPED_SLASHES',
'JSON_UNESCAPED_UNICODE',
];
$bitmask = array_sum(array_map('constant', array_filter($options, 'defined')));
}
return json_encode($data, $bitmask);
}
public static function Period($since, $until, $interval)
{
$since = new \DateTimeImmutable($since);
if (is_int($until) !== true) {
$until = new \DateTimeImmutable($until);
}
if (preg_match('~^P(?:[0-9]+[DMWY]){0,3}(?:T(?:[0-9]+[HMS]){0,3})$~', $interval) > 0) {
$interval = new \DateInterval($interval);
} else {
$interval = \DateInterval::createFromDateString($interval);
}
return new \DatePeriod($since, $interval, $until);
}
public static function Profile($callbacks, $seconds = 15)
{
set_time_limit(0);
if (is_array($callbacks) !== true) {
$callbacks = explode('|', $callbacks);
}
$arguments = array_slice(func_get_args(), 2);
if (count($callbacks = array_filter($callbacks, 'is_callable')) > 0) {
$result = array_fill_keys($callbacks, [
'absolute' => 0,
'relative' => 0,
]);
foreach ($result as $key => $value) {
$reflection = null;
if (is_callable($key, true) === true) {
$reflection = (strpos($key, '::') !== false) ? new \ReflectionMethod($key) : new \ReflectionFunction($key);
}
if ((isset($reflection) === true) && ($reflection->getFileName() !== false)) {
if (($source = file($reflection->getFileName(), FILE_IGNORE_NEW_LINES)) !== false) {
$source = implode("\n", array_slice($source, $reflection->getStartLine() - 1, $reflection->getEndLine() - ($reflection->getStartLine() - 1)));
$result[$key]['source'] = [
'ccn' => 1,
'opcodes' => null,
'statements' => 0,
'lines' => [
'logical' => [],
'physical' => substr_count($source, "\n"),
],
];
if (function_exists('parsekit_compile_string') === true) {
$parsekit = parsekit_compile_string($source);
if ((is_array($parsekit) === true) && (array_key_exists('opcodes', $parsekit) === true)) {
$result[$key]['source']['opcodes'] = max(0, count($parsekit['opcodes']) - 1);
}
}
if (is_array($tokens = token_get_all(sprintf('<?php %s ?>', $source))) === true) {
$points = array_map('constant', array_filter([
'T_BOOLEAN_AND',
'T_BOOLEAN_OR',
'T_CASE',
'T_CATCH',
'T_ELSEIF',
'T_FINALLY',
'T_FOR',
'T_FOREACH',
'T_GOTO',
'T_IF',
'T_LOGICAL_AND',
'T_LOGICAL_OR',
'T_LOGICAL_XOR',
'T_WHILE',
], 'defined'));
foreach ($tokens as $token) {
if (is_array($token) === true) {
if ((in_array($token[0], [T_CLOSE_TAG, T_COMMENT, T_DOC_COMMENT, T_INLINE_HTML, T_OPEN_TAG], true) !== true) && (strlen(trim($token[1])) > 0)) {
if (in_array($token[0], $points, true) === true) {
++$result[$key]['source']['ccn'];
}
array_push($result[$key]['source']['lines']['logical'], $token[2]);
}
} else if (strncmp($token, '?', 1) === 0) {
++$result[$key]['source']['ccn'];
} else if (strncmp($token, ';', 1) === 0) {
++$result[$key]['source']['statements'];
}
}
$result[$key]['source']['lines']['logical'] = max(0, count(array_unique($result[$key]['source']['lines']['logical'])) - 1);
}
}
}
}
if (extension_loaded('xhprof') === true) {
$flags = [
XHPROF_FLAGS_CPU,
XHPROF_FLAGS_MEMORY,
];
$options = [
'ignored_functions' => [
'call_user_func',
'call_user_func_array',
'xhprof_disable',
],
];
foreach ($result as $key => $value) {
xhprof_enable(array_sum($flags), $options); call_user_func_array($key, $arguments);
if ((count($profile = array_slice(xhprof_disable(), -2, 1)) == 1) && (is_null($profile = array_shift($profile)) !== true)) {
$result[$key]['xhprof'] = [
'cpu' => $profile['cpu'],
'time' => $profile['wt'],
'memory' => $profile['mu'],
];
}
}
}
$i = 0;
$omega = microtime(true) + $seconds;
while ((microtime(true) <= $omega) && (++$i < PHP_INT_MAX)) {
foreach ($result as $key => $value) {
$value = microtime(true); call_user_func_array($key, $arguments); $result[$key]['absolute'] += microtime(true) - $value;
}
}
uasort($result,
function ($a, $b)
{
if ($a['absolute'] == $b['absolute']) {
return 0;
}
return ($a['absolute'] > $b['absolute']) ? 1 : -1;
}
);
$base = null;
foreach (array_keys($result) as $key) {
if (is_null($base) === true) {
$base = $result[$key]['absolute'];
}
foreach (['relative', 'absolute'] as $value) {
switch ($value) {
case 'absolute':
$result[$key][$value] /= $i;
break;
case 'relative':
$result[$key][$value] = $result[$key]['absolute'] / $base;
break;
}
$result[$key][$value] = number_format($result[$key][$value], ini_get('precision'), '.', '');
}
if (array_key_exists('xhprof', $result[$key]) === true) {
foreach (['cpu', 'time', 'memory'] as $value) {
$result[$key]['xhprof'][$value] = number_format($result[$key]['xhprof'][$value], 0, '.', ' ');
}
}
}
$result = [
$i => $result,
];
if (method_exists(__CLASS__, 'Dump') === true) {
self::Dump($result);
}
return $result;
}
return [];
}
public static function Render($path, $data = null, $return = false)
{
if (is_file($path) === true) {
extract((array) $data);
if (ob_start() === true) {
require($path);
if (($buffer = ob_get_clean()) !== false) {
if ($return === true) {
return $buffer;
}
echo $buffer;
}
}
}
return false;
}
public static function Romanize($string)
{
if (strpos($string = htmlentities(str_replace('ß', 'ss', $string), ENT_NOQUOTES | ENT_HTML5, 'UTF-8'), '&') !== false) {
$string = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|caron|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $string), ENT_NOQUOTES | ENT_HTML5, 'UTF-8');
}
if (preg_match('~[^[:ascii:]]~', $string) > 0) {
$latin = [
'a' => '~[ǎăāǻąǟắằẳẵặ]~u',
'A' => '~[ǍĂĀǺĄǞẮẰẲẴẶ]~u',
'ae' => '~[ǽǣ]~u',
'Ae' => '~[ǼǢ]~u',
'b' => '~[ɓ]~u',
'B' => '~[Ɓ]~u',
'c' => '~[ćċĉč]~u',
'C' => '~[ĆĊĈČ]~u',
'd' => '~[ďḍđɗð]~u',
'D' => '~[ĎḌĐƊÐ]~u',
'e' => '~[ėěĕēęẹǝəɛḝ]~u',
'E' => '~[ĖĚĔĒĘẸƎƏƐḜ]~u',
'g' => '~[ġĝǧğģɣ]~u',
'G' => '~[ĠĜǦĞĢƔ]~u',
'h' => '~[ĥḥħḧḫ]~u',
'H' => '~[ĤḤĦḦḪ]~u',
'I' => '~[İǏĬĪĨĮỊḮĬ]~u',
'i' => '~[ıǐĭīĩįịḯĬ]~u',
'ij' => '~[ij]~u',
'Ij' => '~[IJ]~u',
'j' => '~[ĵ]~u',
'J' => '~[Ĵ]~u',
'k' => '~[ķƙ]~u',
'K' => '~[ĶƘ]~u',
'l' => '~[ĺļłľŀ]~u',
'L' => '~[ĹĻŁĽĿ]~u',
'n' => '~[ńňņŋ]~u',
'N' => '~[ŃŇŅŊ]~u',
'o' => '~[ǒŏōőǫọǿơȫṏ]~u',
'O' => '~[ǑŎŌŐǪỌǾƠȪṎ]~u',
'r' => '~[ŕřŗ]~u',
'R' => '~[ŔŘŖ]~u',
'S' => '~[ŚŜŞȘṢ]~u',
's' => '~[śŝşșṣ]~u',
't' => '~[ťţṭŧ]~u',
'T' => '~[ŤŢṬŦ]~u',
'u' => '~[ǔŭūũűůųụưǖǘǚǜṳṻ]~u',
'U' => '~[ǓŬŪŨŰŮŲỤƯǕǗǙǛṲṺ]~u',
'w' => '~[ẃẁŵẅƿ]~u',
'W' => '~[ẂẀŴẄǷ]~u',
'x' => '~[ẍ]~u',
'X' => '~[Ẍ]~u',
'y' => '~[ỳŷȳỹƴ]~u',
'Y' => '~[ỲŶȲỸƳ]~u',
'z' => '~[źżžẓ]~u',
'Z' => '~[ŹŻŽẒ]~u',
];
$string = preg_replace($latin, array_keys($latin), $string);
}
return $string;
}
public static function Serve($on = null, $route = null, $callback = null)
{
static $root = null;
if (isset($_SERVER['REQUEST_METHOD']) !== true) {
$_SERVER['REQUEST_METHOD'] = 'CLI';
}
if ((empty($on) === true) || (strcasecmp($on, $_SERVER['REQUEST_METHOD']) === 0)) {
if (is_null($root) === true) {
$root = preg_replace('~/++~', '/', substr($_SERVER['PHP_SELF'], strlen($_SERVER['SCRIPT_NAME'])) . '/');
}
if (preg_match('~^' . str_replace(['#any', '#num'], ['[^/]++', '[0-9]++'], $route) . '~i', $root, $parts) > 0) {
return (empty($callback) === true) ? true : exit(call_user_func_array($callback, array_slice($parts, 1)));
}
}
return false;
}
public static function Slug($string, $slug = '-', $extra = null)
{
return strtolower(trim(preg_replace('~[^0-9a-z' . preg_quote($extra, '~') . ']++~i', $slug, self::Romanize($string)), $slug));
}
public static function Tree($path, $pattern = null, $recursive = true, $mode = \RecursiveIteratorIterator::SELF_FIRST)
{
if (is_dir($path = rtrim(str_replace('\\', '/', realpath($path)), '/')) === true) {
$result = new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS);
if ($recursive === true) {
$result = new \RecursiveIteratorIterator($result, $mode);
}
$result = array_keys(iterator_to_array($result, true));
if (isset($pattern) === true) {
$result = preg_grep('~' . trim($pattern, '~') . '~i', $result);
}
return $result;
}
return (strlen($path) > 0) ? [$path] : false;
}
public static function With($data, $key = null, $default = false)
{
if (isset($key) === true) {
if (is_array($key) !== true) {
$key = explode('.', $key);
}
foreach ((array) $key as $value) {
$data = (is_object($data) === true) ? get_object_vars($data) : $data;
if ((is_array($data) !== true) || (array_key_exists($value, $data) !== true)) {
return $default;
}
$data = $data[$value];
}
}
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment