How can the normalize() method below be improved? I've extracted the functionality from a project I'm working on into a simple class for the purposes of this question.
The method takes a string input and compares it to a set of 'truthy' and 'falsey' strings, returning true or false respectively if a case insensitive match is found. The truthy and falsey strings are mutable so cannot be hard coded into the method.
If the $nullable property is set to true and no match is found, null is returned. Otherwise false is returned.
I feel as though I may be missing a trick by looping through the array and calling strcasecmp twice for each iteration.
<?php
class BooleanNormalizer
{
/** @var array */
public $binaries = [
'yes' => 'no',
'1' => '0',
'on' => 'off',
'enabled' => 'disabled',
];
/** @var bool */
public $nullable = false;
/**
* @param string $value
*
* @return bool|null
*/
public function normalize($value)
{
foreach ($this->binaries as $truthy => $falsey) {
if (strcasecmp($value, $truthy) === 0) {
return true;
}
if (strcasecmp($value, $falsey) === 0) {
return false;
}
}
return ($this->nullable) ? null : false;
}
}
Usage:
$normalizer = new BooleanNormalizer();
$normalizer->nullable = true;
$normalizer->binaries = ['enabled' => 'disabled'];
$normalizer->normalize('enabled'); // returns true
$normalizer->normalize('disabled'); // returns false
$normalizer->normalize('blah'); // returns null