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 Factory
14: */
15: class Factory {
16: /**
17: * @var \Opencart\System\Engine\Registry
18: */
19: protected \Opencart\System\Engine\Registry $registry;
20:
21: /**
22: * Constructor
23: *
24: * @param \Opencart\System\Engine\Registry $registry
25: */
26: public function __construct(\Opencart\System\Engine\Registry $registry) {
27: $this->registry = $registry;
28: }
29:
30: /**
31: * Controller
32: *
33: * @param string $route
34: *
35: * @return \Exception|\Opencart\System\Engine\Controller
36: */
37: public function controller(string $route): object {
38: // Sanitize the call
39: $route = preg_replace('/[^a-zA-Z0-9_\/]/', '', $route);
40:
41: // Class path
42: $class = 'Opencart\\' . $this->registry->get('config')->get('application') . '\Controller\\' . str_replace(['_', '/'], ['', '\\'], ucwords($route, '_/'));
43:
44: if (class_exists($class)) {
45: return new $class($this->registry);
46: } else {
47: return new \Exception('Error: Could not load controller ' . $route . '!');
48: }
49: }
50:
51: /**
52: * Model
53: *
54: * @param string $route
55: *
56: * @return \Opencart\System\Engine\Model
57: */
58: public function model(string $route): object {
59: // Sanitize the call
60: $route = preg_replace('/[^a-zA-Z0-9_\/]/', '', $route);
61:
62: // Generate the class
63: $class = 'Opencart\\' . $this->registry->get('config')->get('application') . '\Model\\' . str_replace(['_', '/'], ['', '\\'], ucwords($route, '_/'));
64:
65: // Check if the requested model is already stored in the registry.
66: if (class_exists($class)) {
67: return new $class($this->registry);
68: } else {
69: throw new \Exception('Error: Could not load model ' . $route . '!');
70: }
71: }
72:
73: /**
74: * Library
75: *
76: * @param string $route
77: * @param array<mixed> $args
78: *
79: * @return object
80: */
81: public function library(string $route, array $args): object {
82: // Sanitize the call
83: $route = preg_replace('/[^a-zA-Z0-9_\/]/', '', $route);
84:
85: // Generate the class
86: $class = 'Opencart\System\Library\\' . str_replace(['_', '/'], ['', '\\'], ucwords($route, '_/'));
87:
88: // Check if the requested model is already stored in the registry.
89: if (class_exists($class)) {
90: return new $class(...$args);
91: } else {
92: throw new \Exception('Error: Could not load library ' . $route . '!');
93: }
94: }
95: }
96: