initial checkin
[m6w6/hikke] / lib / hikke / Event.php
1 <?php
2
3 /**
4 * Hikke
5 *
6 * @author Michael Wallner <mike@php.net>
7 */
8 namespace hikke;
9
10 use hikke\Event\Priority;
11 use hikke\Event\Storage;
12
13 /**
14 * Event
15 *
16 * @package hikke\Event
17 */
18 class Event extends Priority implements \SplSubject, \IteratorAggregate, \Countable
19 {
20 /**
21 * @var string
22 */
23 private $name;
24
25 /**
26 * @var float
27 */
28 private $priority;
29
30 /**
31 * @var hikke\Event\Storage
32 */
33 private $storage;
34
35 /**
36 * Create a new event
37 * @param string $name custom event name
38 * @param int|float $priority
39 */
40 public function __construct($name, $priority = 0) {
41 $this->name = $name;
42 $this->priority = $priority;
43 $this->storage = new Storage;
44 }
45
46 /**
47 * Returns the event name
48 * @return string
49 */
50 public function __toString() {
51 return (string) $this->name;
52 }
53
54 /**
55 * Get priority of this event
56 * @return float
57 */
58 public function getPriority() {
59 return $this->priority;
60 }
61
62 /**
63 * Get the event name
64 * @return string
65 */
66 public function getName() {
67 return $this->name;
68 }
69
70 /**
71 * Update priority of this event
72 * @param float $priority
73 */
74 public function setPriority($priority) {
75 $this->priority = $priority;
76 }
77
78 /**
79 * Attach an event observer
80 * @param \SplObserver $observer
81 * @param float $priority
82 * @return \hikke\Event
83 */
84 public function attach(\SplObserver $observer, $priority = 0) {
85 $this->storage->insert($observer, $priority);
86 return $this;
87 }
88
89 /**
90 * Detach an already attached event observer
91 * @param \SplObserver $observer
92 * @return bool whether the observer was attached
93 */
94 public function detach(\SplObserver $observer) {
95 return $this->storage->delete($observer);
96 }
97
98 /**
99 * Notify attached observers
100 * @param \SplSubject $origin
101 */
102 public function notify(\SplSubject $origin = null) {
103 foreach ($this->storage as $observer) {
104 $observer->update($origin ?: $this, $this);
105 }
106 }
107
108 /**
109 * @ignore
110 */
111 public function count() {
112 return count($this->storage);
113 }
114
115 /**
116 * @ignore
117 */
118 public function getIterator() {
119 return $this->storage;
120 }
121 }