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 +--------------------------------------------------------------------+
13 * A lazy-array works much like a regular array or ArrayObject. However, it is
14 * initially empty - and it is only populated if used.
16 class CRM_Utils_LazyArray
implements ArrayAccess
, IteratorAggregate
, Countable
{
19 * A function which generates a list of values.
22 * function(): iterable
34 * CRM_Utils_LazyList constructor.
36 * @param callable $func
37 * Function which provides a list of values (array/iterator/generator).
39 public function __construct($func) {
44 * Determine if the content has been fetched.
48 public function isLoaded() {
49 return $this->cache
!== NULL;
52 public function load($force = FALSE) {
53 if ($this->cache
=== NULL ||
$force) {
54 $this->cache
= CRM_Utils_Array
::cast(call_user_func($this->func
));
59 public function offsetExists($offset) {
60 return isset($this->load()->cache
[$offset]);
63 public function &offsetGet($offset) {
64 return $this->load()->cache
[$offset];
67 public function offsetSet($offset, $value) {
68 if ($offset === NULL) {
69 $this->load()->cache
[] = $value;
72 $this->load()->cache
[$offset] = $value;
76 public function offsetUnset($offset) {
77 unset($this->load()->cache
[$offset]);
80 public function getIterator() {
81 return new ArrayIterator($this->load()->cache
);
87 public function getArrayCopy() {
88 return $this->load()->cache
;
91 public function count() {
92 return count($this->load()->cache
);