Bytes.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Provides helper methods for byte conversions.
  5. */
  6. class Bytes {
  7. /**
  8. * The number of bytes in a kilobyte.
  9. *
  10. * @see http://wikipedia.org/wiki/Kilobyte
  11. */
  12. const KILOBYTE = 1024;
  13. /**
  14. * Parses a given byte size.
  15. *
  16. * @param mixed $size
  17. * An integer or string size expressed as a number of bytes with optional SI
  18. * or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
  19. *
  20. * @return int
  21. * An integer representation of the size in bytes.
  22. */
  23. public static function toInt($size) {
  24. // Remove the non-unit characters from the size.
  25. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
  26. // Remove the non-numeric characters from the size.
  27. $size = preg_replace('/[^0-9\.]/', '', $size);
  28. if ($unit) {
  29. // Find the position of the unit in the ordered string which is the power
  30. // of magnitude to multiply a kilobyte by.
  31. return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
  32. }
  33. else {
  34. // Ensure size is a proper number type.
  35. return round((float) $size);
  36. }
  37. }
  38. }