ソースを参照

Adding backwards compatible cookie reading back into CookieComponent.
Cookie values using the 1.x formatting will be read, and upon next write
be converted to json encoded values.
Fixes #1593

mark_story 15 年 前
コミット
63275626ee

+ 14 - 2
lib/Cake/Controller/Component/CookieComponent.php

@@ -467,12 +467,24 @@ class CookieComponent extends Component {
 
 /**
  * Explode method to return array from string set in CookieComponent::_implode()
+ * Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
  *
  * @param string $string A string containing JSON encoded data, or a bare string.
  * @return array Map of key and values
  */
 	protected function _explode($string) {
-		$ret = json_decode($string, true);
-		return ($ret != null) ? $ret : $string;
+		if ($string[0] === '{' || $string[0] === '[') {
+			$ret = json_decode($string, true);
+			return ($ret != null) ? $ret : $string;
+		}
+		$array = array();
+		foreach (explode(',', $string) as $pair) {
+			$key = explode('|', $pair);
+			if (!isset($key[1])) {
+				return $key[0];
+			}
+			$array[$key[0]] = $key[1];
+		}
+		return $array;
 	}
 }

+ 26 - 6
lib/Cake/tests/Case/Controller/Component/CookieComponentTest.php

@@ -471,6 +471,19 @@ class CookieComponentTest extends CakeTestCase {
 		unset($_COOKIE['CakeTestCookie']);
 	}
 
+/**
+ * Test Reading legacy cookie values.
+ *
+ * @return void
+ */
+	function testReadLegacyCookieValue() {
+		$_COOKIE['CakeTestCookie'] = array(
+			'Legacy' => array('value' => $this->_oldImplode(array(1, 2, 3)))
+		);
+		$result = $this->Cookie->read('Legacy.value');
+		$expected = array(1, 2, 3);
+		$this->assertEquals($expected, $result);
+	}
 
 /**
  * test that no error is issued for non array data.
@@ -485,14 +498,11 @@ class CookieComponentTest extends CakeTestCase {
 	}
 	
 /**
- * Implode method to keep keys are multidimensional arrays
+ * Helper method for generating old style encoded cookie values.
  *
- * @param array $array Map of key and values
- * @return string String in the form key1|value1,key2|value2
+ * @return string.
  */
-	protected function _implode(array $array) {
-		return json_encode($array);
-
+	protected function _oldImplode(array $array) {
 		$string = '';
 		foreach ($array as $key => $value) {
 			$string .= ',' . $key . '|' . $value;
@@ -501,6 +511,16 @@ class CookieComponentTest extends CakeTestCase {
 	}
 
 /**
+ * Implode method to keep keys are multidimensional arrays
+ *
+ * @param array $array Map of key and values
+ * @return string String in the form key1|value1,key2|value2
+ */
+	protected function _implode(array $array) {
+		return json_encode($array);
+	}
+
+/**
  * encrypt method
  *
  * @param mixed $value