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 |
||
14 | class OpenAuth extends Core |
||
15 | { |
||
16 | const API_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize'; |
||
17 | const CODE_GET_USER = 'https://api.weixin.qq.com/sns/oauth2/component/access_token'; |
||
18 | const API_USER_INFO = 'https://api.weixin.qq.com/sns/userinfo'; |
||
19 | |||
20 | protected $authorizedUser; |
||
21 | private $authorized_app_id; |
||
22 | |||
23 | /** |
||
24 | * AuthApi constructor. |
||
25 | * |
||
26 | * @param $authorized_app_id |
||
27 | */ |
||
28 | public function __construct($authorized_app_id) |
||
34 | |||
35 | /** |
||
36 | * 获取当前URL |
||
37 | * |
||
38 | * @return string |
||
39 | */ |
||
40 | View Code Duplication | public static function current() |
|
54 | |||
55 | /** |
||
56 | * 生成outh URL |
||
57 | * |
||
58 | * @param string $to |
||
59 | * @param string $scope |
||
60 | * @param string $state |
||
61 | * |
||
62 | * @return string |
||
63 | */ |
||
64 | public function url($to = null, $scope = 'snsapi_userinfo', $state = 'STATE') |
||
79 | |||
80 | /** |
||
81 | * 直接跳转 |
||
82 | * |
||
83 | * @param string $to |
||
84 | * @param string $scope |
||
85 | * @param string $state |
||
86 | */ |
||
87 | public function redirect($to = null, $scope = 'snsapi_userinfo', $state = 'STATE') |
||
93 | |||
94 | /** |
||
95 | * 获取已授权用户 |
||
96 | * |
||
97 | * @return array $user |
||
98 | */ |
||
99 | public function user() |
||
109 | |||
110 | /** |
||
111 | * 通过授权获取用户 |
||
112 | * |
||
113 | * @param null $to |
||
114 | * @param string $scope |
||
115 | * @param string $state |
||
116 | * |
||
117 | * @return array |
||
118 | */ |
||
119 | public function authorize($to = null, $scope = 'snsapi_userinfo', $state = 'STATE') |
||
127 | |||
128 | /** |
||
129 | * 获取用户信息 |
||
130 | * |
||
131 | * @param string $code |
||
132 | * |
||
133 | * @return array |
||
134 | */ |
||
135 | public function getUser($code) |
||
152 | |||
153 | /** |
||
154 | * 获取大授权 用户信息 |
||
155 | * |
||
156 | * @param $access_token |
||
157 | * @param $openid |
||
158 | * @param string $lang |
||
159 | * |
||
160 | * @return array |
||
161 | */ |
||
162 | public function getUserInfo($access_token, $openid, $lang = 'zh_CN') |
||
176 | } |
||
177 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: