GitHubChecker.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * This file is part of Psy Shell.
  4. *
  5. * (c) 2012-2018 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Psy\VersionUpdater;
  11. use Psy\Shell;
  12. class GitHubChecker implements Checker
  13. {
  14. const URL = 'https://api.github.com/repos/bobthecow/psysh/releases/latest';
  15. private $latest;
  16. /**
  17. * @return bool
  18. */
  19. public function isLatest()
  20. {
  21. return \version_compare(Shell::VERSION, $this->getLatest(), '>=');
  22. }
  23. /**
  24. * @return string
  25. */
  26. public function getLatest()
  27. {
  28. if (!isset($this->latest)) {
  29. $this->setLatest($this->getVersionFromTag());
  30. }
  31. return $this->latest;
  32. }
  33. /**
  34. * @param string $version
  35. */
  36. public function setLatest($version)
  37. {
  38. $this->latest = $version;
  39. }
  40. /**
  41. * @return string|null
  42. */
  43. private function getVersionFromTag()
  44. {
  45. $contents = $this->fetchLatestRelease();
  46. if (!$contents || !isset($contents->tag_name)) {
  47. throw new \InvalidArgumentException('Unable to check for updates');
  48. }
  49. $this->setLatest($contents->tag_name);
  50. return $this->getLatest();
  51. }
  52. /**
  53. * Set to public to make testing easier.
  54. *
  55. * @return mixed
  56. */
  57. public function fetchLatestRelease()
  58. {
  59. $context = \stream_context_create([
  60. 'http' => [
  61. 'user_agent' => 'PsySH/' . Shell::VERSION,
  62. 'timeout' => 3,
  63. ],
  64. ]);
  65. \set_error_handler(function () {
  66. // Just ignore all errors with this. The checker will throw an exception
  67. // if it doesn't work :)
  68. });
  69. $result = @\file_get_contents(self::URL, false, $context);
  70. \restore_error_handler();
  71. return \json_decode($result);
  72. }
  73. }