PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/core/utilities.php

http://github.com/pateketrueke/tetlphp
PHP | 427 lines | 250 code | 93 blank | 84 comment | 26 complexity | 961b19bccebd2a285dc007a0cab978d4 MD5 | raw file
  1. <?php
  2. /**
  3. * Utility functions library
  4. */
  5. /**#@+
  6. * Slug transformation options
  7. */
  8. define('SLUG_STRICT', 1);
  9. define('SLUG_LOWER', 2);
  10. define('SLUG_TRIM', 4);
  11. /**#@-*/
  12. /**
  13. * Retrieve the character at first position in the provided string
  14. *
  15. * @param mixed String
  16. * @return string
  17. */
  18. function char($text) {
  19. return ! is_num($text) ? substr((string) $text, 0, 1) : chr((int) $text);
  20. }
  21. /**
  22. * Make a string lowercase and non alphabetic charater to underscore
  23. *
  24. * @param string String
  25. * @param boolean Use ucwords()?
  26. * @param boolean Strict mode?
  27. * @staticvar array Replacements
  28. * @return string
  29. */
  30. function underscore($text, $ucwords = FALSE, $strict = FALSE) {
  31. static $repl = array(
  32. '/(^|\W)([A-Z])/e' => '"\\1_".strtolower("\\2");',
  33. '/[A-Z](?=\w)/' => '_\\0',
  34. );
  35. $text = plain(unents($text));
  36. if (is_true($ucwords)) {
  37. $text = ucwords($text);
  38. }
  39. $text = preg_replace(array_keys($repl), $repl, $text);
  40. $text = trim(strtr($text, ' ', '_'), '_');
  41. $text = strtolower($text);
  42. return $text;
  43. }
  44. /**
  45. * Convert the specified string to camel case format
  46. *
  47. * @param string String
  48. * @param boolean Use ucfirst()?
  49. * @param string Character separator
  50. * @return string
  51. */
  52. function camelcase($text, $ucfirst = FALSE, $glue = '') {
  53. static $repl = array(
  54. '/[^a-z0-9]|\s+/i' => ' ',
  55. '/\s([a-z])/ie' => '$glue.ucfirst("\\1");',
  56. );
  57. $text = preg_replace(array_keys($repl), $repl, underscore($text));
  58. if (is_true($ucfirst)) {
  59. $text = ucfirst($text);
  60. }
  61. return $text;
  62. }
  63. /**
  64. * Unique hash
  65. *
  66. * @param integer String length
  67. * @staticvar string Charset
  68. * @return string
  69. */
  70. function salt($length = 8) {
  71. static $chars = '@ABCD,EFGH.IJKL-MNOP=QRST~UVWX$YZab/cdef*ghij;klmn:opqr_stuv(wxyz)0123!4567|89{}';
  72. $length = (int) $length;
  73. $length > 32 && $length = 32;
  74. $out = '';
  75. do
  76. {
  77. $index = substr($chars, mt_rand(0, 79), 1);
  78. if ( ! strstr($out, $index)) {
  79. $out .= $index;
  80. }
  81. $current = strlen($out);
  82. } while($current !== $length);
  83. return $out;
  84. }
  85. /**
  86. * Slugify string segments
  87. *
  88. * @param string Path|Route
  89. * @param boolean Character separator
  90. * @param mixed SLUG_STRICT|SLUG_LOWER|SLUG_TRIM
  91. * @return string
  92. */
  93. function slug($text, $glue = '-', $options = NULL) {
  94. $strict = ((int) $options & SLUG_STRICT) == 0 ? FALSE : TRUE;
  95. $lower = ((int) $options & SLUG_LOWER) == 0 ? FALSE : TRUE;
  96. $trim = ((int) $options & SLUG_TRIM) == 0 ? FALSE : TRUE;
  97. $expr = $strict ? '\W+' : sprintf('[^%s\/]', substr(match('%l'), 1, -1));
  98. $text = preg_replace("/$expr/", $glue, plain(unents($text)));
  99. $text = $lower ? strtolower($text) : $text;
  100. if ($trim) {
  101. $char = preg_quote($glue, '/');
  102. $text = preg_replace("/$char+/", $glue, $text);
  103. $text = trim($text, $glue);
  104. }
  105. return $text;
  106. }
  107. /**
  108. * Remove punctuation characters
  109. *
  110. * @param string String
  111. * @param boolean Magic regex
  112. * @staticvar array Entities set
  113. * @return string
  114. */
  115. function plain($text, $special = FALSE) {
  116. static $set = NULL,
  117. $rev = NULL;
  118. if (is_null($set)) {
  119. $old = $rev = array();
  120. $html = get_html_translation_table(HTML_ENTITIES);
  121. foreach ($html as $char => $ord) {
  122. if (ord($char) >= 192) {
  123. $char = utf8_encode($char);
  124. $key = substr($ord, 1, 1);
  125. $set[$char] = $key;
  126. if ( ! isset($old[$key])) {
  127. $old[$key] = (array) $key;
  128. }
  129. $old[$key] []= $char;
  130. $old[$key] []= $ord;
  131. }
  132. }
  133. foreach ($old as $key => $val) {
  134. $rev[$key] = '(?:' . join('|', $val) . ')';
  135. }
  136. }
  137. $text = strtr($text, $set);
  138. $text = is_true($special) ? strtr($text, $rev) : $text;
  139. return $text;
  140. }
  141. /**
  142. * Strips out some type of tags
  143. *
  144. * @param string String
  145. * @param boolean Allow comments?
  146. * @return string
  147. */
  148. function strips($text, $comments = FALSE) {
  149. $out = preg_replace('/[<\{\[]\/*[^<\{\[!\]\}>]*[\]\}>]/Us', '', $text);
  150. $out = is_false($comments) ? strip_tags($out) : $out;
  151. return $out;
  152. }
  153. /**
  154. * Entity repair and escaping
  155. *
  156. * @param mixed String|Array
  157. * @param boolean Escape tags?
  158. * @staticvar array Hex replacements
  159. * @return string
  160. */
  161. function ents($text, $escape = FALSE) {
  162. static $expr = array(
  163. '/(&#?[0-9a-z]{2,})([\x00-\x20])*;?/i' => '\\1;\\2',
  164. '/&#x([0-9a-f]+);?/ei' => 'chr(hexdec("\\1"));',
  165. '/(&#x?)([0-9A-F]+);?/i' => '\\1\\2;',
  166. '/&#(\d+);?/e' => 'chr("\\1");',
  167. );
  168. $hash = uniqid('--entity-backup');
  169. $text = preg_replace('/&([a-z0-9;_]+)=([a-z0-9_]+)/i', "{$hash}\\1=\\2", $text);
  170. $text = preg_replace(array_keys($expr), $expr, $text);
  171. $text = preg_replace('/&(#?[a-z0-9]+);/i', "{$hash}\\1;", $text);
  172. $text = str_replace(array('&', '\\', $hash), array('&amp;', '&#92;', '&'), $text);
  173. if (is_true($escape)) {
  174. $text = strtr($text, array(
  175. '<' => '&lt;',
  176. '>' => '&gt;',
  177. '"' => '&quot;',
  178. "'" => '&#39;',
  179. ));
  180. }
  181. $text = preg_replace("/[\200-\237]|\240|[\241-\377]/", '\\0', $text);
  182. $text = preg_replace("/{$hash}(.+?);/", '&\\1;', $text);
  183. return $text;
  184. }
  185. /**
  186. * Revert entities
  187. *
  188. * @param string String
  189. * @staticvar array Entities set
  190. * @staticvar array Replacements
  191. * @return string
  192. */
  193. function unents($text) {
  194. static $set = NULL,
  195. $expr = array(
  196. '/&amp;([a-z]+|(#\d+)|(#x[\da-f]+));/i' => '&\\1;',
  197. '/&#x([0-9a-f]+);/ei' => 'chr(hexdec("\\1"));',
  198. '/&#([0-9]+);/e' => 'chr("\\1");',
  199. );
  200. if (is_null($set)) {
  201. $set = get_html_translation_table(HTML_ENTITIES);
  202. $set = array_flip($set);
  203. $set['&apos;'] = "'";
  204. }
  205. $text = preg_replace(array_keys($expr), $expr, $text);
  206. $text = strtr($text, $set);
  207. return html_entity_decode($text);
  208. }
  209. /**
  210. * HTML generic tag
  211. *
  212. * @param string Tag name
  213. * @param mixed Attributes
  214. * @param mixed Inner text value|Function callback
  215. * @return string
  216. */
  217. function tag($name, $args = array(), $text = '') {
  218. static $set = NULL;
  219. if (is_null($set)) {
  220. $test = include LIB.DS.'assets'.DS.'scripts'.DS.'html_vars'.EXT;
  221. $set = $test['empty'];
  222. }
  223. $attrs = attrs($args);
  224. if (in_array($name, $set)) {
  225. return "<$name$attrs>";
  226. }
  227. if (is_closure($text)) {
  228. ob_start() && $text();
  229. $text = ob_get_clean();
  230. }
  231. return "<$name$attrs>$text</$name>";
  232. }
  233. /**
  234. * Make a string of HTML attributes
  235. *
  236. * @param mixed Array|Object|Expression
  237. * @param boolean Strictly HTML attributes?
  238. * @staticvar array Global attributes set
  239. * @staticvar string Selector regex
  240. * @return string
  241. */
  242. function attrs($args, $html = FALSE) {
  243. static $global = NULL,
  244. $regex = '/(?:#([a-z_][\da-z_-]*))?(?:[.,]?([\s\d.,a-z_-]+))?(?:@([^"]+))?/i';
  245. if (is_null($global)) {
  246. $test = include LIB.DS.'assets'.DS.'scripts'.DS.'html_vars'.EXT;
  247. $global = array_merge($test['global'], $test['events']);
  248. unset($global['data-*']);
  249. unset($global['aria-*']);
  250. }
  251. if (is_string($args)) {
  252. preg_match_all($regex, $args, $match);
  253. $args = array();
  254. if ( ! empty($match[1][0])) {
  255. $args['id'] = $match[1][0];
  256. }
  257. if ( ! empty($match[2][0])) {
  258. $args['class'] = strtr($match[2][0], ',.', ' ');
  259. }
  260. if ( ! empty($match[3][0])) {
  261. foreach (explode('@', $match[3][0]) as $one) {
  262. $test = explode('=', $one);
  263. $key = ! empty($test[0]) ? $test[0] : $one;
  264. $val = ! empty($test[1]) ? $test[1] : $key;
  265. $args[$key] = $val;
  266. }
  267. }
  268. }
  269. $out = array('');
  270. foreach ((array) $args as $key => $value) {
  271. $key = preg_replace('/\W/', '-', trim($key));
  272. if (is_true($html) && ! in_array($key, $global)) {
  273. continue;
  274. }
  275. if (is_bool($value)) {
  276. if (is_true($value)) {
  277. $out []= $key;
  278. }
  279. } elseif (is_iterable($value)) {
  280. if ($key === 'style') {//FIX
  281. $props = array();
  282. foreach ($value as $key => $val) {//TODO: deep chained props?
  283. $props []= $key . ':' . trim($val);
  284. }
  285. $out []= sprintf('style="%s"', join(';', $props));
  286. } else {
  287. foreach ((array) $value as $index => $test) {
  288. $out []= sprintf('%s-%s="%s"', $key, $index, trim($test));
  289. }
  290. }
  291. } elseif ( ! is_num($key) && is_scalar($value)) {
  292. $out []= sprintf('%s="%s"', $key, ents($value, TRUE));
  293. }
  294. }
  295. $out = join(' ', $out);
  296. return $out;
  297. }
  298. /**
  299. * Retrieve params from attributes string
  300. *
  301. * @param string String
  302. * @staticvar string Match regex
  303. * @return array
  304. */
  305. function args($text, $prefix = '') {
  306. static $regex = '/(?:^|\s+)(?:([\w:-]+)\s*=\s*([\'"`]?)(.+?)\\2|[\w:-]+)(?=\s+|$)/';
  307. $out = array();
  308. preg_match_all($regex, $text, $match);
  309. foreach ($match[1] as $i => $key) {
  310. if (empty($key)) {
  311. $out []= trim($match[0][$i]);
  312. continue;
  313. }
  314. $val = ents($match[3][$i], TRUE);
  315. $key = strtolower($key);
  316. $out[$key] = $val;
  317. }
  318. return $out;
  319. }
  320. /* EOF: ./framework/core/utilities.php */