|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * Copyright 2011 Facebook, Inc. |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | + |
| 19 | +class PhabricatorEventEngine { |
| 20 | + |
| 21 | + private static $instance; |
| 22 | + |
| 23 | + private $listeners = array(); |
| 24 | + |
| 25 | + private function __construct() { |
| 26 | + // <empty> |
| 27 | + } |
| 28 | + |
| 29 | + public static function initialize() { |
| 30 | + self::$instance = new PhabricatorEventEngine(); |
| 31 | + |
| 32 | + // Instantiate and register custom event listeners so they can react to |
| 33 | + // events. |
| 34 | + $listeners = PhabricatorEnv::getEnvConfig('events.listeners'); |
| 35 | + foreach ($listeners as $listener) { |
| 36 | + id(new $listener())->register(); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static function getInstance() { |
| 41 | + if (!self::$instance) { |
| 42 | + throw new Exception("Event engine has not been initialized!"); |
| 43 | + } |
| 44 | + return self::$instance; |
| 45 | + } |
| 46 | + |
| 47 | + public function addListener( |
| 48 | + PhabricatorEventListener $listener, |
| 49 | + $type) { |
| 50 | + $this->listeners[$type][] = $listener; |
| 51 | + return $this; |
| 52 | + } |
| 53 | + |
| 54 | + public static function dispatchEvent(PhabricatorEvent $event) { |
| 55 | + $instance = self::getInstance(); |
| 56 | + |
| 57 | + $listeners = idx($instance->listeners, $event->getType(), array()); |
| 58 | + foreach ($listeners as $listener) { |
| 59 | + if ($event->isStopped()) { |
| 60 | + // Do this first so if someone tries to dispatch a stopped event it |
| 61 | + // doesn't go anywhere. Silly but less surprising. |
| 62 | + break; |
| 63 | + } |
| 64 | + $listener->handleEvent($event); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments