Completed
Push — master ( f1c5d8...b7eb80 )
by Gregorio
01:54
created

GatewayFactory::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 1
crap 2
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
            $parameters = config('moneta.gateways.' . $name, []);
50
51
            if (!array_key_exists('test_mode', $parameters)) {
52
                $parameters = config('moneta.test_mode', true);
53
            }
54
        }
55
56 42
        return $parameters;
57
    }
58
59
    /**
60
     * @param string $name
61
     * @return string
62
     */
63 45
    private function gatewayClass($name)
64
    {
65 45
        if (strstr($name, '\\')) {
66 42
            return $name;
67
        }
68
69 3
        return $this->contextNamespace . '\\' . ucfirst($name) . '\\Gateway';
70
    }
71
}