1+ <?php
2+
3+ namespace Eugenefvdm \Api ;
4+
5+ use Illuminate \Http \Client \PendingRequest ;
6+ use Illuminate \Support \Facades \Http ;
7+
8+ class X
9+ {
10+ private string $ bearerToken ;
11+ private string $ baseUrl = 'https://api.twitter.com/2 ' ;
12+ private ?PendingRequest $ client = null ;
13+
14+ public function __construct (string $ bearerToken )
15+ {
16+ $ this ->bearerToken = $ bearerToken ;
17+ }
18+
19+ /**
20+ * Get the HTTP client instance
21+ */
22+ private function client (): PendingRequest
23+ {
24+ if (! $ this ->client ) {
25+ $ this ->client = Http::baseUrl ($ this ->baseUrl )
26+ ->withHeaders ([
27+ 'Authorization ' => "Bearer {$ this ->bearerToken }" ,
28+ 'Content-Type ' => 'application/json ' ,
29+ ]);
30+ }
31+
32+ return $ this ->client ;
33+ }
34+
35+ /**
36+ * Set a custom HTTP client (used for testing)
37+ */
38+ public function setClient (PendingRequest $ client ): void
39+ {
40+ $ this ->client = $ client ;
41+ }
42+
43+ /**
44+ * Get user ID by username
45+ *
46+ * @param string $username The username to lookup
47+ * @return array User data including id, name, and username
48+ */
49+ public function userId (string $ username ): array
50+ {
51+ $ response = $ this ->client ()->get ("/users/by/username/ {$ username }" );
52+ return $ response ->json ();
53+ }
54+
55+ /**
56+ * Get tweets for a user
57+ *
58+ * @param string $userId The user ID to get tweets for
59+ * @param int $maxResults Maximum number of tweets to retrieve (default: 5)
60+ * @return array Tweets data including tweets and metadata
61+ */
62+ public function tweets (string $ userId , int $ maxResults = 5 ): array
63+ {
64+ $ response = $ this ->client ()->get ("/users/ {$ userId }/tweets " , [
65+ 'max_results ' => $ maxResults ,
66+ ]);
67+ return $ response ->json ();
68+ }
69+
70+ /**
71+ * Get user data and rate limits
72+ *
73+ * @param string $username The username to lookup
74+ * @return array User data and rate limit information
75+ */
76+ public function userWithRateLimits (string $ username ): array
77+ {
78+ $ response = $ this ->client ()->withHeaders ([
79+ 'Accept ' => 'application/json ' ,
80+ ])->get ("/users/by/username/ {$ username }" );
81+
82+ return [
83+ 'data ' => $ response ->json (),
84+ 'rate_limits ' => [
85+ 'limit ' => $ response ->header ('x-rate-limit-limit ' ),
86+ 'remaining ' => $ response ->header ('x-rate-limit-remaining ' ),
87+ 'reset ' => $ response ->header ('x-rate-limit-reset ' ),
88+ ],
89+ ];
90+ }
91+ }
0 commit comments