Created
March 13, 2018 15:29
-
-
Save brcontainer/32a4c338bc1cf11b7877f6d64448610e to your computer and use it in GitHub Desktop.
Converte tamanho em Kb, Mb, Gb, Tb, etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ByteSize | |
{ | |
const KB = 1; | |
const MB = 2; | |
const GB = 3; | |
const TB = 4; | |
const PB = 5; | |
const EB = 6; | |
const ZB = 7; | |
const YB = 8; | |
private $acronyms = array( | |
'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb' | |
); | |
private $precision = 2; | |
/** | |
* Set size | |
* | |
* @param int $size | |
* @return void | |
*/ | |
public function setSize($size) | |
{ | |
$this->size = $size; | |
} | |
/** | |
* Set precision | |
* | |
* @param int $precision | |
* @return void | |
*/ | |
public function setPrecision($precision) | |
{ | |
$this->precision = $precision; | |
} | |
/** | |
* Change size acronyms | |
* | |
* @param int $type | |
* @param string $acronym | |
* @throws \Inphinit\Experimental\Exception | |
* @return void | |
*/ | |
public function setUnit($type, $acronym) | |
{ | |
if (array_key_exists($type - 1, $this->acronyms) === false) { | |
throw new Exception('Invalid format', 2); | |
} | |
$this->acronyms[$type - 1] = $acronym; | |
} | |
/** | |
* Return size by defined format | |
* | |
* @param int $type | |
* @throws \Inphinit\Experimental\Exception | |
* @return string | |
*/ | |
public function format($type) | |
{ | |
if (array_key_exists($type - 1, $this->acronyms) === false) { | |
throw new Exception('Invalid format', 2); | |
} | |
if ($this->size > 0) { | |
$size = $this->size / pow(1024, $type); | |
} else { | |
$size = 0; | |
} | |
return sprintf('%.' . $this->precision . 'f', $size) . $this->acronyms[$type - 1]; | |
} | |
/** | |
* Return size and detect format | |
* | |
* @return string | |
*/ | |
public function auto() | |
{ | |
$type = intval(log($this->size) / log(1024)); | |
if ($type < 1) { | |
$type = 1; | |
} | |
return $this->format($type); | |
} | |
} | |
$x = new ByteSize; | |
$x->setSize(1024 * 1024*1024); | |
$x->setPrecision(2); | |
echo $x->auto(), PHP_EOL, | |
$x->format(ByteSize::KB), PHP_EOL, | |
$x->format(ByteSize::MB), PHP_EOL, | |
$x->format(ByteSize::GB), PHP_EOL, | |
$x->format(ByteSize::TB), PHP_EOL, | |
$x->format(ByteSize::PB), PHP_EOL, | |
$x->format(ByteSize::EB), PHP_EOL, | |
$x->format(ByteSize::ZB), PHP_EOL, | |
$x->format(ByteSize::YB), PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment