AbstractProvider.php
2.2 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Lackoxygen\TiktokOpen\Base;
use Lackoxygen\TiktokOpen\Application;
use GuzzleHttp\Client;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
abstract class AbstractProvider implements ServiceProviderInterface
{
/**
* @var string $alias
*/
protected string $alias;
/**
* @var array
*/
private array $preServices = [];
/**
* @var array
*/
protected array $services = [];
/**
* @var Container $application
*/
protected Container $application;
/**
* @param string $alias
*/
public function __construct(string $alias)
{
$this->alias = $alias;
$this->addPreService('guzzleHttp', function (Application $app) {
return new Client(
[
'base_uri' => $app['config']->getUrl(),
'timeout' => $app['config']->getTimeout()
]
);
});
}
/**
* @param Container $pimple
* @return void
*/
public function register(Container $pimple)
{
$this->application = $pimple;
$this->registerServices($this->preServices, function (string $key) {
return $key;
});
$this->registerServices($this->services, function (string $key) {
return $this->alias . '.' . $key;
});
$this->application[$this->alias] = $this;
}
/**
* @return array
*/
protected function getServices(): array
{
return array_merge(
$this->preServices,
$this->services
);
}
protected function addPreService($name, $service)
{
$this->preServices[$name] = $service;
}
/**
* @param $services
* @param \Closure $callback
* @return void
*/
protected function registerServices($services, \Closure $callback)
{
foreach ($services as $key => $value) {
if ($value instanceof \Closure) {
$service = call_user_func($value, $this->application);
} else {
$service = new $value($this->application);
}
$this->application[$callback($key)] = $service;
}
}
}