PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/lithium/util/String.php

https://github.com/joshbhamilton/todophp
PHP | 440 lines | 239 code | 43 blank | 158 comment | 50 complexity | 306f127b7c01b1e5d3957ac7ca2dd356 MD5 | raw file
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2011, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/mit-license.php The MIT License
  7. */
  8. namespace lithium\util;
  9. use COM;
  10. use Closure;
  11. use Exception;
  12. /**
  13. * String manipulation utility class. Includes functionality for generating UUIDs,
  14. * {:tag} and regex replacement, and tokenization. Also includes a cryptographically-strong random
  15. * number generator, and a base64 encoder for use with DES and XDES.
  16. */
  17. class String {
  18. /**
  19. * UUID-related constant. Clears all bits of version byte (`00001111`).
  20. */
  21. const UUID_CLEAR_VER = 15;
  22. /**
  23. * UUID constant that sets the version bit for generated UUIDs (`01000000`).
  24. */
  25. const UUID_VERSION_4 = 64;
  26. /**
  27. * Clears relevant bits of variant byte (`00111111`).
  28. */
  29. const UUID_CLEAR_VAR = 63;
  30. /**
  31. * The RFC 4122 variant (`10000000`).
  32. */
  33. const UUID_VAR_RFC = 128;
  34. /**
  35. * Option flag used in `String::random()`.
  36. */
  37. const ENCODE_BASE_64 = 1;
  38. /**
  39. * A closure which, given a number of bytes, returns that amount of
  40. * random bytes.
  41. *
  42. * @var Closure
  43. */
  44. protected static $_source;
  45. /**
  46. * Generates an RFC 4122-compliant version 4 UUID.
  47. *
  48. * @return string The string representation of an RFC 4122-compliant, version 4 UUID.
  49. * @link http://www.ietf.org/rfc/rfc4122.txt RFC 4122: UUID URN Namespace
  50. */
  51. public static function uuid() {
  52. $uuid = static::random(16);
  53. $uuid[6] = chr(ord($uuid[6]) & static::UUID_CLEAR_VER | static::UUID_VERSION_4);
  54. $uuid[8] = chr(ord($uuid[8]) & static::UUID_CLEAR_VAR | static::UUID_VAR_RFC);
  55. return join('-', array(
  56. bin2hex(substr($uuid, 0, 4)),
  57. bin2hex(substr($uuid, 4, 2)),
  58. bin2hex(substr($uuid, 6, 2)),
  59. bin2hex(substr($uuid, 8, 2)),
  60. bin2hex(substr($uuid, 10, 6))
  61. ));
  62. }
  63. /**
  64. * Generates random bytes for use in UUIDs and password salts, using
  65. * (when available) a cryptographically strong random number generator.
  66. *
  67. * {{{
  68. * $bits = String::random(8); // 64 bits
  69. * $hex = bin2hex($bits); // [0-9a-f]+
  70. * }}}
  71. *
  72. * Optionally base64-encodes the resulting random string per the following:
  73. *
  74. * _The alphabet used by `base64_encode()` is different than the one we should be using. When
  75. * considering the meaty part of the resulting string, however, a bijection allows to go the
  76. * from one to another. Given that we're working on random bytes, we can use safely use
  77. * `base64_encode()` without losing any entropy._
  78. *
  79. * @param integer $bytes The number of random bytes to generate.
  80. * @param array $options The options used when generating random bytes:
  81. * - `'encode'` _integer_: If specified, and set to `String::ENCODE_BASE_64`, the
  82. * resulting value will be base64-encoded, per the notes above.
  83. * @return string Returns a string of random bytes.
  84. */
  85. public static function random($bytes, array $options = array()) {
  86. $defaults = array('encode' => null);
  87. $options += $defaults;
  88. $source = static::$_source ?: static::_source();
  89. $result = $source($bytes);
  90. if ($options['encode'] != static::ENCODE_BASE_64) {
  91. return $result;
  92. }
  93. return strtr(rtrim(base64_encode($result), '='), '+', '.');
  94. }
  95. /**
  96. * Initializes `String::$_source` using the best available random number generator.
  97. *
  98. * When available, `/dev/urandom` and COM gets used on *nix and
  99. * [Windows systems](http://msdn.microsoft.com/en-us/library/aa388182%28VS.85%29.aspx?ppud=4),
  100. * respectively.
  101. *
  102. * If all else fails, a Mersenne Twister gets used. (Strictly
  103. * speaking, this fallback is inadequate, but good enough.)
  104. *
  105. * @see lithium\util\String::$_source
  106. * @return closure Returns a closure containing a random number generator.
  107. */
  108. protected static function _source() {
  109. switch (true) {
  110. case isset(static::$_source):
  111. return static::$_source;
  112. case is_readable('/dev/urandom') && $fp = fopen('/dev/urandom', 'rb'):
  113. return static::$_source = function($bytes) use (&$fp) {
  114. return fread($fp, $bytes);
  115. };
  116. case class_exists('COM', false):
  117. try {
  118. $com = new COM('CAPICOM.Utilities.1');
  119. return static::$_source = function($bytes) use ($com) {
  120. return base64_decode($com->GetRandom($bytes, 0));
  121. };
  122. } catch (Exception $e) {
  123. }
  124. default:
  125. return static::$_source = function($bytes) {
  126. $rand = '';
  127. for ($i = 0; $i < $bytes; $i++) {
  128. $rand .= chr(mt_rand(0, 255));
  129. }
  130. return $rand;
  131. };
  132. }
  133. }
  134. /**
  135. * Uses PHP's hashing functions to create a hash of the string provided, using the options
  136. * specified. The default hash algorithm is SHA-512.
  137. *
  138. * @link http://php.net/manual/en/function.hash.php PHP Manual: `hash()`
  139. * @link http://php.net/manual/en/function.hash-hmac.php PHP Manual: `hash_hmac()`
  140. * @link http://php.net/manual/en/function.hash-algos.php PHP Manual: `hash_algos()`
  141. * @param string $string The string to hash.
  142. * @param array $options Supported options:
  143. * - `'type'` _string_: Any valid hashing algorithm. See the `hash_algos()` function to
  144. * determine which are available on your system.
  145. * - `'salt'` _string_: A _salt_ value which, if specified, will be prepended to the
  146. * string.
  147. * - `'key'` _string_: If specified `hash_hmac()` will be used to hash the string,
  148. * instead of `hash()`, with `'key'` being used as the message key.
  149. * - `'raw'` _boolean_: If `true`, outputs the raw binary result of the hash operation.
  150. * Defaults to `false`.
  151. * @return string Returns a hashed string.
  152. */
  153. public static function hash($string, array $options = array()) {
  154. $defaults = array(
  155. 'type' => 'sha512',
  156. 'salt' => false,
  157. 'key' => false,
  158. 'raw' => false
  159. );
  160. $options += $defaults;
  161. if ($options['salt']) {
  162. $string = $options['salt'] . $string;
  163. }
  164. if ($options['key']) {
  165. return hash_hmac($options['type'], $string, $options['key'], $options['raw']);
  166. }
  167. return hash($options['type'], $string, $options['raw']);
  168. }
  169. /**
  170. * Replaces variable placeholders inside a string with any given data. Each key
  171. * in the `$data` array corresponds to a variable placeholder name in `$str`.
  172. *
  173. * Usage:
  174. * {{{
  175. * String::insert(
  176. * 'My name is {:name} and I am {:age} years old.',
  177. * array('name' => 'Bob', 'age' => '65')
  178. * ); // returns 'My name is Bob and I am 65 years old.'
  179. * }}}
  180. *
  181. * @param string $str A string containing variable place-holders.
  182. * @param array $data A key, value array where each key stands for a place-holder variable
  183. * name to be replaced with value.
  184. * @param array $options Available options are:
  185. * - `'after'`: The character or string after the name of the variable place-holder
  186. * (defaults to `null`).
  187. * - `'before'`: The character or string in front of the name of the variable
  188. * place-holder (defaults to `':'`).
  189. * - `'clean'`: A boolean or array with instructions for `String::clean()`.
  190. * - `'escape'`: The character or string used to escape the before character or string
  191. * (defaults to `'\'`).
  192. * - `'format'`: A regular expression to use for matching variable place-holders
  193. * (defaults to `'/(?<!\\)\:%s/'`. Please note that this option takes precedence over
  194. * all other options except `'clean'`.
  195. * @return string
  196. * @todo Optimize this
  197. */
  198. public static function insert($str, array $data, array $options = array()) {
  199. $defaults = array(
  200. 'before' => '{:',
  201. 'after' => '}',
  202. 'escape' => null,
  203. 'format' => null,
  204. 'clean' => false
  205. );
  206. $options += $defaults;
  207. $format = $options['format'];
  208. reset($data);
  209. if ($format == 'regex' || (!$format && $options['escape'])) {
  210. $format = sprintf(
  211. '/(?<!%s)%s%%s%s/',
  212. preg_quote($options['escape'], '/'),
  213. str_replace('%', '%%', preg_quote($options['before'], '/')),
  214. str_replace('%', '%%', preg_quote($options['after'], '/'))
  215. );
  216. }
  217. if (!$format && key($data) !== 0) {
  218. $replace = array();
  219. foreach ($data as $key => $value) {
  220. $replace["{$options['before']}{$key}{$options['after']}"] = $value;
  221. }
  222. $str = strtr($str, $replace);
  223. return $options['clean'] ? static::clean($str, $options) : $str;
  224. }
  225. if (strpos($str, '?') !== false && isset($data[0])) {
  226. $offset = 0;
  227. while (($pos = strpos($str, '?', $offset)) !== false) {
  228. $val = array_shift($data);
  229. $offset = $pos + strlen($val);
  230. $str = substr_replace($str, $val, $pos, 1);
  231. }
  232. return $options['clean'] ? static::clean($str, $options) : $str;
  233. }
  234. foreach ($data as $key => $value) {
  235. $hashVal = crc32($key);
  236. $key = sprintf($format, preg_quote($key, '/'));
  237. if (!$key) {
  238. continue;
  239. }
  240. $str = preg_replace($key, $hashVal, $str);
  241. if (is_object($value) && !$value instanceof Closure) {
  242. try {
  243. $value = $value->__toString();
  244. } catch (Exception $e) {
  245. $value = '';
  246. }
  247. }
  248. if (!is_array($value)) {
  249. $str = str_replace($hashVal, $value, $str);
  250. }
  251. }
  252. if (!isset($options['format']) && isset($options['before'])) {
  253. $str = str_replace($options['escape'] . $options['before'], $options['before'], $str);
  254. }
  255. return $options['clean'] ? static::clean($str, $options) : $str;
  256. }
  257. /**
  258. * Cleans up a `Set::insert()` formatted string with given `$options` depending
  259. * on the `'clean'` option. The goal of this function is to replace all whitespace
  260. * and unneeded mark-up around place-holders that did not get replaced by `Set::insert()`.
  261. *
  262. * @param string $str The string to clean.
  263. * @param array $options Available options are:
  264. * - `'after'`: characters marking the end of targeted substring.
  265. * - `'andText'`: (defaults to `true`).
  266. * - `'before'`: characters marking the start of targeted substring.
  267. * - `'clean'`: `true` or an array of clean options:
  268. * - `'gap'`: Regular expression matching gaps.
  269. * - `'method'`: Either `'text'` or `'html'` (defaults to `'text'`).
  270. * - `'replacement'`: String to use for cleaned substrings (defaults to `''`).
  271. * - `'word'`: Regular expression matching words.
  272. * @return string The cleaned string.
  273. */
  274. public static function clean($str, array $options = array()) {
  275. if (!$options['clean']) {
  276. return $str;
  277. }
  278. $clean = $options['clean'];
  279. $clean = ($clean === true) ? array('method' => 'text') : $clean;
  280. $clean = (!is_array($clean)) ? array('method' => $options['clean']) : $clean;
  281. switch ($clean['method']) {
  282. case 'html':
  283. $clean += array('word' => '[\w,.]+', 'andText' => true, 'replacement' => '');
  284. $kleenex = sprintf(
  285. '/[\s]*[a-z]+=(")(%s%s%s[\s]*)+\\1/i',
  286. preg_quote($options['before'], '/'),
  287. $clean['word'],
  288. preg_quote($options['after'], '/')
  289. );
  290. $str = preg_replace($kleenex, $clean['replacement'], $str);
  291. if ($clean['andText']) {
  292. $options['clean'] = array('method' => 'text');
  293. $str = static::clean($str, $options);
  294. }
  295. break;
  296. case 'text':
  297. $clean += array(
  298. 'word' => '[\w,.]+', 'gap' => '[\s]*(?:(?:and|or|,)[\s]*)?', 'replacement' => ''
  299. );
  300. $before = preg_quote($options['before'], '/');
  301. $after = preg_quote($options['after'], '/');
  302. $kleenex = sprintf(
  303. '/(%s%s%s%s|%s%s%s%s|%s%s%s%s%s)/',
  304. $before, $clean['word'], $after, $clean['gap'],
  305. $clean['gap'], $before, $clean['word'], $after,
  306. $clean['gap'], $before, $clean['word'], $after, $clean['gap']
  307. );
  308. $str = preg_replace($kleenex, $clean['replacement'], $str);
  309. break;
  310. }
  311. return $str;
  312. }
  313. /**
  314. * Extract a part of a string based on a regular expression `$regex`.
  315. *
  316. * @param string $regex The regular expression to use.
  317. * @param string $str The string to run the extraction on.
  318. * @param integer $index The number of the part to return based on the regex.
  319. * @return mixed
  320. */
  321. public static function extract($regex, $str, $index = 0) {
  322. if (!preg_match($regex, $str, $match)) {
  323. return false;
  324. }
  325. return isset($match[$index]) ? $match[$index] : null;
  326. }
  327. /**
  328. * Tokenizes a string using `$options['separator']`, ignoring any instances of
  329. * `$options['separator']` that appear between `$options['leftBound']` and
  330. * `$options['rightBound']`.
  331. *
  332. * @param string $data The data to tokenize.
  333. * @param array $options Options to use when tokenizing:
  334. * -`'separator'` _string_: The token to split the data on.
  335. * -`'leftBound'` _string_: Left scope-enclosing boundary.
  336. * -`'rightBound'` _string_: Right scope-enclosing boundary.
  337. * @return array Returns an array of tokens.
  338. */
  339. public static function tokenize($data, array $options = array()) {
  340. $defaults = array('separator' => ',', 'leftBound' => '(', 'rightBound' => ')');
  341. extract($options + $defaults);
  342. if (!$data || is_array($data)) {
  343. return $data;
  344. }
  345. $depth = 0;
  346. $offset = 0;
  347. $buffer = '';
  348. $results = array();
  349. $length = strlen($data);
  350. $open = false;
  351. while ($offset <= $length) {
  352. $tmpOffset = -1;
  353. $offsets = array(
  354. strpos($data, $separator, $offset),
  355. strpos($data, $leftBound, $offset),
  356. strpos($data, $rightBound, $offset)
  357. );
  358. for ($i = 0; $i < 3; $i++) {
  359. if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset == -1)) {
  360. $tmpOffset = $offsets[$i];
  361. }
  362. }
  363. if ($tmpOffset === -1) {
  364. $results[] = $buffer . substr($data, $offset);
  365. $offset = $length + 1;
  366. continue;
  367. }
  368. $buffer .= substr($data, $offset, ($tmpOffset - $offset));
  369. if ($data{$tmpOffset} == $separator && $depth == 0) {
  370. $results[] = $buffer;
  371. $buffer = '';
  372. } else {
  373. $buffer .= $data{$tmpOffset};
  374. }
  375. if ($leftBound != $rightBound) {
  376. if ($data{$tmpOffset} == $leftBound) {
  377. $depth++;
  378. }
  379. if ($data{$tmpOffset} == $rightBound) {
  380. $depth--;
  381. }
  382. $offset = ++$tmpOffset;
  383. continue;
  384. }
  385. if ($data{$tmpOffset} == $leftBound) {
  386. ($open) ? $depth-- : $depth++;
  387. $open = !$open;
  388. }
  389. $offset = ++$tmpOffset;
  390. }
  391. if (!$results && $buffer) {
  392. $results[] = $buffer;
  393. }
  394. return $results ? array_map('trim', $results) : array();
  395. }
  396. }
  397. ?>