Skip to content

Instantly share code, notes, and snippets.

@alixaxel

alixaxel/y.php

Last active Oct 13, 2016
Embed
What would you like to do?
Why...
<?php
namespace alixaxel;
class y
{
public static function Dump()
{
foreach (func_get_args() as $argument)
{
if (is_resource($argument) === true)
{
$result = sprintf('%s (#%u)', get_resource_type($argument), $argument);
}
else if ((is_array($argument) === true) || (is_object($argument) === true))
{
$result = rtrim(print_r($argument, true));
}
else
{
$result = stripslashes(preg_replace("~^'|'$~", '', var_export($argument, true)));
}
if (strcmp('cli', PHP_SAPI) !== 0)
{
$style = array
(
'background: #ecf0f1',
'border: 1px solid #34495e',
'font: bold 12px monospace',
'margin: 0.6em',
'padding: 0.6em',
'text-align: left',
);
if (strpbrk($result, '<>') !== false)
{
$result = str_replace(array('<', '>'), array('&lt;', '&gt;'), $result);
}
$result = '<pre style="' . implode('; ', $style) . '">' . $result . '</pre>';
}
else if (strncasecmp('WIN', PHP_OS, 3) !== 0)
{
$result = sprintf('%c[%s;%u;%um%s%c[0m', 27, 0, 36, 49, $result, 27);
}
echo $result . "\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(array('~\R~u', '~[^\P{C}\t\n]+~u'), array("\n", ''), $data);
}
return $data;
}
public static function Map($path, $grep = null, $recursive = true)
{
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, \RecursiveIteratorIterator::SELF_FIRST);
}
$result = array_keys(iterator_to_array($result, true));
if (strlen($grep) > 0)
{
$result = preg_grep('~' . trim($grep, '~') . '~', $result);
}
return $result;
}
return (strlen($path) > 0) ? array($path) : false;
}
public static function Mark($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)
{
$i = 0;
$omega = microtime(true) + $seconds;
$result = array_fill_keys($callbacks, array
(
'memory' => 0,
'absolute' => 0,
'relative' => 0,
));
if (($memory = memory_get_usage()) > 0)
{
foreach ($result as $key => $value)
{
$memory = memory_get_usage();
if (is_null($output = call_user_func_array($key, $arguments)) !== true)
{
$result[$key]['memory'] = memory_get_usage() - $memory;
}
unset($output);
}
}
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'])
{
if ($a['memory'] == $b['memory'])
{
return 0;
}
return ($a['memory'] > $b['memory']) ? 1 : -1;
}
return ($a['absolute'] > $b['absolute']) ? 1 : -1;
});
$base = null;
foreach (array_keys($result) as $key)
{
if (is_null($base) === true)
{
$base = $result[$key]['absolute'] / $i;
}
foreach (array('absolute', 'relative', 'memory') as $value)
{
if (in_array($value, array('absolute', 'relative')) === true)
{
if ($value == 'absolute')
{
$result[$key][$value] /= $i;
}
else if ($value == 'relative')
{
$result[$key][$value] = $result[$key]['absolute'] / $base;
}
$result[$key][$value] = number_format($result[$key][$value], ini_get('precision'), '.', '');
}
else
{
$result[$key]['memory'] = number_format($result[$key]['memory'], 0, '.', ' ');
}
}
}
$result = array
(
$i => $result,
'arguments' => $arguments,
);
if (method_exists(__CLASS__, 'Dump') === true)
{
self::Dump($result);
}
return $result;
}
return array();
}
public static function Query($query = null)
{
static $db = null;
static $result = array();
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]->fetchAll();
}
return true;
}
return false;
}
else if (isset($query) === true)
{
$options = array
(
\PDO::ATTR_CASE => \PDO::CASE_NATURAL,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\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 += array
(
\PDO::ATTR_TIMEOUT => 0,
);
$db = new \PDO(sprintf('sqlite:%s', $dsn[1]), null, null, $options);
$pragmas = array
(
'busy_timeout' => '0',
'cache_size' => '8192',
'encoding' => '"UTF-8"',
'foreign_keys' => 'ON',
'journal_mode' => 'WAL',
'journal_size_limit' => '67110000',
'legacy_file_format' => 'OFF',
'page_size' => '4096',
'recursive_triggers' => 'ON',
'secure_delete' => 'ON',
'synchronous' => 'NORMAL',
'temp_store' => 'MEMORY',
'wal_autocheckpoint' => '4096',
);
if (strncasecmp('WIN', PHP_OS, 3) !== 0)
{
if (($page = intval(shell_exec('getconf PAGESIZE'))) > 0)
{
$pragmas['page_size'] = $page;
}
if ((is_file('/proc/meminfo') === true) && (is_readable('/proc/meminfo') === true))
{
$memory = 131072;
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 round(6378.14 * acos(sin($data[0]) * sin($data[2]) + cos($data[0]) * cos($data[2]) * cos($data[1] - $data[3])), 3);
}
return null;
});
$db->sqliteCreateFunction('json', function ($data, $key)
{
if ((ord($data[0]) == 0x78) && (in_array(ord($data[1]), array(0x01, 0x5E, 0x9C, 0xDA)) === true))
{
$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);
}
else if (preg_match('~^mysql://(?:(.+?)(?::(.+?))?@)?([^/:@]++)(?::(\d++))?/(\w++)/?$~i', $query, $dsn) > 0)
{
$options += array
(
\PDO::ATTR_AUTOCOMMIT => true,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8" COLLATE "utf8_general_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 $e)
{
return false;
}
catch (\Exception $e)
{
return false;
}
return (isset($db) === true) ? $db : false;
}
public static function Reduce($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 $e)
{
return array();
}
return iterator_to_array($data, false);
}
public static function Render($path, $data = null, $tidy = null, $return = false)
{
if (is_file($path) === true)
{
extract((array) $data);
if (ob_start() === true)
{
require($path);
if (($buffer = ob_get_clean()) !== false)
{
if ((is_null($tidy) === true) && ((strncasecmp($buffer, '<!DOCTYPE', 9) === 0) || (strncasecmp($buffer, '<html', 5) === 0)))
{
$tidy = true;
}
if ((isset($tidy) === true) && ($tidy !== false))
{
$options = array
(
'force-output' => true,
);
if (is_int($tidy) === true)
{
$options['indent-spaces'] = $tidy;
}
$buffer = self::Tidy($buffer, $options);
}
if ($return === true)
{
return $buffer;
}
echo $buffer;
}
}
}
return false;
}
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(array('#any', '#num'), array('[^/]++', '[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)
{
$string = \Normalizer::normalize($string, \Normalizer::FORM_KD);
if (strpos($string = htmlentities($string, ENT_QUOTES, '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_QUOTES, 'UTF-8');
}
return strtolower(trim(preg_replace('~[^0-9a-z' . preg_quote($extra, '~') . ']++~i', $slug, $string), $slug));
}
public static function Tidy($string, $options = null, $encoding = 'utf8')
{
if (extension_loaded('tidy') === true)
{
$default = array
(
'anchor-as-name' => false,
'break-before-br' => true,
'char-encoding' => $encoding,
'decorate-inferred-ul' => false,
'doctype' => 'omit',
'drop-empty-paras' => false,
'drop-font-tags' => true,
'drop-proprietary-attributes' => false,
'force-output' => false,
'hide-comments' => false,
'indent' => true,
'indent-attributes' => false,
'indent-spaces' => 2,
'input-encoding' => $encoding,
'join-styles' => false,
'logical-emphasis' => false,
'merge-divs' => false,
'merge-spans' => false,
'new-blocklevel-tags' => 'article aside audio details dialog figcaption figure footer header hgroup menutidy nav section source summary track video',
'new-empty-tags' => 'command embed keygen source track wbr',
'new-inline-tags' => 'canvas command data datalist embed keygen mark meter output progress time wbr',
'newline' => 0,
'numeric-entities' => false,
'output-bom' => false,
'output-encoding' => $encoding,
'output-html' => true,
'preserve-entities' => true,
'quiet' => true,
'quote-ampersand' => true,
'quote-marks' => false,
'repeated-attributes' => 1,
'show-body-only' => true,
'show-warnings' => false,
'sort-attributes' => 1,
'tab-size' => 4,
'tidy-mark' => false,
'vertical-space' => true,
'wrap' => 0,
);
$doctype = $menu = null;
if ((strncasecmp($string, '<!DOCTYPE', 9) === 0) || (strncasecmp($string, '<html', 5) === 0))
{
$doctype = '<!DOCTYPE html>'; $options['show-body-only'] = false;
}
$options = (is_array($options) === true) ? array_merge($default, $options) : $default;
if (strpos($string, '<menu') !== false)
{
$menu = array
(
'<menu' => '<menutidy',
'</menu' => '</menutidy',
);
}
if (isset($menu) === true)
{
$string = str_replace(array_keys($menu), $menu, $string);
}
$string = tidy_repair_string($string, $options, $encoding);
if (empty($string) !== true)
{
if (isset($menu) === true)
{
$string = str_replace($menu, array_keys($menu), $string);
}
if (isset($doctype) === true)
{
$string = $doctype . "\n" . $string;
}
return $string;
}
}
return 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
You can’t perform that action at this time.