1010use CDash \Model \Project ;
1111use CDash \ServiceContainer ;
1212use Illuminate \Support \Facades \Log ;
13+ use Illuminate \Support \Str ;
14+ use Illuminate \Support \Uri ;
1315use PDO ;
1416
1517class RepositoryUtils
@@ -27,7 +29,7 @@ public static function isGitHubUrl(string $url): bool
2729 }
2830 $ enterpriseUrl = self ::getEnterpriseUrl ();
2931 if ($ enterpriseUrl !== null ) {
30- $ host = parse_url ($ enterpriseUrl, PHP_URL_HOST );
32+ $ host = Uri:: of ($ enterpriseUrl)-> host ( );
3133 return is_string ($ host ) && str_contains ($ url , $ host );
3234 }
3335 return false ;
@@ -162,36 +164,22 @@ public static function post_pull_request_comment($projectid, $pull_request, $com
162164 }
163165 }
164166
165- /** Convert GitHub repository viewer URL into corresponding API URL. */
166- public static function get_github_api_url ($ github_url ): string
167+ /**
168+ * Convert a GitHub repository viewer URL (e.g. https://<host>/<user>/<repo>)
169+ * into the corresponding REST API URL.
170+ */
171+ public static function get_github_api_url (string $ github_url ): string
167172 {
168173 $ enterpriseUrl = self ::getEnterpriseUrl ();
169- if ($ enterpriseUrl !== null ) {
170- $ host = parse_url ($ enterpriseUrl , PHP_URL_HOST );
171- if (is_string ($ host )) {
172- $ idx = strpos ($ github_url , $ host );
173- if ($ idx !== false ) {
174- // For GHE, ...://<host>/<user>/<repo> becomes ...://<host>/api/v3/repos/<user>/<repo>
175- $ idx2 = $ idx + strlen ($ host ) + 1 ;
176- $ api_url = substr ($ github_url , 0 , $ idx ) . $ host . '/api/v3/repos/ ' ;
177- $ api_url .= substr ($ github_url , $ idx2 );
178- return $ api_url ;
179- }
180- }
174+ $ host = $ enterpriseUrl !== null ? Uri::of ($ enterpriseUrl )->host () : null ;
175+
176+ if (is_string ($ host ) && str_contains ($ github_url , $ host )) {
177+ // GHE uses <host>/api/v3/repos/ as the API base
178+ return Str::replaceFirst ($ host . '/ ' , $ host . '/api/v3/repos/ ' , $ github_url );
179+ } else {
180+ // GitHub.com uses api.github.com/repos/ as the API base
181+ return Str::replaceFirst ('github.com/ ' , 'api.github.com/repos/ ' , $ github_url );
181182 }
182- /*
183- * For a URL of the form:
184- * ...://github.com/<user>/<repo>
185- * We return:
186- * ...://api.github.com/repos/<user>/<repo>
187- */
188- $ idx1 = strpos ($ github_url , 'github.com ' );
189- $ idx2 = $ idx1 + strlen ('github.com/ ' );
190- $ api_url = substr ($ github_url , 0 , $ idx2 );
191- $ api_url = str_replace ('github.com ' , 'api.github.com ' , $ api_url );
192- $ api_url .= 'repos/ ' ;
193- $ api_url .= substr ($ github_url , $ idx2 );
194- return $ api_url ;
195183 }
196184
197185 public static function post_github_pull_request_comment (Project $ project , $ pull_request , $ comment , $ cdash_url ): void
0 commit comments