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