GithubClient.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Console\SelfUpdate;
  13. /**
  14. * @readonly
  15. *
  16. * @internal
  17. */
  18. final class GithubClient implements GithubClientInterface
  19. {
  20. private string $url;
  21. public function __construct(string $url = 'https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/tags')
  22. {
  23. $this->url = $url;
  24. }
  25. public function getTags(): array
  26. {
  27. $result = @file_get_contents(
  28. $this->url,
  29. false,
  30. stream_context_create([
  31. 'http' => [
  32. 'header' => 'User-Agent: PHP-CS-Fixer/PHP-CS-Fixer',
  33. ],
  34. ])
  35. );
  36. if (false === $result) {
  37. throw new \RuntimeException(\sprintf('Failed to load tags at "%s".', $this->url));
  38. }
  39. /**
  40. * @var list<array{
  41. * name: string,
  42. * zipball_url: string,
  43. * tarball_url: string,
  44. * commit: array{sha: string, url: string},
  45. * }>
  46. */
  47. $result = json_decode($result, true);
  48. if (JSON_ERROR_NONE !== json_last_error()) {
  49. throw new \RuntimeException(\sprintf(
  50. 'Failed to read response from "%s" as JSON: %s.',
  51. $this->url,
  52. json_last_error_msg()
  53. ));
  54. }
  55. return array_map(
  56. static fn (array $tagData): string => $tagData['name'],
  57. $result
  58. );
  59. }
  60. }