Filter.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin;
  12. use Exception;
  13. /**
  14. * Filter
  15. *
  16. * Provides data filtering functions.
  17. */
  18. class Filter
  19. {
  20. /**
  21. * format a given time string into a human readable label (localized)
  22. *
  23. * accepts times in the format "[integer][time unit]"
  24. *
  25. * @access public
  26. * @static
  27. * @param string $time
  28. * @throws Exception
  29. * @return string
  30. */
  31. public static function formatHumanReadableTime($time)
  32. {
  33. if (preg_match('/^(\d+) *(\w+)$/', $time, $matches) !== 1) {
  34. throw new Exception("Error parsing time format '$time'", 30);
  35. }
  36. switch ($matches[2]) {
  37. case 'sec':
  38. $unit = 'second';
  39. break;
  40. case 'min':
  41. $unit = 'minute';
  42. break;
  43. default:
  44. $unit = rtrim($matches[2], 's');
  45. }
  46. return I18n::_(['%d ' . $unit, '%d ' . $unit . 's'], (int) $matches[1]);
  47. }
  48. /**
  49. * format a given number of bytes in IEC 80000-13:2008 notation (localized)
  50. *
  51. * @access public
  52. * @static
  53. * @param int $size
  54. * @return string
  55. */
  56. public static function formatHumanReadableSize($size)
  57. {
  58. $iec = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  59. $i = 0;
  60. while (($size / 1000) >= 1) {
  61. $size = $size / 1000;
  62. ++$i;
  63. }
  64. return number_format($size, $i ? 2 : 0, '.', ' ') . ' ' . I18n::_($iec[$i]);
  65. }
  66. }