PageRenderTime 68ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/src/classes/XLite/Core/Converter.php

https://github.com/chaikk/core
PHP | 485 lines | 262 code | 35 blank | 188 comment | 18 complexity | 2f44406377b2003071f0ce0b2daf0501 MD5 | raw file
  1. <?php
  2. // vim: set ts=4 sw=4 sts=4 et:
  3. /**
  4. * LiteCommerce
  5. *
  6. * NOTICE OF LICENSE
  7. *
  8. * This source file is subject to the Open Software License (OSL 3.0)
  9. * that is bundled with this package in the file LICENSE.txt.
  10. * It is also available through the world-wide-web at this URL:
  11. * http://opensource.org/licenses/osl-3.0.php
  12. * If you did not receive a copy of the license and are unable to
  13. * obtain it through the world-wide-web, please send an email
  14. * to licensing@litecommerce.com so we can send you a copy immediately.
  15. *
  16. * PHP version 5.3.0
  17. *
  18. * @category LiteCommerce
  19. * @author Creative Development LLC <info@cdev.ru>
  20. * @copyright Copyright (c) 2011 Creative Development LLC <info@cdev.ru>. All rights reserved
  21. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  22. * @link http://www.litecommerce.com/
  23. * @see ____file_see____
  24. * @since 1.0.0
  25. */
  26. namespace XLite\Core;
  27. /**
  28. * Miscelaneous convertion routines
  29. *
  30. * @see ____class_see____
  31. * @since 1.0.0
  32. */
  33. class Converter extends \XLite\Base\Singleton
  34. {
  35. /**
  36. * Method name translation records
  37. *
  38. * @var array
  39. * @see ____var_see____
  40. * @since 1.0.0
  41. */
  42. protected static $to = array(
  43. 'Q', 'W', 'E', 'R', 'T',
  44. 'Y', 'U', 'I', 'O', 'P',
  45. 'A', 'S', 'D', 'F', 'G',
  46. 'H', 'J', 'K', 'L', 'Z',
  47. 'X', 'C', 'V', 'B', 'N',
  48. 'M',
  49. );
  50. /**
  51. * Method name translation patterns
  52. *
  53. * @var array
  54. * @see ____var_see____
  55. * @since 1.0.0
  56. */
  57. protected static $from = array(
  58. '_q', '_w', '_e', '_r', '_t',
  59. '_y', '_u', '_i', '_o', '_p',
  60. '_a', '_s', '_d', '_f', '_g',
  61. '_h', '_j', '_k', '_l', '_z',
  62. '_x', '_c', '_v', '_b', '_n',
  63. '_m',
  64. );
  65. /**
  66. * Flag to avoid multiple setlocale() calls
  67. *
  68. * @var boolean
  69. * @see ____var_see____
  70. * @since 1.0.0
  71. */
  72. protected static $isLocaleSet = false;
  73. /**
  74. * Convert a string like "test_foo_bar" into the camel case (like "TestFooBar")
  75. *
  76. * @param string $string String to convert
  77. *
  78. * @return string
  79. * @see ____func_see____
  80. * @since 1.0.0
  81. */
  82. public static function convertToCamelCase($string)
  83. {
  84. return ucfirst(str_replace(self::$from, self::$to, strval($string)));
  85. }
  86. /**
  87. * Convert a string like "testFooBar" into the underline style (like "test_foo_bar")
  88. *
  89. * @param string $string String to convert
  90. *
  91. * @return string
  92. * @see ____func_see____
  93. * @since 1.0.0
  94. */
  95. public static function convertFromCamelCase($string)
  96. {
  97. return str_replace(self::$to, self::$from, lcfirst(strval($string)));
  98. }
  99. /**
  100. * Prepare method name
  101. *
  102. * @param string $string Underline-style string
  103. *
  104. * @return string
  105. * @see ____func_see____
  106. * @since 1.0.0
  107. */
  108. public static function prepareMethodName($string)
  109. {
  110. return str_replace(self::$from, self::$to, strval($string));
  111. }
  112. /**
  113. * Compose controller class name using target
  114. *
  115. * @param string $target Current target
  116. *
  117. * @return string
  118. * @see ____func_see____
  119. * @since 1.0.0
  120. */
  121. public static function getControllerClass($target)
  122. {
  123. if (\XLite\Core\Request::getInstance()->isCLI()) {
  124. $zone = 'Console';
  125. } elseif (\XLite::isAdminZone()) {
  126. $zone = 'Admin';
  127. } else {
  128. $zone = 'Customer';
  129. }
  130. return '\XLite\Controller\\'
  131. . $zone
  132. . (empty($target) ? '' : '\\' . self::convertToCamelCase($target));
  133. }
  134. /**
  135. * Compose URL from target, action and additional params
  136. *
  137. * @param string $target Page identifier OPTIONAL
  138. * @param string $action Action to perform OPTIONAL
  139. * @param array $params Additional params OPTIONAL
  140. * @param string $interface Interface script OPTIONAL
  141. *
  142. * @return string
  143. * @see ____func_see____
  144. * @since 1.0.0
  145. */
  146. public static function buildURL($target = '', $action = '', array $params = array(), $interface = null)
  147. {
  148. $url = isset($interface) ? $interface : \XLite::getInstance()->getScript();
  149. $urlParams = array();
  150. if ($target) {
  151. $urlParams['target'] = $target;
  152. }
  153. if ($action) {
  154. $urlParams['action'] = $action;
  155. }
  156. $params = $urlParams + $params;
  157. if (!empty($params)) {
  158. uksort($params, array(get_called_class(), 'sortURLParams'));
  159. $url .= '?' . http_build_query($params);
  160. }
  161. return $url;
  162. }
  163. /**
  164. * Compose full URL from target, action and additional params
  165. *
  166. * @param string $target Page identifier OPTIONAL
  167. * @param string $action Action to perform OPTIONAL
  168. * @param array $params Additional params OPTIONAL
  169. *
  170. * @return string
  171. * @see ____func_see____
  172. * @since 1.0.0
  173. */
  174. public static function buildFullURL($target = '', $action = '', array $params = array())
  175. {
  176. return \XLite::getInstance()->getShopURL(static::buildURL($target, $action, $params));
  177. }
  178. /**
  179. * Return array schema
  180. *
  181. * @param array $keys Keys list OPTIONAL
  182. * @param array $values Values list OPTIONAL
  183. *
  184. * @return array
  185. * @see ____func_see____
  186. * @since 1.0.0
  187. */
  188. public static function getArraySchema(array $keys = array(), array $values = array())
  189. {
  190. return array_combine($keys, $values);
  191. }
  192. /**
  193. * Convert to one-dimensional array
  194. *
  195. * @param array $data Array to flat
  196. * @param string $currKey Parameter for recursive calls OPTIONAL
  197. *
  198. * @return array
  199. * @see ____func_see____
  200. * @since 1.0.0
  201. */
  202. public static function convertTreeToFlatArray(array $data, $currKey = '')
  203. {
  204. $result = array();
  205. foreach ($data as $key => $value) {
  206. $key = $currKey . (empty($currKey) ? $key : '[' . $key . ']');
  207. $result += is_array($value) ? self::convertTreeToFlatArray($value, $key) : array($key => $value);
  208. }
  209. return $result;
  210. }
  211. /**
  212. * Generate random token (32 chars)
  213. *
  214. * @return string
  215. * @see ____func_see____
  216. * @since 1.0.0
  217. */
  218. public static function generateRandomToken()
  219. {
  220. return md5(microtime(true) + rand(0, 1000000));
  221. }
  222. /**
  223. * Check - is GDlib enabled or not
  224. *
  225. * @return boolean
  226. * @see ____func_see____
  227. * @since 1.0.0
  228. */
  229. public static function isGDEnabled()
  230. {
  231. return function_exists('imagecreatefromjpeg')
  232. && function_exists('imagecreatetruecolor')
  233. && function_exists('imagealphablending')
  234. && function_exists('imagesavealpha')
  235. && function_exists('imagecopyresampled');
  236. }
  237. /**
  238. * Check if specified string is URL or not
  239. *
  240. * @param string $url URL
  241. *
  242. * @return boolean
  243. * @see ____func_see____
  244. * @since 1.0.0
  245. */
  246. public static function isURL($url)
  247. {
  248. static $pattern = '(?:([a-z][a-z0-9\*\-\.]*):\/\/(?:(?:(?:[\w\.\-\+!$&\'\(\)*\+,;=]|%[0-9a-f]{2})+:)*(?:[\w\.\-\+%!$&\'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:(?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?](?:[\w#!:\.\?\+=&@!$\'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?)';
  249. return is_string($url) && 0 < preg_match('/^' . $pattern . '$/Ss', $url);
  250. }
  251. /**
  252. * Return class name without backslashes
  253. *
  254. * @param \XLite_Base $obj Object to get class name from
  255. *
  256. * @return string
  257. * @see ____func_see____
  258. * @since 1.0.0
  259. */
  260. public static function getPlainClassName(\XLite\Base $obj)
  261. {
  262. return str_replace('\\', '', get_class($obj));
  263. }
  264. /**
  265. * Format currency value
  266. *
  267. * @param mixed $price Currency unformatted value
  268. *
  269. * @return string
  270. * @see ____func_see____
  271. * @since 1.0.0
  272. */
  273. public static function formatCurrency($price)
  274. {
  275. if (isset($price)) {
  276. $config = \XLite\Core\Config::getInstance();
  277. $price = number_format(
  278. doubleval($price),
  279. 2,
  280. $config->General->decimal_delim,
  281. $config->General->thousand_delim
  282. );
  283. }
  284. return $price;
  285. }
  286. /**
  287. * Format price value
  288. *
  289. * @param mixed $price Price
  290. *
  291. * @return string
  292. * @see ____func_see____
  293. * @since 1.0.0
  294. */
  295. public static function formatPrice($price)
  296. {
  297. if (isset($price)) {
  298. $config = \XLite\Core\Config::getInstance();
  299. $price = sprintf(
  300. $config->General->price_format,
  301. number_format(doubleval($price), 2, $config->General->decimal_delim, $config->General->thousand_delim)
  302. );
  303. }
  304. return $price;
  305. }
  306. /**
  307. * Convert value from one to other weight units
  308. *
  309. * @param float $value Weight value
  310. * @param string $srcUnit Source weight unit
  311. * @param string $dstUnit Destination weight unit
  312. *
  313. * @return float
  314. * @see ____func_see____
  315. * @since 1.0.0
  316. */
  317. public static function convertWeightUnits($value, $srcUnit, $dstUnit)
  318. {
  319. $unitsInGrams = array(
  320. 'lbs' => 453.59,
  321. 'oz' => 28.35,
  322. 'kg' => 1000,
  323. 'g' => 1,
  324. );
  325. $multiplier = $unitsInGrams[$srcUnit] / $unitsInGrams[$dstUnit];
  326. return $value * $multiplier;
  327. }
  328. /**
  329. * Format time
  330. *
  331. * @param integer $base UNIX time stamp OPTIONAL
  332. * @param string $format Format string OPTIONAL
  333. *
  334. * @return string
  335. * @see ____func_see____
  336. * @since 1.0.0
  337. */
  338. public static function formatTime($base = null, $format = null)
  339. {
  340. if (!$format) {
  341. $config = \XLite\Core\Config::getInstance();
  342. $format = $config->General->date_format . ', ' . $config->General->time_format;
  343. }
  344. return static::getStrftime($format, $base);
  345. }
  346. /**
  347. * Format date
  348. *
  349. * @param integer $base UNIX time stamp OPTIONAL
  350. * @param string $format Format string OPTIONAL
  351. *
  352. * @return string
  353. * @see ____func_see____
  354. * @since 1.0.0
  355. */
  356. public static function formatDate($base = null, $format = null)
  357. {
  358. if (!$format) {
  359. $format = \XLite\Core\Config::getInstance()->General->date_format;
  360. }
  361. return static::getStrftime($format, $base);
  362. }
  363. /**
  364. * Get strftime() with specified format and timestamp value
  365. *
  366. * @param string $format Format string
  367. * @param integer $base UNIX time stamp OPTIONAL
  368. *
  369. * @return string
  370. * @see ____func_see____
  371. * @since 1.0.0
  372. */
  373. protected static function getStrftime($format, $base = null)
  374. {
  375. static::setLocaleToUTF8();
  376. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
  377. $format = str_replace('%e', '%#d', $format);
  378. }
  379. return isset($base) ? strftime($format, $base) : strftime($format);
  380. }
  381. /**
  382. * Attempt to set locale to UTF-8
  383. *
  384. * @return void
  385. * @see ____func_see____
  386. * @since 1.0.0
  387. */
  388. protected static function setLocaleToUTF8()
  389. {
  390. if (
  391. !self::$isLocaleSet
  392. && preg_match('/(([^_]+)_?([^.]*))\.?(.*)?/', setlocale(LC_TIME, 0), $match)
  393. && !preg_match('/utf\-?8/i', $match[4])
  394. ) {
  395. setlocale(
  396. LC_TIME,
  397. $match[1] . '.UTF8',
  398. $match[1] . '.UTF-8',
  399. 'en_US.UTF8',
  400. 'en_US.UTF-8',
  401. 'en_US',
  402. 'ENG',
  403. 'English',
  404. $match[0]
  405. );
  406. self::$isLocaleSet = true;
  407. }
  408. }
  409. /**
  410. * Sort URL parameters (callback)
  411. *
  412. * @param string $a First parameter
  413. * @param string $b Second parameter
  414. *
  415. * @return integer
  416. * @see ____func_see____
  417. * @since 1.0.0
  418. */
  419. protected static function sortURLParams($a, $b)
  420. {
  421. return ('target' == $b || ('action' == $b && 'target' != $a)) ? 1 : 0;
  422. }
  423. /**
  424. * Prepare human-readable output for file size
  425. *
  426. * @param integer $size Size in bytes
  427. *
  428. * @return string
  429. * @see ____func_see____
  430. * @since 1.0.0
  431. */
  432. public static function formatFileSize($size)
  433. {
  434. list($size, $suffix) = \Includes\Utils\Converter::formatFileSize($size);
  435. return $size . ' ' . ($suffix ? static::t($suffix) : '');
  436. }
  437. }