From dcf98ad0f362652755137f8d4c7abc0dff3f75af Mon Sep 17 00:00:00 2001 From: Igor Santos Date: Thu, 20 Jun 2013 03:35:12 -0300 Subject: [PATCH 1/2] Allows for aliased methods in serialization, so we can do stuff like `$model->to_array(['methods' => ['get_name' => 'name']]);` --- lib/Serialization.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/Serialization.php b/lib/Serialization.php index ed54cef81..6d266a1d8 100644 --- a/lib/Serialization.php +++ b/lib/Serialization.php @@ -136,10 +136,13 @@ private function check_methods() { $this->options_to_a('methods'); - foreach ($this->options['methods'] as $method) + foreach ($this->options['methods'] as $method => $name) { + if (is_numeric($method)) + $method = $name; + if (method_exists($this->model, $method)) - $this->attributes[$method] = $this->model->$method(); + $this->attributes[$name] = $this->model->$method(); } } } From ae50f6e710609830a7619839c7cf692b7fe7f3be Mon Sep 17 00:00:00 2001 From: Koen Punt Date: Sun, 20 Jul 2014 13:32:12 +0200 Subject: [PATCH 2/2] add test for serialization method alias --- test/SerializationTest.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/test/SerializationTest.php b/test/SerializationTest.php index d82e4277c..562e24d39 100644 --- a/test/SerializationTest.php +++ b/test/SerializationTest.php @@ -64,14 +64,21 @@ public function test_methods_takes_a_string() $this->assert_equals('ANCIENT ART OF MAIN TANKING', $a['upper_name']); } - // methods added last should we shuld have value of the method in our json - // rather than the regular attribute value + // methods should take precedence over attributes public function test_methods_method_same_as_attribute() { $a = $this->_a(array('methods' => 'name')); $this->assert_equals('ancient art of main tanking', $a['name']); } + public function test_methods_method_alias() + { + $a = $this->_a(array('methods' => array('name' => 'alias_name'))); + $this->assert_equals('ancient art of main tanking', $a['alias_name']); + $a = $this->_a(array('methods' => array('upper_name' => 'name'))); + $this->assert_equals('ANCIENT ART OF MAIN TANKING', $a['name']); + } + public function test_include() { $a = $this->_a(array('include' => array('author')));