ToolInfo.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /*
  3. * This file is part of the PHP CS utility.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Symfony\CS;
  11. /**
  12. * Obtain information about using version of tool.
  13. *
  14. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  15. */
  16. class ToolInfo
  17. {
  18. const COMPOSER_INSTALLED_FILE = '/../../composer/installed.json';
  19. const COMPOSER_PACKAGE_NAME = 'fabpot/php-cs-fixer';
  20. public static function getComposerVersion()
  21. {
  22. static $result;
  23. if (!self::isInstalledByComposer()) {
  24. throw new \LogicException('Can not get composer version for tool not installed by composer.');
  25. }
  26. if (null === $result) {
  27. $composerInstalled = json_decode(file_get_contents(self::getScriptDir().self::COMPOSER_INSTALLED_FILE), true);
  28. foreach ($composerInstalled as $package) {
  29. if (self::COMPOSER_PACKAGE_NAME === $package['name']) {
  30. $result = $package['version'].'#'.$package['dist']['reference'];
  31. break;
  32. }
  33. }
  34. }
  35. return $result;
  36. }
  37. private static function getScriptDir()
  38. {
  39. static $result;
  40. if (null === $result) {
  41. $script = $_SERVER['SCRIPT_NAME'];
  42. if (is_link($script)) {
  43. $linkTarget = readlink($script);
  44. // If the link target is relative to the link
  45. if (false === realpath($linkTarget)) {
  46. $linkTarget = dirname($script).'/'.$linkTarget;
  47. }
  48. $script = $linkTarget;
  49. }
  50. $result = dirname($script);
  51. }
  52. return $result;
  53. }
  54. public static function getVersion()
  55. {
  56. if (self::isInstalledByComposer()) {
  57. return Fixer::VERSION.':'.self::getComposerVersion();
  58. }
  59. return Fixer::VERSION;
  60. }
  61. public static function isInstalledAsPhar()
  62. {
  63. static $result;
  64. if (null === $result) {
  65. $result = 'phar://' === substr(__DIR__, 0, 7);
  66. }
  67. return $result;
  68. }
  69. public static function isInstalledByComposer()
  70. {
  71. static $result;
  72. if (null === $result) {
  73. $result = !self::isInstalledAsPhar() && file_exists(self::getScriptDir().self::COMPOSER_INSTALLED_FILE);
  74. }
  75. return $result;
  76. }
  77. }