- array_key_exists: documentation ( source)
- array_search: documentation ( source)
- is_scalar: documentation ( source)
- max: documentation ( source)
- get_class: documentation ( source)
- sprintf: documentation ( source)
<?php
namespace App\ServerArbiter;
use App\ServerArbiter\Rules\Rule,
App\Model\Entity\Server;
/**
* Class ServerArbiter
*
* @package App\ServerArbiter
*/
class ServerArbiter
{
/**
* @var RuleSet
*/
private $ruleSet;
/**
* @var Server[]
*/
private $servers;
public function __construct(RuleSet $ruleSet, array $servers)
{
foreach ($servers as $server)
{
if (!($server instanceof Server))
{
throw new \InvalidArgumentException(sprintf(
"Second parameter for: %s must be an array of Server objects. %s given which is an instance of %s.",
__METHOD__, $server, is_scalar($server) ? 'a scalar value' : get_class($server)
));
}
}
$this->ruleSet = $ruleSet;
$this->servers = $servers;
}
/**
* Run each Server against each Rule in the RuleSet and return the Server that matched the most rules
*
* @return Server The Server chosen by the ServerArbiter
*
* @note If two servers match the same number of rules successfully, the first one will be returned
*/
public function decide()
{
$decisions = [];
/** @var Rule $rule */
foreach ($this->ruleSet as $rule)
{
foreach ($this->servers as $server)
{
if (!array_key_exists($server->getId(), $decisions))
{
$decisions[$server->getId()]['successes'] = 0;
}
if ($rule->resolve())
{
$decisions[$server->getId()]['successes']++;
}
}
}
$decision = array_search(max($decisions), $decisions);
return $decision;
}
}