mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-06-07 18:44:08 +00:00
75 lines
1.7 KiB
PHP
75 lines
1.7 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Chill is a software for social workers
|
|
*
|
|
* For the full copyright and license information, please view
|
|
* the LICENSE file that was distributed with this source code.
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Chill\BudgetBundle\Calculator;
|
|
|
|
use Chill\BudgetBundle\Entity\AbstractElement;
|
|
use OutOfBoundsException;
|
|
|
|
use function array_key_exists;
|
|
use function array_keys;
|
|
use function implode;
|
|
|
|
class CalculatorManager
|
|
{
|
|
/**
|
|
* @var CalculatorInterface[]
|
|
*/
|
|
protected $calculators = [];
|
|
|
|
protected $defaultCalculator = [];
|
|
|
|
public function addCalculator(CalculatorInterface $calculator, bool $default)
|
|
{
|
|
$this->calculators[$calculator::getAlias()] = $calculator;
|
|
|
|
if ($default) {
|
|
$this->defaultCalculator[] = $calculator::getAlias();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param AbstractElement[] $elements
|
|
*
|
|
* @return CalculatorResult[]
|
|
*/
|
|
public function calculateDefault(array $elements)
|
|
{
|
|
$results = [];
|
|
|
|
foreach ($this->defaultCalculator as $alias) {
|
|
$calculator = $this->calculators[$alias];
|
|
$result = $calculator->calculate($elements);
|
|
|
|
if (null !== $result) {
|
|
$results[$calculator::getAlias()] = $result;
|
|
}
|
|
}
|
|
|
|
return $results;
|
|
}
|
|
|
|
/**
|
|
* @param string $alias
|
|
*
|
|
* @return CalculatorInterface
|
|
*/
|
|
public function getCalculator($alias)
|
|
{
|
|
if (false === array_key_exists($alias, $this->calculators)) {
|
|
throw new OutOfBoundsException("The calculator with alias '{$alias}' does "
|
|
. 'not exists. Possible values are ' . implode(', ', array_keys($this->calculators)));
|
|
}
|
|
|
|
return $this->calculators[$alias];
|
|
}
|
|
}
|