PluginProbe
WooCommerce / 11.1.0
WooCommerce v11.1.0
11.1.0 11.1.0-rc.2 11.1.0-rc.1 11.1.0-beta.2 11.1.0-beta.1 11.0.1 11.0.0 11.0.0-rc.3 11.0.0-rc.2 11.0.0-rc.1 11.0.0-beta.2 11.0.0-beta.1 10.9.4 10.9.3 10.9.2 10.9.1 10.9.0 10.9.0-rc.1 10.9.0-beta.2 10.9.0-beta.1 10.8.1 10.8.0 10.8.0-rc.1 10.8.0-beta.2 10.8.0-beta.1 All 648 releases
woocommerce / packages / email-editor / src / class-container.php
class-container.php
93 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * This file is part of the WooCommerce Email Editor package
4 *
5 * @package Automattic\WooCommerce\EmailEditor
6 */
7
8 declare( strict_types = 1 );
9 namespace Automattic\WooCommerce\EmailEditor;
10
11 /**
12 * Class Container is a simple dependency injection container.
13 *
14 * @package Automattic\WooCommerce\EmailEditor
15 */
16 class Container {
17 /**
18 * A list of registered services
19 *
20 * @var array<string, callable> $services
21 */
22 protected array $services = array();
23
24 /**
25 * A list of created instances
26 *
27 * @var array<string, object> $instances
28 */
29 protected array $instances = array();
30
31 /**
32 * Prevents deserialization of this class to avoid callback replacement attacks.
33 *
34 * @param array $data The serialized data.
35 * @return void
36 * @throws \Exception Always throws an exception to prevent deserialization.
37 */
38 public function __unserialize( array $data ): void {
39 throw new \Exception( 'Deserialization of Container is not allowed for security reasons.' );
40 }
41
42 /**
43 * The method for registering a new service.
44 *
45 * @param string $name The name of the service.
46 * @param callable $callback The callable that will be used to create the service.
47 * @return void
48 * @phpstan-template T of object
49 * @phpstan-param class-string<T> $name
50 */
51 public function set( string $name, callable $callback ): void {
52 $this->services[ $name ] = $callback;
53 }
54
55 /**
56 * Method for getting a registered service.
57 *
58 * @param string $name The name of the service.
59 * @return object The service instance.
60 * @throws \Exception If the service is not found.
61 * @phpstan-template T of object
62 * @phpstan-param class-string<T> $name
63 * @phpstan-return T
64 */
65 public function get( string $name ): object {
66 // Check if the service is already instantiated.
67 if ( isset( $this->instances[ $name ] ) ) {
68 /**
69 * Instance.
70 *
71 * @var T $instance Instance of requested service.
72 */
73 $instance = $this->instances[ $name ];
74 return $instance;
75 }
76
77 // Check if the service is registered.
78 if ( ! isset( $this->services[ $name ] ) ) {
79 throw new \Exception( esc_html( "Service not found: $name" ) );
80 }
81
82 /**
83 * Instance.
84 *
85 * @var T $instance Instance of requested service.
86 */
87 $instance = $this->services[ $name ]( $this );
88 $this->instances[ $name ] = $instance;
89
90 return $instance;
91 }
92 }
93