1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace FondBot\Drivers; |
6
|
|
|
|
7
|
|
|
use FondBot\Helpers\Arr; |
8
|
|
|
use FondBot\Channels\Channel; |
9
|
|
|
use Psr\Container\ContainerInterface; |
10
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
11
|
|
|
use FondBot\Drivers\Exceptions\DriverNotFound; |
12
|
|
|
use FondBot\Drivers\Exceptions\InvalidConfiguration; |
13
|
|
|
|
14
|
|
|
class DriverManager |
15
|
|
|
{ |
16
|
|
|
protected $container; |
17
|
|
|
|
18
|
|
|
/** @var Driver[] */ |
19
|
|
|
protected $drivers = []; |
20
|
|
|
|
21
|
|
|
/** @var array */ |
22
|
|
|
protected $parameters = []; |
23
|
|
|
|
24
|
4 |
|
public function __construct(ContainerInterface $container) |
25
|
|
|
{ |
26
|
4 |
|
$this->container = $container; |
27
|
4 |
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Add driver. |
31
|
|
|
* |
32
|
|
|
* @param Driver $driver |
33
|
|
|
* @param string $name |
34
|
|
|
* @param array $parameters |
35
|
|
|
*/ |
36
|
3 |
|
public function add(Driver $driver, string $name, array $parameters): void |
37
|
|
|
{ |
38
|
3 |
|
$this->drivers[$name] = $driver; |
39
|
3 |
|
$this->parameters[$name] = $parameters; |
40
|
3 |
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Get driver for channel. |
44
|
|
|
* |
45
|
|
|
* @param Channel $channel |
46
|
|
|
* |
47
|
|
|
* @param ServerRequestInterface $request |
48
|
|
|
* |
49
|
|
|
* @return Driver |
50
|
|
|
* @throws DriverNotFound |
51
|
|
|
*/ |
52
|
3 |
|
public function get(Channel $channel, ServerRequestInterface $request): Driver |
53
|
|
|
{ |
54
|
3 |
|
$driver = Arr::get($this->drivers, $channel->getDriver()); |
55
|
|
|
|
56
|
3 |
|
if ($driver === null || !$driver instanceof Driver) { |
57
|
1 |
|
throw new DriverNotFound('Driver `'.$channel->getDriver().'` not found.'); |
58
|
|
|
} |
59
|
|
|
|
60
|
2 |
|
$this->validateParameters($channel); |
61
|
|
|
|
62
|
1 |
|
$driver->fill($channel->getParameters(), $request); |
63
|
|
|
|
64
|
1 |
|
return $driver; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Get all added drivers. |
69
|
|
|
* |
70
|
|
|
* @return array |
71
|
|
|
*/ |
72
|
1 |
|
public function all(): array |
73
|
|
|
{ |
74
|
1 |
|
return $this->drivers; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Validate channel parameters with driver requirements. |
79
|
|
|
* |
80
|
|
|
* @param Channel $channel |
81
|
|
|
*/ |
82
|
2 |
|
protected function validateParameters(Channel $channel): void |
83
|
|
|
{ |
84
|
2 |
|
$parameters = Arr::get($this->parameters, $channel->getDriver(), []); |
85
|
|
|
|
86
|
2 |
|
collect($parameters) |
87
|
2 |
|
->each(function (string $parameter) use ($channel) { |
88
|
2 |
|
if ($channel->getParameter($parameter) === null) { |
89
|
1 |
|
throw new InvalidConfiguration('Invalid `'.$channel->getName().'` channel configuration.'); |
90
|
|
|
} |
91
|
2 |
|
}); |
92
|
1 |
|
} |
93
|
|
|
} |
94
|
|
|
|