From b812aefb240f269303e2f4cac9c7ddc1df7d4fc6 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Fri, 24 Jul 2015 20:43:08 -0700 Subject: [PATCH] CRM_Utils_AutoClean --- CRM/Utils/AutoClean.php | 98 +++++++++++++++++++++++ tests/phpunit/CRM/Utils/AutoCleanTest.php | 58 ++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 CRM/Utils/AutoClean.php create mode 100644 tests/phpunit/CRM/Utils/AutoCleanTest.php diff --git a/CRM/Utils/AutoClean.php b/CRM/Utils/AutoClean.php new file mode 100644 index 0000000000..a4eab9bf53 --- /dev/null +++ b/CRM/Utils/AutoClean.php @@ -0,0 +1,98 @@ +args = func_get_args(); + $ac->callback = array_shift($ac->args); + return $ac; + } + + /** + * Temporarily swap values using callback functions, and cleanup + * when the current context shuts down. + * + * @code + * function doStuff() { + * $ac = CRM_Utils_AutoClean::swap('My::get', 'My::set', 'tmpValue'); + * ... + * } + * @endcode + * + * @param mixed $getter + * Function to lookup current value. + * @param mixed $setter + * Function to set new value. + * @param mixed $tmpValue + * The value to temporarily use. + * @return CRM_Utils_AutoClean + * @see \Civi\Core\Resolver + */ + public static function swap($getter, $setter, $tmpValue) { + $resolver = \Civi\Core\Resolver::singleton(); + + $origValue = $resolver->call($getter, array()); + + $ac = new CRM_Utils_AutoClean(); + $ac->callback = $setter; + $ac->args = array($origValue); + + $resolver->call($setter, array($tmpValue)); + + return $ac; + } + + public function __destruct() { + \Civi\Core\Resolver::singleton()->call($this->callback, $this->args); + } + +} diff --git a/tests/phpunit/CRM/Utils/AutoCleanTest.php b/tests/phpunit/CRM/Utils/AutoCleanTest.php new file mode 100644 index 0000000000..f4ffcd07d2 --- /dev/null +++ b/tests/phpunit/CRM/Utils/AutoCleanTest.php @@ -0,0 +1,58 @@ +useTransaction(); + parent::setUp(); + } + + public function testAutoclean() { + $this->foo = 'orig'; + $this->assertEquals('orig', $this->foo); + $this->nestedWithArrayCb(); + $this->assertEquals('orig', $this->foo); + $this->nestedWithFuncCb(); + $this->assertEquals('orig', $this->foo); + $this->nestedSwap(); + $this->assertEquals('orig', $this->foo); + } + + public function nestedWithArrayCb() { + $this->foo = 'arraycb'; + $ac = CRM_Utils_AutoClean::with(array($this, 'setFoo'), 'orig'); + $this->assertEquals('arraycb', $this->foo); + } + + public function nestedWithFuncCb() { + $this->foo = 'funccb'; + + $self = $this; /* php 5.3 */ + $ac = CRM_Utils_AutoClean::with(function () use ($self /* php 5.3 */) { + $self->foo = 'orig'; + }); + + $this->assertEquals('funccb', $this->foo); + } + + public function nestedSwap() { + $ac = CRM_Utils_AutoClean::swap(array($this, 'getFoo'), array($this, 'setFoo'), 'tmp'); + $this->assertEquals('tmp', $this->foo); + } + + public function getFoo() { + return $this->foo; + } + + public function setFoo($value) { + $this->foo = $value; + } + +} -- 2.25.1