1: <?php
2: /**
3: * @package OpenCart
4: *
5: * @author Daniel Kerr
6: * @copyright Copyright (c) 2005 - 2017, 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 Action
14: *
15: * @package Opencart\System\Engine
16: */
17: class Action {
18: /**
19: * @var string
20: */
21: private string $route;
22:
23: /**
24: * @var string
25: */
26: private string $method;
27:
28: /**
29: * Constructor
30: *
31: * @param string $route
32: */
33: public function __construct(string $route) {
34: $route = preg_replace('/[^a-zA-Z0-9_|\/\.]/', '', $route);
35:
36: $pos = strrpos($route, '.');
37:
38: if ($pos !== false) {
39: $this->route = substr($route, 0, $pos);
40: $this->method = substr($route, $pos + 1);
41: } else {
42: $this->route = $route;
43: $this->method = 'index';
44: }
45: }
46:
47: /**
48: * getId
49: *
50: * @return string
51: */
52: public function getId(): string {
53: return $this->route;
54: }
55:
56: /**
57: * Execute
58: *
59: * @param \Opencart\System\Engine\Registry $registry
60: * @param array<mixed> $args
61: *
62: * @return mixed
63: */
64: public function execute(\Opencart\System\Engine\Registry $registry, array &$args = []) {
65: // Stop any magical methods being called
66: if (substr($this->method, 0, 2) == '__') {
67: return new \Exception('Error: Calls to magic methods are not allowed!');
68: }
69:
70: // Create a key to store the controller object
71: $key = 'controller_' . str_replace('/', '_', $this->route);
72:
73: if (!$registry->has($key)) {
74: // Initialize the class
75: $controller = $registry->get('factory')->controller($this->route);
76:
77: // Store object
78: $registry->set($key, $controller);
79: } else {
80: $controller = $registry->get($key);
81: }
82:
83: // If action cannot be executed, we return an action error object.
84: if ($controller instanceof \Exception) {
85: return new \Exception('Error: Could not call route ' . $this->route . '!');
86: }
87:
88: $callable = [$controller, $this->method];
89:
90: if (is_callable($callable)) {
91: return $callable(...$args);
92: } else {
93: return new \Exception('Error: Could not call route ' . $this->route . '!');
94: }
95: }
96: }
97: