Skip to content

Instantly share code, notes, and snippets.

@gowon
Created May 24, 2014 04:23
Show Gist options
  • Save gowon/2a04f4ccca42fb45801e to your computer and use it in GitHub Desktop.
Save gowon/2a04f4ccca42fb45801e to your computer and use it in GitHub Desktop.
Simple Byte-size handling class
<?php
class Bytes
{
private $sizeInBytes;
private static $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
public function __construct($sizeInBytes)
{
$this->sizeInBytes = floatval($sizeInBytes);
}
public function __toString ()
{
return $this->ToString();
}
public function ToString($unit = null, $decimalPrecision = 2)
{
$orderOfMagnitude = 0;
$newSize = $this->sizeInBytes;
if ($unit === null) {
for ($i = 0, $size = $this->sizeInBytes; $size > 1024 && isset(self::$units[$i + 1]); $i++) {
$size /= 1024;
}
$orderOfMagnitude = $i;
$newSize = $size;
}
elseif (!in_array($unit, self::$units)) {
$pow = floor(log($this->sizeInBytes) / log(1024));
$orderOfMagnitude = array_search($pow, self::$units);
$newSize /= pow(1024, $orderOfMagnitude);
}
return sprintf('%.' . $decimalPrecision . 'f ' . self::$units[$orderOfMagnitude], $newSize);
}
public function Convert($unit)
{
switch ($unit) {
case "k":
case "K":
case "Ki":
$pow = 1;
break;
case "M":
case "Mi":
$pow = 2;
break;
case "G":
case "Gi":
$pow = 3;
break;
case "T":
case "Ti":
$pow = 4;
break;
case "P":
case "Pi":
$pow = 5;
break;
case "E":
case "Ei":
$pow = 6;
break;
case "Z":
case "Zi":
$pow = 7;
break;
case "Y":
case "Yi":
$pow = 8;
break;
default:
$pow = 0;
}
return $this->sizeInBytes / pow(1024, $pow);
}
public static function Size($size)
{
return new Bytes($size);
}
public static function FromFile($filename)
{
if (file_exists($filename)) {
return new Bytes(filesize($filename));
}
throw new Exception("File '" . $filename . "' not found.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment