3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Class CRM_Utils_AutoClean
21 * Automatically cleanup state when the object handle is released.
22 * This is useful for unordered cleanup when a function has many
23 * different exit scenarios (eg multiple returns, exceptions).
25 class CRM_Utils_AutoClean
{
30 * Call a cleanup function when the current context shuts down.
33 * function doStuff() {
34 * $ac = CRM_Utils_AutoClean::with(function(){
41 * @param mixed $callback
42 * @return CRM_Utils_AutoClean
44 public static function with($callback) {
45 $ac = new CRM_Utils_AutoClean();
46 $ac->args
= func_get_args();
47 $ac->callback
= array_shift($ac->args
);
52 * Temporarily swap values using callback functions, and cleanup
53 * when the current context shuts down.
56 * function doStuff() {
57 * $ac = CRM_Utils_AutoClean::swap('My::get', 'My::set', 'tmpValue');
62 * @param mixed $getter
63 * Function to lookup current value.
64 * @param mixed $setter
65 * Function to set new value.
66 * @param mixed $tmpValue
67 * The value to temporarily use.
68 * @return CRM_Utils_AutoClean
69 * @see \Civi\Core\Resolver
71 public static function swap($getter, $setter, $tmpValue) {
72 $resolver = \Civi\Core\Resolver
::singleton();
74 $origValue = $resolver->call($getter, []);
76 $ac = new CRM_Utils_AutoClean();
77 $ac->callback
= $setter;
78 $ac->args
= [$origValue];
80 $resolver->call($setter, [$tmpValue]);
85 public function __destruct() {
86 \Civi\Core\Resolver
::singleton()->call($this->callback
, $this->args
);
90 * Prohibit (de)serialization of CRM_Utils_AutoClean.
92 * The generic nature of AutoClean makes it a potential target for escalating
93 * serialization vulnerabilities, and there's no good reason for serializing it.
95 public function __sleep() {
96 throw new \
RuntimeException("CRM_Utils_AutoClean is a runtime helper. It is not intended for serialization.");
100 * Prohibit (de)serialization of CRM_Utils_AutoClean.
102 * The generic nature of AutoClean makes it a potential target for escalating
103 * serialization vulnerabilities, and there's no good reason for deserializing it.
105 public function __wakeup() {
106 throw new \
RuntimeException("CRM_Utils_AutoClean is a runtime helper. It is not intended for deserialization.");