Completed
Pull Request — master (#24)
by Rafał
03:08
created

AdapterFactory::initializeGateway()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 19
rs 9.4285
cc 2
eloc 11
nc 2
nop 2
1
<?php
2
3
/**
4
 * @author Rafał Muszyński <[email protected]>
5
 * @copyright 2015 Sourcefabric z.ú.
6
 * @license http://www.gnu.org/licenses/gpl-3.0.txt
7
 */
8
namespace Newscoop\PaywallBundle\Adapter;
9
10
use Symfony\Component\Routing\RouterInterface;
11
use Newscoop\PaywallBundle\Services\PaymentMethodInterface;
12
use Newscoop\PaywallBundle\Provider\MethodProviderInterface;
13
use Omnipay\Omnipay;
14
15
/**
16
 * Adapter Factory.
17
 */
18
class AdapterFactory
19
{
20
    const OFFLINE = 'offline';
21
22
    /**
23
     * Get current adapter.
24
     *
25
     * @param MethodProviderInterface $paymentMethodProvider
26
     * @param RouterInterface         $router
27
     * @param array                   $config
28
     * @param PaymentMethodInterface  $paymentMethodContext
29
     *
30
     * @return Omnipay
31
     */
32
    public function getAdapter(
33
        MethodProviderInterface $paymentMethodProvider,
34
        RouterInterface $router,
35
        PaymentMethodInterface $paymentMethodContext,
36
        array $config
37
    ) {
38
        $gateway = null;
39
        $enabledAdapter = $paymentMethodProvider->getActiveMethod();
40
41
        $gatewayName = $enabledAdapter->getValue();
42
        if ($paymentMethodContext->getMethod() === static::OFFLINE) {
43
            $gatewayName = $paymentMethodContext->getMethod();
44
        }
45
46
        $paymentMethodContext->setMethod($gatewayName);
47
        if ($paymentMethodContext->getMethod() !== static::OFFLINE) {
48
            $gateway = $this->initializeGateway($config, $paymentMethodContext->getMethod());
49
        }
50
51
        return new GatewayAdapter($router, $gateway);
52
    }
53
54
    private function initializeGateway(array $config, $name)
55
    {
56
        if (!isset($config['gateways'][$name])) {
57
            throw new \InvalidArgumentException(
58
                '"'.$name.'" gateway is not configured! Make sure it is '.
59
                'installed via Composer and that you added it to custom_parameters.yml'
60
            );
61
        }
62
63
        $gateway = Omnipay::create($name);
64
        $gateway->initialize(array_merge(
65
            $config['gateways'][$name],
66
            array(
67
                'brandName' => $config['brandName'],
68
            )
69
        ));
70
71
        return $gateway;
72
    }
73
}
74