Platform.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. /**
  13. * Platform helper for uniform platform-specific tests.
  14. *
  15. * @author Niels Keurentjes <niels.keurentjes@omines.com>
  16. */
  17. class Platform
  18. {
  19. /**
  20. * Parses tildes and environment variables in paths.
  21. *
  22. * @param string $path
  23. * @return string
  24. */
  25. public static function expandPath($path)
  26. {
  27. if (preg_match('#^~[\\/]#', $path)) {
  28. return self::getUserDirectory() . substr($path, 1);
  29. }
  30. return preg_replace_callback('#^(\$|(?P<percent>%))(?P<var>\w++)(?(percent)%)(?P<path>.*)#', function ($matches) {
  31. // Treat HOME as an alias for USERPROFILE on Windows for legacy reasons
  32. if (Platform::isWindows() && $matches['var'] == 'HOME') {
  33. return (getenv('HOME') ?: getenv('USERPROFILE')) . $matches['path'];
  34. }
  35. return getenv($matches['var']) . $matches['path'];
  36. }, $path);
  37. }
  38. /**
  39. * @throws \RuntimeException If the user home could not reliably be determined
  40. * @return string The formal user home as detected from environment parameters
  41. */
  42. public static function getUserDirectory()
  43. {
  44. if (false !== ($home = getenv('HOME'))) {
  45. return $home;
  46. }
  47. if (self::isWindows() && false !== ($home = getenv('USERPROFILE'))) {
  48. return $home;
  49. }
  50. if (function_exists('posix_getuid') && function_exists('posix_getpwuid')) {
  51. $info = posix_getpwuid(posix_getuid());
  52. return $info['dir'];
  53. }
  54. throw new \RuntimeException('Could not determine user directory');
  55. }
  56. /**
  57. * @return bool Whether the host machine is running a Windows OS
  58. */
  59. public static function isWindows()
  60. {
  61. return defined('PHP_WINDOWS_VERSION_BUILD');
  62. }
  63. /**
  64. * @param string $str
  65. * @return int return a guaranteed binary length of the string, regardless of silly mbstring configs
  66. */
  67. public static function strlen($str)
  68. {
  69. static $useMbString = null;
  70. if (null === $useMbString) {
  71. $useMbString = function_exists('mb_strlen') && ini_get('mbstring.func_overload');
  72. }
  73. if ($useMbString) {
  74. return mb_strlen($str, '8bit');
  75. }
  76. return strlen($str);
  77. }
  78. }