Details
-
Type:
New Feature
-
Status:
Resolved
-
Priority:
Minor
-
Resolution: Needs Proposal
-
Affects Version/s: 1.0.3
-
Fix Version/s: 1.10.0
-
Component/s: Zend_Filter
-
Labels:None
-
Fix Version Priority:Nice to Have
Description
A new filter that converts values to booleans.
class Zend_Filter_Boolean implements Zend_Filter_Interface { /** * Values that are equivilent to true. * * @var array */ protected $_true = array('t', 'true', 'y', 'yes', '1'); /** * Values that are equivilent to false. * * @var array */ protected $_false = array('f', 'false', 'n', 'no', '0'); /** * The default value if the provided value does not match any of the * expected values. * * @var bool */ protected $_default = false; /** * Constructs a boolean filter. * * @param bool $default The default value if the provided value * does not match any of the expected values. */ public function __construct($default = false) { $this->_default = (bool) $default; } /** * Casts value to a boolean. * * @param mixed $value * * @return bool */ public function filter($value) { if (is_bool($value) || is_null($value)) { return (bool) $value; } $value = strtolower(trim($value)); if (in_array($value, $this->_true)) { return true; } if (in_array($value, $this->_false)) { return false; } return $this->_default; } }
Hi Jordan,
I agree with this filter, but I think the class deserves a little more discussion.
I gave a look at your suggestion but, for example, it seems unable to handle an array.
I would expect an empty array to be evaluated as false and a not empty array as true, as (bool) already does.
It doesn't handle objects as well.
I suggest to check whether the variable is a scalar type (http://php.net/manual/en/function.is-scalar.php).
If no, the default (bool) cast statement might be used, otherwise we could rely to in_array() comparison.
Additionally, it would be great to provide an #addValue method (or perhaps #addTrue() and #addFalse() methods) to let developers add more values to default array.
What do you think?