- var_dump: documentation ( source)
- preg_match_all: documentation ( source)
- in_array: documentation ( source)
<?php
interface PolicyRule
{
public function isSatisfiedBy(string $aValue);
}
class CredentialPolicy implements PolicyRule
{
private $maximumDaysOld;
private $policyRules = [];
public function __construct(array $aPolicyRuleSet)
{
foreach ($aPolicyRuleSet as $rule) {
if ($rule instanceof PolicyRule && $rule !== $this) {
$this->policyRules[] = $rule;
}
}
}
public function isSatisfiedBy(string $aCredential) : bool
{
foreach ($this->policyRules as $rule) {
if (! $rule->isSatisfiedBy($aCredential)) {
return false;
}
}
return true;
}
}
abstract class EnforcedRule implements PolicyRule
{
const UNENFORCED = 0;
const ENFORCED = 1;
private $enforcementType;
protected function isEnforced() : bool
{
return ($this->enforcementType == self::ENFORCED);
}
protected function setEnforcementType(int $aType)
{
$this->guardEnforcementType($aType);
$this->enforcementType = $aType;
}
protected function guardEnforcementType(int $aType)
{
if (! in_array($aType, [self::UNENFORCED, self::ENFORCED])) {
throw new InvalidEnforcementTypeException($aType);
}
}
}
abstract class MinimumCharacterCountRule extends EnforcedRule
{
const DEFAULT_MINIMUM = 1;
protected $regexPattern;
protected $minimumCount = self::DEFAULT_MINIMUM;
public function isSatisfiedBy(string $aValue) : bool
{
if (! $this->isEnforced()) {
return true;
}
$matches = [];
preg_match_all($this->regexPattern, $aValue, $matches);
return (count($matches[0]) >= $this->minimumCount);
}
}
class NumericRule extends MinimumCharacterCountRule
{
protected $regexPattern = '/[0-9]/';
public function __construct(int $aMinimumCount = self::DEFAULT_MINIMUM, int $anEnforcementType = self::ENFORCED)
{
$this->setEnforcementType($anEnforcementType);
$this->minimumCount = $aMinimumCount;
}
}
class SpecialCharacterRule extends MinimumCharacterCountRule
{
protected $regexPattern = '/[~`#\$%\^&\*\(\)\-_\+\|,\.<>]/';
public function __construct(int $aMinimumCount = self::DEFAULT_MINIMUM, int $anEnforcementType = self::ENFORCED)
{
$this->setEnforcementType($anEnforcementType);
$this->minimumCount = $aMinimumCount;
}
}
$policy = new CredentialPolicy([
new NumericRule(), new SpecialCharacterRule()
]);
var_dump($policy->isSatisfiedBy("for5"));