Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
16 | class Core |
||
17 | { |
||
18 | /** @var object */ |
||
19 | public $configs; |
||
20 | protected static $error; |
||
21 | /** @var BaseDriver */ |
||
22 | protected static $cacheDriver; |
||
23 | /** @var DatabaseBaseDriver */ |
||
24 | protected static $databaseDriver; |
||
25 | |||
26 | const GET_COMPONENT_ACCESS_TOKEN = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'; //获取第三方token |
||
27 | const GET_COMPONENT_PRE_AUTH_CODE = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode'; //获取第三方auth_code |
||
28 | |||
29 | /** |
||
30 | * 初始化 缓存 数据库 配置 |
||
31 | * |
||
32 | * @param \OpenOauth\Core\CacheDriver\BaseDriver|null $cacheDriver |
||
33 | * @param \OpenOauth\Core\DatabaseDriver\BaseDriver|null $databaseDriver |
||
34 | */ |
||
35 | public static function init(CacheBaseDriver $cacheDriver = null, DatabaseBaseDriver $databaseDriver = null) |
||
45 | |||
46 | /** |
||
47 | * Core constructor. |
||
48 | * |
||
49 | */ |
||
50 | public function __construct() |
||
82 | |||
83 | /** |
||
84 | * 获取开放平台 ComponentAccessToken |
||
85 | * |
||
86 | * @return bool|mixed |
||
87 | */ |
||
88 | public function getComponentAccessToken() |
||
89 | { |
||
90 | $component_access_token = self::$cacheDriver->_get('component_access_token:' . $this->configs->component_app_id); |
||
91 | |||
92 | if (false == $component_access_token) { |
||
93 | |||
94 | $request_data = [ |
||
95 | 'component_appid' => $this->configs->component_app_id, |
||
96 | 'component_appsecret' => $this->configs->component_app_secret, |
||
97 | 'component_verify_ticket' => self::$cacheDriver->_get('component_verify_ticket:' . $this->configs->component_app_id), |
||
98 | ]; |
||
99 | |||
100 | $response_data = Http::_post(self::GET_COMPONENT_ACCESS_TOKEN, $request_data); |
||
101 | |||
102 | View Code Duplication | if (!$response_data || !is_array($response_data) || empty($response_data)) { |
|
103 | $this->setError(Http::$error); |
||
104 | |||
105 | return false; |
||
106 | } |
||
107 | |||
108 | self::$cacheDriver->_set('component_access_token:' . $this->configs->component_app_id, $response_data['component_access_token'], 5000); |
||
109 | |||
110 | $component_access_token = $response_data['component_access_token']; |
||
111 | } |
||
112 | |||
113 | return $component_access_token; |
||
114 | } |
||
115 | |||
116 | /** |
||
117 | * 获取第三方auth_code |
||
118 | * |
||
119 | * @return bool|null|string|void |
||
120 | */ |
||
121 | public function getComponentPreAuthCode() |
||
147 | |||
148 | /** |
||
149 | * @return mixed |
||
150 | */ |
||
151 | public static function getError() |
||
155 | |||
156 | /** |
||
157 | * @param string $error |
||
158 | */ |
||
159 | public static function setError($error = '') |
||
163 | } |
||
164 |