44
55use WP_Error ;
66use WP \OAuth2 \Client ;
7- use WP_Query ;
87use WP_User ;
8+ use WP_User_Query ;
99
1010class Access_Token extends Token {
1111 const META_PREFIX = '_oauth2_access_ ' ;
@@ -19,21 +19,12 @@ protected function get_meta_prefix() {
1919 }
2020
2121 /**
22- * Get the ID for the user that the token represents .
22+ * Get client for the token.
2323 *
24- * @return int
24+ * @return Client|null
2525 */
26- public function get_user_id () {
27- return (int ) $ this ->value ['user ' ];
28- }
29-
30- /**
31- * Get the user that the token represents.
32- *
33- * @return WP_User|null
34- */
35- public function get_user () {
36- return get_user_by ( 'id ' , $ this ->get_user_id () );
26+ public function get_client () {
27+ return Client::get_by_id ( $ this ->value ['client ' ] );
3728 }
3829
3930 /**
@@ -45,28 +36,28 @@ public function get_user() {
4536 public static function get_by_id ( $ id ) {
4637 $ key = static ::META_PREFIX . $ id ;
4738 $ args = array (
48- 'post_type ' => Client::POST_TYPE ,
49- 'post_status ' => 'publish ' ,
50- 'posts_per_page ' => 1 ,
51- 'no_found_rows ' => true ,
52- 'meta_query ' => array (
39+ 'number ' => 1 ,
40+ 'count_total ' => false ,
41+ 'meta_query ' => array (
5342 array (
5443 'key ' => $ key ,
5544 'compare ' => 'EXISTS ' ,
5645 ),
5746 ),
5847 );
59- $ query = new WP_Query ( $ args );
60- if ( empty ( $ query ->posts ) ) {
48+ $ query = new WP_User_Query ( $ args );
49+ $ results = $ query ->get_results ();
50+ if ( empty ( $ results ) ) {
6151 return null ;
6252 }
6353
64- $ value = get_post_meta ( $ query ->posts [0 ]->ID , wp_slash ( $ key ), false );
54+ $ user = $ results [0 ];
55+ $ value = get_user_meta ( $ user ->ID , wp_slash ( $ key ), false );
6556 if ( empty ( $ value ) ) {
6657 return null ;
6758 }
6859
69- return new static ( $ key , $ value [0 ] );
60+ return new static ( $ user , $ key , $ value [0 ] );
7061 }
7162
7263 /**
@@ -86,20 +77,20 @@ public static function create( Client $client, WP_User $user ) {
8677 }
8778
8879 $ data = array (
89- 'user ' => ( int ) $ user -> ID ,
80+ 'client ' => $ client -> get_id () ,
9081 );
9182 $ key = wp_generate_password ( static ::KEY_LENGTH , false );
9283 $ meta_key = static ::META_PREFIX . $ key ;
9384
94- $ result = add_post_meta ( $ client -> get_post_id () , wp_slash ( $ meta_key ), wp_slash ( $ data ), true );
85+ $ result = add_user_meta ( $ user -> ID , wp_slash ( $ meta_key ), wp_slash ( $ data ), true );
9586 if ( ! $ result ) {
9687 return new WP_Error (
9788 'oauth2.tokens.access_token.create.could_not_create ' ,
9889 __ ( 'Unable to create token. ' , 'oauth2 ' )
9990 );
10091 }
10192
102- return new static ( $ key , $ data );
93+ return new static ( $ user , $ key , $ data );
10394 }
10495
10596 /**
0 commit comments