Merge pull request #16169 from agh1/5.21.0-releasenotes-final
[civicrm-core.git] / CRM / Utils / GlobalStack.php
1 <?php /*
2 +--------------------------------------------------------------------+
3 | Copyright CiviCRM LLC. All rights reserved. |
4 | |
5 | This work is published under the GNU AGPLv3 license with some |
6 | permitted exceptions and without any warranty. For full license |
7 | and copyright information, see https://civicrm.org/licensing |
8 +--------------------------------------------------------------------+
9 */
10
11 /**
12 *
13 * @package CRM
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
15 */
16
17 /**
18 * Temporarily change a global variable.
19 *
20 * @code
21 * $globals = CRM_Utils_GlobalStack::singleton();
22 * $globals->push(array(
23 * '_GET' => array(
24 * 'q' => 'some-value
25 * ),
26 * ));
27 * ...do stuff...
28 * $globals->pop();
29 * @endcode
30 *
31 * Note: for purposes of this class, we'll refer to the array passed into
32 * push() as a frame.
33 */
34 class CRM_Utils_GlobalStack {
35 /**
36 * We don't have a container or dependency-injection, so use singleton instead
37 *
38 * @var object
39 */
40 private static $_singleton = NULL;
41
42 private $backups = [];
43
44 /**
45 * Get or set the single instance of CRM_Utils_GlobalStack.
46 *
47 * @return CRM_Utils_GlobalStack
48 */
49 public static function singleton() {
50 if (self::$_singleton === NULL) {
51 self::$_singleton = new CRM_Utils_GlobalStack();
52 }
53 return self::$_singleton;
54 }
55
56 /**
57 * @param $newFrame
58 */
59 public function push($newFrame) {
60 $this->backups[] = $this->createBackup($newFrame);
61 $this->applyFrame($newFrame);
62 }
63
64 public function pop() {
65 $this->applyFrame(array_pop($this->backups));
66 }
67
68 /**
69 * @param array $new
70 * The new, incoming frame.
71 * @return array
72 * frame
73 */
74 public function createBackup($new) {
75 $frame = [];
76 foreach ($new as $globalKey => $values) {
77 if (is_array($values)) {
78 foreach ($values as $key => $value) {
79 $frame[$globalKey][$key] = CRM_Utils_Array::value($key, $GLOBALS[$globalKey]);
80 }
81 }
82 else {
83 $frame[$globalKey] = CRM_Utils_Array::value($globalKey, $GLOBALS);
84 }
85 }
86 return $frame;
87 }
88
89 /**
90 * @param $newFrame
91 */
92 public function applyFrame($newFrame) {
93 foreach ($newFrame as $globalKey => $values) {
94 if (is_array($values)) {
95 foreach ($values as $key => $value) {
96 $GLOBALS[$globalKey][$key] = $value;
97 }
98 }
99 else {
100 $GLOBALS[$globalKey] = $values;
101 }
102 }
103 }
104
105 }