3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 * The Collection classes inheriting from this abstract class are meant to represent a list of database record.
26 * The associated model class has to be provided in the child classes.
28 * Collections can be used with foreach(), accessed like an array and counted.
30 abstract class BaseCollection extends \ArrayIterator
33 * This property is used with paginated results to hold the total number of items satisfying the paginated request.
36 protected $totalCount = 0;
39 * @param BaseEntity[] $entities
40 * @param int|null $totalCount
42 public function __construct(array $entities = [], int $totalCount = null)
44 parent::__construct($entities);
46 $this->totalCount = $totalCount ?? count($entities);
52 public function offsetSet($offset, $value)
54 if (is_null($offset)) {
58 parent::offsetSet($offset, $value);
64 public function offsetUnset($offset)
66 if ($this->offsetExists($offset)) {
70 parent::offsetUnset($offset);
76 public function getTotalCount()
78 return $this->totalCount;
82 * Return the values from a single field in the collection
84 * @param string $column
85 * @param int|null $index_key
89 public function column($column, $index_key = null)
91 return array_column($this->getArrayCopy(), $column, $index_key);
95 * Apply a callback function on all elements in the collection and returns a new collection with the updated elements
97 * @param callable $callback
98 * @return BaseCollection
101 public function map(callable $callback)
103 return new static(array_map($callback, $this->getArrayCopy()), $this->getTotalCount());
107 * Filters the collection based on a callback that returns a boolean whether the current item should be kept.
109 * @param callable|null $callback
111 * @return BaseCollection
112 * @see array_filter()
114 public function filter(callable $callback = null, int $flag = 0)
116 return new static(array_filter($this->getArrayCopy(), $callback, $flag));