Passed
Pull Request — master (#754)
by Songda
02:04
created

ParserPlugin::getParser()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 3
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Plugin;
6
7
use Closure;
8
use Yansongda\Pay\Contract\PackerInterface;
9
use Yansongda\Pay\Contract\ParserInterface;
10
use Yansongda\Pay\Contract\PluginInterface;
11
use Yansongda\Pay\Exception\Exception;
12
use Yansongda\Pay\Exception\InvalidConfigException;
13
use Yansongda\Pay\Pay;
14
use Yansongda\Pay\Rocket;
15
16
class ParserPlugin implements PluginInterface
17
{
18
    /**
19
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
20
     * @throws \Yansongda\Pay\Exception\ContainerException
21
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
22
     */
23
    public function assembly(Rocket $rocket, Closure $next): Rocket
24
    {
25
        /* @var Rocket $rocket */
26
        $rocket = $next($rocket);
27
28
        /* @var \Psr\Http\Message\ResponseInterface $response */
29
        $response = $rocket->getDestination();
30
31
        return $rocket->setDestination(
32
            $this->getParser($rocket)->parse($this->getPacker($rocket), $response)
33
        );
34
    }
35
36
    /**
37
     * @throws \Yansongda\Pay\Exception\ContainerException
38
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
39
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
40
     */
41
    protected function getParser(Rocket $rocket): ParserInterface
42
    {
43
        $packer = Pay::get($rocket->getDirection());
44
45
        $packer = is_string($packer) ? Pay::get($packer) : $packer;
46
47
        if (!($packer instanceof ParserInterface)) {
48
            throw new InvalidConfigException(Exception::INVALID_PARSER);
49
        }
50
51
        return $packer;
52
    }
53
54
    /**
55
     * @throws \Yansongda\Pay\Exception\ContainerException
56
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
57
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
58
     */
59
    protected function getPacker(Rocket $rocket): PackerInterface
60
    {
61
        $packer = Pay::get($rocket->getPacker());
62
63
        $packer = is_string($packer) ? Pay::get($packer) : $packer;
64
65
        if (!($packer instanceof PackerInterface)) {
66
            throw new InvalidConfigException(Exception::INVALID_PACKER);
67
        }
68
69
        return $packer;
70
    }
71
}
72