UserAgentParser.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php declare(strict_types=1);
  2. namespace Packagist\WebBundle\Util;
  3. class UserAgentParser
  4. {
  5. /** @var ?string */
  6. private $composerVersion;
  7. /** @var ?string */
  8. private $phpVersion;
  9. /** @var ?string */
  10. private $os;
  11. /** @var ?string */
  12. private $httpVersion;
  13. /** @var ?bool */
  14. private $ci;
  15. public function __construct(?string $userAgent)
  16. {
  17. if ($userAgent && preg_match('#^Composer/(?P<composer>[a-z0-9.+-]+) \((?P<os>\S+).*?; PHP (?P<php>[0-9.]+)[^;]*(?:; (?P<http>streams|curl [0-9.]+)[^;]*)?(?P<ci>; CI)?#i', $userAgent, $matches)) {
  18. if ($matches['composer'] === 'source' || preg_match('{^[a-f0-9]{40}$}', $matches['composer'])) {
  19. $matches['composer'] = 'pre-1.8.5';
  20. }
  21. $this->composerVersion = preg_replace('{\+[a-f0-9]{40}}', '', $matches['composer']);
  22. $this->phpVersion = $matches['php'];
  23. $this->os = preg_replace('{^cygwin_nt-.*}', 'cygwin', strtolower($matches['os']));
  24. $this->httpVersion = $matches['http'] ?? null;
  25. $this->ci = (bool) ($matches['ci'] ?? null);
  26. }
  27. }
  28. public function getComposerVersion(): ?string
  29. {
  30. return $this->composerVersion;
  31. }
  32. public function getPhpVersion(): ?string
  33. {
  34. return $this->phpVersion;
  35. }
  36. public function getOs(): ?string
  37. {
  38. return $this->os;
  39. }
  40. public function getHttpVersion(): ?string
  41. {
  42. return $this->httpVersion;
  43. }
  44. public function getCI(): ?bool
  45. {
  46. return $this->ci;
  47. }
  48. }