Completed
Push — master ( b7eb80...1b338f )
by Gregorio
03:03
created

GatewayFactory::resolveParameters()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.4042

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 5
cts 9
cp 0.5556
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 6
nop 2
crap 5.4042
1
<?php
2
3
namespace Gregoriohc\Moneta\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
     * @param mixed $context
27
     * @return GatewayInterface
28
     */
29 45
    public function create($name, $parameters = null, $context = null)
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
30
    {
31 45
        $class = $this->gatewayClass($name);
32
33 45
        if (!class_exists($class)) {
34 3
            throw new RuntimeException("Gateway class '$class' does not exists");
35
        }
36
37 42
        $parameters = $this->resolveParameters($name, $parameters);
38
39 42
        return new $class($parameters);
40
    }
41
42 42
    private function resolveParameters($name, $parameters)
43
    {
44 42
        if (!is_array($parameters)) {
45 3
            $parameters = [];
46
        }
47
48 42
        if (function_exists('config')) {
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
        }
56
57 42
        return $parameters;
58
    }
59
60
    /**
61
     * @param string $name
62
     * @return string
63
     */
64 45
    private function gatewayClass($name)
65
    {
66 45
        if (strstr($name, '\\')) {
67 42
            return $name;
68
        }
69
70 3
        return $this->contextNamespace . '\\' . ucfirst($name) . '\\Gateway';
71
    }
72
}