Yii's
CPropertyValue class is interesting. It has some useful methods to convert values. Some examples:
var_dump( CPropertyValue::ensureArray( '1,2,a' ) );
/* output: array 0 => string '1,2,3' (length=5) */
var_dump( CPropertyValue::ensureArray( '(1,2,"a")' ) );
/* output:
array
0 => int 1
1=> int 2
2 => string 'a' (length=1)
*/
var_dump( CPropertyValue::ensureBoolean( "TRUE" ) );
/* output: boolean true */
var_dump( CPropertyValue::ensureBoolean( "yii" ) );
/* output: boolean false */
var_dump( CPropertyValue::ensureFloat( "3.9" ) );
/* output: float 3.9 */
var_dump( CPropertyValue::ensureInteger( "3.9" ) );
/* output: int 3 */
var_dump( CPropertyValue::ensureObject( array("a"=>1, "b"=>2) ) );
/* output:
object(stdClass)[53]
public 'a' => int 0
public 'b' => int 1
*/
var_dump( CPropertyValue::ensureString( 5 ) );
/* output: string 5 (length=1) */
ensureEnum ensures that a value is among a list of enumerated values. pass it in a value and a class name that extends CEnumerable and it will throw an error if value is not among the enumerated values.
class SortDirection extends CEnumerable
{
const Asc="Asc";
const Desc="Desc";
}
var_dump( CPropertyValue::ensureEnum( "Up" , 'SortDirection' ) );
/* output: throws an error */
var_dump( CPropertyValue::ensureEnum( "Asc" , 'SortDirection' ) );
/* output: string 'Asc' (length=3) */
No comments:
Post a Comment