1: <?php
2: /**
3: * @package OpenCart
4: *
5: * @author Daniel Kerr
6: * @copyright Copyright (c) 2005 - 2022, OpenCart, Ltd. (https://www.opencart.com/)
7: * @license https://opensource.org/licenses/GPL-3.0
8: *
9: * @see https://www.opencart.com
10: */
11: namespace Opencart\System\Engine;
12: /**
13: * Class Event
14: *
15: * https://github.com/opencart/opencart/wiki/Events-(script-notifications)-2.2.x.x
16: */
17: class Event {
18: /**
19: * @var \Opencart\System\Engine\Registry
20: */
21: protected \Opencart\System\Engine\Registry $registry;
22: /**
23: * @var array<int, array<string, mixed>>
24: */
25: protected array $data = [];
26:
27: /**
28: * Constructor
29: *
30: * @param \Opencart\System\Engine\Registry $registry
31: */
32: public function __construct(\Opencart\System\Engine\Registry $registry) {
33: $this->registry = $registry;
34: }
35:
36: /**
37: * Register
38: *
39: * @param string $trigger
40: * @param \Opencart\System\Engine\Action $action
41: * @param int $priority
42: *
43: * @return void
44: */
45: public function register(string $trigger, \Opencart\System\Engine\Action $action, int $priority = 0): void {
46: $this->data[] = [
47: 'trigger' => $trigger,
48: 'action' => $action,
49: 'priority' => $priority
50: ];
51:
52: $sort_order = [];
53:
54: foreach ($this->data as $key => $value) {
55: $sort_order[$key] = $value['priority'];
56: }
57:
58: array_multisort($sort_order, SORT_ASC, $this->data);
59: }
60:
61: /**
62: * Trigger
63: *
64: * @param string $event
65: * @param array<mixed> $args
66: *
67: * @return mixed
68: */
69: public function trigger(string $event, array $args = []) {
70: foreach ($this->data as $value) {
71: if (preg_match('/^' . str_replace(['\*', '\?'], ['.*', '.'], preg_quote($value['trigger'], '/')) . '/', $event)) {
72: $value['action']->execute($this->registry, $args);
73: }
74: }
75:
76: return '';
77: }
78:
79: /**
80: * Unregister
81: *
82: * @param string $trigger
83: * @param string $route
84: *
85: * @return void
86: */
87: public function unregister(string $trigger, string $route): void {
88: foreach ($this->data as $key => $value) {
89: if ($trigger == $value['trigger'] && $value['action']->getId() == $route) {
90: unset($this->data[$key]);
91: }
92: }
93: }
94:
95: /**
96: * Clear
97: *
98: * @param string $trigger
99: *
100: * @return void
101: */
102: public function clear(string $trigger): void {
103: foreach ($this->data as $key => $value) {
104: if ($trigger == $value['trigger']) {
105: unset($this->data[$key]);
106: }
107: }
108: }
109: }
110: