Move normalize() into Set2.

Dropping the ability to 'normalize' string data.
This commit is contained in:
mark_story 2012-01-15 21:42:54 -05:00
parent e736ea3af9
commit ad65098348
2 changed files with 57 additions and 0 deletions

View file

@ -447,4 +447,30 @@ class Set2Test extends CakeTestCase {
$this->assertEquals(Set2::merge($a, $b), $expected);
}
/**
* test normalizing arrays
*
* @return void
*/
public function testNormalize() {
$result = Set2::normalize(array('one', 'two', 'three'));
$expected = array('one' => null, 'two' => null, 'three' => null);
$this->assertEquals($expected, $result);
$result = Set2::normalize(array('one', 'two', 'three'), false);
$expected = array('one', 'two', 'three');
$this->assertEquals($expected, $result);
$result = Set2::normalize(array('one' => 1, 'two' => 2, 'three' => 3, 'four'), false);
$expected = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => null);
$this->assertEquals($expected, $result);
$result = Set2::normalize(array('one' => 1, 'two' => 2, 'three' => 3, 'four'));
$expected = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => null);
$this->assertEquals($expected, $result);
$result = Set2::normalize(array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three'));
$expected = array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three' => null);
$this->assertEquals($expected, $result);
}
}

View file

@ -240,8 +240,39 @@ class Set2 {
return $data + $data2;
}
/**
* Normalizes an array, and converts it to a standard format.
*
* @param mixed $data List to normalize
* @param boolean $assoc If true, $data will be converted to an associative array.
* @return array
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::normalize
*/
public static function normalize(array $data, $assoc = true) {
$keys = array_keys($data);
$count = count($keys);
$numeric = true;
if (!$assoc) {
for ($i = 0; $i < $count; $i++) {
if (!is_int($keys[$i])) {
$numeric = false;
break;
}
}
}
if (!$numeric || $assoc) {
$newList = array();
for ($i = 0; $i < $count; $i++) {
if (is_int($keys[$i])) {
$newList[$data[$keys[$i]]] = null;
} else {
$newList[$keys[$i]] = $data[$keys[$i]];
}
}
$data = $newList;
}
return $data;
}
}