Passed
Pull Request — master (#662)
by Songda
01:48
created

GetUnipayCerts   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 19
c 1
b 0
f 0
dl 0
loc 50
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getCertId() 0 22 3
A getCerts() 0 14 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Traits;
6
7
use Yansongda\Pay\Contract\ConfigInterface;
8
use Yansongda\Pay\Exception\Exception;
9
use Yansongda\Pay\Exception\InvalidConfigException;
10
use Yansongda\Pay\Pay;
11
12
trait GetUnipayCerts
13
{
14
    /**
15
     * @throws \Yansongda\Pay\Exception\ContainerException
16
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
17
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
18
     */
19
    public function getCertId(string $tenant, array $config): string
20
    {
21
        if (!empty($config['certs']['cert_id'])) {
22
            return $config['certs']['cert_id'];
23
        }
24
25
        $certs = $this->getCerts($config);
26
        $ssl = openssl_x509_parse($certs['cert'] ?? '');
27
28
        if (false === $ssl) {
29
            throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Parse `mch_cert_path` Error');
30
        }
31
32
        $certs['cert_id'] = $ssl['serialNumber'] ?? '';
33
34
        $unipay = array_merge($config, ['certs' => $certs]);
35
36
        Pay::set(ConfigInterface::class, Pay::get(ConfigInterface::class)->merge([
37
            'unipay' => [$tenant => $unipay],
38
        ]));
39
40
        return $certs['cert_id'];
41
    }
42
43
    /**
44
     * @return array ['cert' => 公钥, 'pkey' => 私钥, 'extracerts' => array]
45
     *
46
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
47
     */
48
    protected function getCerts(array $config): array
49
    {
50
        $path = $config['mch_cert_path'] ?? null;
51
        $password = $config['mch_cert_password'] ?? null;
52
53
        if (is_null($path) || is_null($password)) {
54
            throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Missing Unipay Config -- [mch_cert_path] or [mch_cert_password]');
55
        }
56
57
        if (false === openssl_pkcs12_read(file_get_contents($path), $certs, $password)) {
58
            throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Read `mch_cert_path` Error');
59
        }
60
61
        return $certs;
62
    }
63
}
64