From cf930369757a5949f809d228686978221040f369 Mon Sep 17 00:00:00 2001 From: Leighton Shank Date: Mon, 8 Jul 2013 17:27:57 -0400 Subject: [PATCH] Allow custom setter methods to run for aliased attributes (fixes #350) The logic in the Model::__set() magic method allowed for either an aliased attribute *or* a custom setter, but not both. If a custom setter method was defined for an aliased attribute, then the attribute value would be set without going through the custom setter method. Changed the logic so that the _set() method first normalizes an aliased attribute into the real attribute name, then checks to see if an there is a custom setter method defined and runs it if it exists. --- lib/Model.php | 2 +- test/ActiveRecordTest.php | 16 ++++++++++++++++ test/models/Venue.php | 9 +++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/Model.php b/lib/Model.php index 1d98aca58..a956063c4 100644 --- a/lib/Model.php +++ b/lib/Model.php @@ -399,7 +399,7 @@ public function __set($name, $value) if (array_key_exists($name, static::$alias_attribute)) $name = static::$alias_attribute[$name]; - elseif (method_exists($this,"set_$name")) + if (method_exists($this,"set_$name")) { $name = "set_$name"; return $this->$name($value); diff --git a/test/ActiveRecordTest.php b/test/ActiveRecordTest.php index a20aa913f..f47667645 100644 --- a/test/ActiveRecordTest.php +++ b/test/ActiveRecordTest.php @@ -259,6 +259,22 @@ public function test_alias_attribute_setter() $this->assert_equals($venue->marquee, $venue->name); } + public function test_alias_attribute_custom_setter() + { + Venue::$use_custom_set_city_setter = true; + $venue = Venue::find(1); + + $venue->mycity = 'cityname'; + $this->assert_equals($venue->mycity, 'cityname#'); + $this->assert_equals($venue->mycity, $venue->city); + + $venue->city = 'anothercity'; + $this->assert_equals($venue->city, 'anothercity#'); + $this->assert_equals($venue->city, $venue->mycity); + + Venue::$use_custom_set_city_setter = false; + } + public function test_alias_from_mass_attributes() { $venue = new Venue(array('marquee' => 'meme', 'id' => 123)); diff --git a/test/models/Venue.php b/test/models/Venue.php index 38ad9241b..fd6e7c0b5 100644 --- a/test/models/Venue.php +++ b/test/models/Venue.php @@ -4,6 +4,7 @@ class Venue extends ActiveRecord\Model static $use_custom_get_state_getter = false; static $use_custom_set_state_setter = false; + static $use_custom_set_city_setter = false; static $has_many = array( 'events', @@ -32,6 +33,14 @@ public function set_state($value) else return $this->assign_attribute('state', $value); } + + public function set_city($value) + { + if (self::$use_custom_set_city_setter) + return $this->assign_attribute('city', $value . '#'); + else + return $this->assign_attribute('city', $value); + } }; ?>