blob: d5d763a2e49d16db2976ce578a5fec8933da8e7d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
<?php
namespace SMW\Services;
use RuntimeException;
/**
* @private
*
* @license GNU GPL v2+
* @since 3.0
*
* @author mwjames
*/
class ServicesContainer {
/**
* @var callable[]
*/
private $services;
/**
* @since 3.0
*/
public function __construct( array $services = [] ) {
$this->services = $services;
}
/**
* @since 3.0
*
* @param string $key
*
* @return mixed
*/
public function get( $key, ...$args ) {
if ( !isset( $this->services[$key] ) ) {
throw new RuntimeException( "$key is an unknown service!" );
};
$type = null;
$service = $this->services[$key];
if ( !is_callable( $service ) && isset( $service['_type'] ) && isset( $service['_service'] ) ) {
$type = $service['_type'];
$service = $service['_service'];
}
if ( !is_callable( $service ) ) {
throw new RuntimeException( "$key is not a callable service!" );
};
$instance = $service( ...$args );
if ( $type !== null && !is_a( $instance, $type ) ) {
throw new RuntimeException( "Service $key is not of the expected $type type!" );
}
return $instance;
}
/**
* @since 3.0
*
* @param string $key
* @param callable $service
*/
public function add( $key, callable $service ) {
$this->services[$key] = $service;
}
}
|