forked from Abbotton/alipay-sdk-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AlipayRequestFactory.php
103 lines (88 loc) · 2.54 KB
/
AlipayRequestFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace Alipay;
use Alipay\Exception\AlipayInvalidPropertyException;
use Alipay\Exception\AlipayInvalidRequestException;
use Alipay\Request\AbstractAlipayRequest;
class AlipayRequestFactory
{
public $namespace = '';
/**
* 创建请求类工厂
*
* @param string $namespace
*/
public function __construct($namespace = 'Alipay\Request\\')
{
$this->namespace = $namespace;
}
/**
* 通过 `API 名称` 创建请求类实例
*
* @param string $apiName
* @param array $config
*
* @return AbstractAlipayRequest
*/
public function createByApi($apiName, $config = [])
{
$className = AlipayHelper::studlyCase($apiName, '.') . 'Request';
return $this->createByClass($className, $config);
}
/**
* 通过 `请求类名` 创建请求类实例
*
* @param string $className
* @param array $config
*
* @return AbstractAlipayRequest
*/
public function createByClass($className, $config = [])
{
$className = $this->namespace . $className;
$this->validate($className);
$instance = new $className();
foreach ($config as $key => $value) {
$property = AlipayHelper::studlyCase($key, '_');
try {
$instance->$property = $value;
} catch (AlipayInvalidPropertyException $ex) {
throw new AlipayInvalidRequestException($ex->getMessage() . ': ' . $key);
}
}
return $instance;
}
/**
* 验证某类可否被创建
*
* @param string $className
*
* @return void
*/
protected function validate($className)
{
if (!class_exists($className)) {
throw new AlipayInvalidRequestException("Class {$className} doesn't exist");
}
$abstractClass = AbstractAlipayRequest::className();
if (!is_subclass_of($className, $abstractClass)) {
throw new AlipayInvalidRequestException("Class {$className} doesn't extend {$abstractClass}");
}
}
/**
* 创建请求类实例
*
* @param string $classOrApi
* @param array $config
*
* @return AbstractAlipayRequest
*/
public static function create($classOrApi, $config = [])
{
$factory = isset($this) ? $this : new self();
if (strpos($classOrApi, '.')) {
return $factory->createByApi($classOrApi, $config);
} else {
return $factory->createByClass($classOrApi, $config);
}
}
}