1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gregoriohc\Protean\Common; |
4
|
|
|
|
5
|
|
|
use RuntimeException; |
6
|
|
|
|
7
|
|
|
class GatewayFactory |
8
|
|
|
{ |
9
|
|
|
protected $contextNamespace; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* GatewayFactory constructor. |
13
|
|
|
* @param string|null $contextNamespace |
14
|
|
|
*/ |
15
|
3 |
|
public function __construct($contextNamespace = null) |
16
|
|
|
{ |
17
|
3 |
|
$this->contextNamespace = $contextNamespace ?: substr(get_class($this), 0, -strlen('\\Common\\GatewayFactory')); |
18
|
3 |
|
} |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Create a new gateway instance |
23
|
|
|
* |
24
|
|
|
* @param string $name |
25
|
|
|
* @param array $parameters |
26
|
|
|
* @return GatewayInterface |
27
|
|
|
*/ |
28
|
42 |
|
public function create($name, $parameters = null) |
29
|
|
|
{ |
30
|
42 |
|
$class = $this->gatewayClass($name); |
31
|
|
|
|
32
|
42 |
|
if (!class_exists($class)) { |
33
|
3 |
|
throw new RuntimeException("Gateway class '$class' does not exists"); |
34
|
|
|
} |
35
|
|
|
|
36
|
39 |
|
$parameters = $this->resolveParameters($name, $parameters); |
37
|
|
|
|
38
|
39 |
|
return new $class($parameters); |
39
|
|
|
} |
40
|
|
|
|
41
|
39 |
|
private function resolveParameters($name, $parameters) |
42
|
|
|
{ |
43
|
39 |
|
if (!is_array($parameters)) { |
44
|
3 |
|
$parameters = []; |
45
|
|
|
} |
46
|
|
|
|
47
|
39 |
|
if (function_exists('config')) { |
48
|
|
|
// @codeCoverageIgnoreStart |
49
|
|
|
$configBasePath = snake_case(class_basename($this->contextNamespace)); |
50
|
|
|
$parameters = config($configBasePath . '.gateways.' . $name, []); |
51
|
|
|
|
52
|
|
|
if (!array_key_exists('test_mode', $parameters)) { |
53
|
|
|
$parameters = config($configBasePath . '.test_mode', true); |
54
|
|
|
} |
55
|
|
|
// @codeCoverageIgnoreEnd |
56
|
|
|
} |
57
|
|
|
|
58
|
39 |
|
return $parameters; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param string $name |
63
|
|
|
* @return string |
64
|
|
|
*/ |
65
|
42 |
|
private function gatewayClass($name) |
66
|
|
|
{ |
67
|
42 |
|
if (strstr($name, '\\')) { |
68
|
39 |
|
return $name; |
69
|
|
|
} |
70
|
|
|
|
71
|
3 |
|
return $this->contextNamespace . '\\' . ucfirst($name) . '\\Gateway'; |
72
|
|
|
} |
73
|
|
|
} |