Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Move normalize() into Set2.

Dropping the ability to 'normalize' string data.
  • Loading branch information...
commit ad6509834817ac7425efcb5ef3dd16417f0662fd 1 parent e736ea3
@markstory markstory authored
View
26 lib/Cake/Test/Case/Utility/Set2Test.php
@@ -447,4 +447,30 @@ public function testMerge() {
$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
33 lib/Cake/Utility/Set2.php
@@ -240,8 +240,39 @@ public static function diff(array $data, $data2) {
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;
}
}
Please sign in to comment.
Something went wrong with that request. Please try again.