| 1: | <?php |
| 2: | /* |
| 3: | * SimpleID |
| 4: | * |
| 5: | * Copyright (C) Kelvin Mo 2021-2025 |
| 6: | * |
| 7: | * This program is free software; you can redistribute it and/or |
| 8: | * modify it under the terms of the GNU General Public |
| 9: | * License as published by the Free Software Foundation; either |
| 10: | * version 2 of the License, or (at your option) any later version. |
| 11: | * |
| 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 GNU |
| 15: | * General Public License for more details. |
| 16: | * |
| 17: | * You should have received a copy of the GNU General Public |
| 18: | * License along with this program; if not, write to the Free |
| 19: | * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. |
| 20: | * |
| 21: | */ |
| 22: | |
| 23: | namespace SimpleID\Util\Events; |
| 24: | |
| 25: | /** |
| 26: | * A generic event used to collect data with a specified order. |
| 27: | * |
| 28: | * Unlike the {@link BaseDataCollectionEvent}, results are always |
| 29: | * appended to the results array and never merged. |
| 30: | * |
| 31: | */ |
| 32: | class OrderedDataCollectionEvent extends BaseDataCollectionEvent { |
| 33: | /** |
| 34: | * Creates an ordered data collection event |
| 35: | * |
| 36: | * @param string $eventName the name of the event, or null to use |
| 37: | * the name of this class |
| 38: | */ |
| 39: | public function __construct($eventName = null) { |
| 40: | parent::__construct($eventName, self::MERGE_APPEND); |
| 41: | } |
| 42: | |
| 43: | /** |
| 44: | * Adds data to the event with a specified weight. The weight |
| 45: | * is used to order the results, to be retrieved by |
| 46: | * {@link OrderedDataCollectionEvent::getResults()}. |
| 47: | * |
| 48: | * @param array<mixed> $result the data to add |
| 49: | * @param int $weight the weight |
| 50: | * @return void |
| 51: | */ |
| 52: | public function addResult($result, $weight = 0) { |
| 53: | if ($this->isEmpty($result)) return; |
| 54: | |
| 55: | parent::addResult([ |
| 56: | '#data' => $result, |
| 57: | '#weight' => $weight |
| 58: | ]); |
| 59: | } |
| 60: | |
| 61: | /** |
| 62: | * Retrieves the data collected from the event, ordered by the |
| 63: | * weight, from lowest to highest. |
| 64: | * |
| 65: | * @return array<mixed> |
| 66: | */ |
| 67: | public function getResults() { |
| 68: | uasort($this->results, function($a, $b) { if ($a['#weight'] == $b['#weight']) { return 0; } return ($a['#weight'] < $b['#weight']) ? -1 : 1; }); |
| 69: | return array_map(function($a) { return $a['#data']; }, $this->results); |
| 70: | } |
| 71: | } |
| 72: | |
| 73: | ?> |