69 lines
1.5 KiB
PHP
69 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\Juicer\Helper;
|
|
|
|
/**
|
|
* Normalize percentages to a full 100%.
|
|
*
|
|
*/
|
|
class Normalizer
|
|
{
|
|
|
|
protected $inputs = [];
|
|
|
|
protected $ratio = 0;
|
|
|
|
/**
|
|
* Normalizer constructor.
|
|
*
|
|
* @param array The percentages indexed by a unique key
|
|
*/
|
|
public function __construct(array $inputPercents=[])
|
|
{
|
|
foreach ($inputPercents as $k=>$p)
|
|
$this->setPart($k, $p);
|
|
}
|
|
|
|
/**
|
|
* Set the percentage of a component.
|
|
*
|
|
* @param mixed The key used to access this part later
|
|
* @param float The percent of this part
|
|
*/
|
|
public function setPart($key, float $percent)
|
|
{
|
|
$this->inputs[$key] = $percent;
|
|
$total = array_sum(array_values($this->inputs));
|
|
$this->ratio = 100 / $total;
|
|
}
|
|
|
|
/**
|
|
* Get the original percentage of the key.
|
|
*
|
|
* @param mixed The key
|
|
* @return float Original percentage as provided
|
|
*/
|
|
public function getPercent($key)
|
|
{
|
|
if (!array_key_exists($key, $this->inputs))
|
|
throw new \Exception();
|
|
|
|
return floatval($this->inputs[$key]);
|
|
}
|
|
|
|
/**
|
|
* Get the normalized percentage where the added total equals 100%
|
|
*
|
|
* @param mixed The key
|
|
* @return float Normalized percentage as provided
|
|
*/
|
|
public function getNormalizedPercent($key)
|
|
{
|
|
if (!array_key_exists($key, $this->inputs))
|
|
throw new \Exception();
|
|
|
|
return floatval($this->inputs[$key]) * $this->ratio;
|
|
}
|
|
|
|
}
|