Add list of blacklisted array functions, add more tests

This commit is contained in:
Timothy Warren 2012-05-24 11:59:15 -04:00
parent c786004f22
commit 1dd57b18de
3 changed files with 74 additions and 5 deletions

View File

@ -30,6 +30,8 @@ class JSObject extends ArrayObject {
foreach($params as $name => &$val)
{
if (empty($val)) continue;
// Bind '$this' for closures
if ($val instanceof Closure)
{
@ -52,11 +54,34 @@ class JSObject extends ArrayObject {
*/
public function __call($name, $params = [])
{
$function_blacklist = [
'array_change_key_case',
'array_combine',
'array_count_values',
'array_fill_keys',
'array_fill',
'array_key_exists',
'array_map',
'array_merge',
'array_merge_recursive',
'array_search',
'array_unshift',
];
// Allow array operations on the object
if (substr($name, 0, 6) === 'array_' && is_callable($name))
if (substr($name, 0, 6) === 'array_' && is_callable($name) && ! in_array($name, $function_blacklist))
{
$args = array_merge($this->getArrayCopy(), $params);
return call_user_func_array($name, [$args]);
$args = ( ! empty($params))
? array_merge($this->getArrayCopy(), $params)
: $this->getArrayCopy();
// Make sure the array items in the array parameter aren't used as function parameters
if (count($args === 1))
{
$args = [$args];
}
return call_user_func_array($name, $args);
}
// Call closures attached to the object

View File

@ -3,9 +3,25 @@ JSObject
A PHP 5.4 class to emulate Javascript object literals.
Also, can use ``array_`` functions to operate on the object's properties and values. (Only works for functions that start with ``array_`` and have the array as the first parameter)
Also, can use ``array_`` functions to operate on the object's properties and values. (Only works for functions that start with ``array_`` and have the array as the first parameter.)
Examples:
The following array functions are blacklisted because of their parameter ordering, or unpredictable behavior:
* array_change_key_case
* array_count_values
* array_combine
* array_fill_keys
* array_fill
* array_key_exists
* array_map
* array_merge
* array_merge_recursive
* array_search
* array_unshift
##Examples:
* Basic Usage

View File

@ -15,6 +15,8 @@ require_once('simpletest/autorun.php');
// Include JSObject
require_once('JSObject.php');
class JSObjectTests extends UnitTestCase {
function TestIsA()
@ -41,6 +43,22 @@ class JSObjectTests extends UnitTestCase {
$this->assertEqual($obj->x(), 50);
}
// List of blacklisted array functions
/*
'array_change_key_case',
'array_count_values',
'array_combine',
'array_fill_keys',
'array_fill',
'array_key_exists',
'array_map',
'array_merge',
'array_merge_recursive',
'array_search',
'array_unshift',
*/
function TestArrayFlip()
{
$obj = new JSObject([
@ -60,5 +78,15 @@ class JSObjectTests extends UnitTestCase {
$this->assertEqual($obj->array_keys(), ['x','y']);
}
function TestArrayValues()
{
$obj = new JSObject([
'x' => 'foo',
'y' => 'bar'
]);
$this->assertEqual($obj->array_values(), ['foo','bar']);
}
}