TestCase.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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;
  12. use Composer\Semver\VersionParser;
  13. use Composer\Package\AliasPackage;
  14. use Composer\Semver\Constraint\Constraint;
  15. use Composer\Util\Filesystem;
  16. use Composer\Util\Silencer;
  17. abstract class TestCase extends \PHPUnit_Framework_TestCase
  18. {
  19. private static $parser;
  20. protected static function getVersionParser()
  21. {
  22. if (!self::$parser) {
  23. self::$parser = new VersionParser();
  24. }
  25. return self::$parser;
  26. }
  27. protected function getVersionConstraint($operator, $version)
  28. {
  29. $constraint = new Constraint(
  30. $operator,
  31. self::getVersionParser()->normalize($version)
  32. );
  33. $constraint->setPrettyString($operator.' '.$version);
  34. return $constraint;
  35. }
  36. protected function getPackage($name, $version, $class = 'Composer\Package\Package')
  37. {
  38. $normVersion = self::getVersionParser()->normalize($version);
  39. return new $class($name, $normVersion, $version);
  40. }
  41. protected function getAliasPackage($package, $version)
  42. {
  43. $normVersion = self::getVersionParser()->normalize($version);
  44. return new AliasPackage($package, $normVersion, $version);
  45. }
  46. protected static function getUniqueTmpDirectory()
  47. {
  48. $attempts = 5;
  49. $root = sys_get_temp_dir();
  50. do {
  51. $unique = $root . DIRECTORY_SEPARATOR . uniqid('composer-test-' . rand(1000, 9000));
  52. if (!file_exists($unique) && Silencer::call('mkdir', $unique, 0777)) {
  53. return realpath($unique);
  54. }
  55. } while (--$attempts);
  56. throw new \RuntimeException('Failed to create a unique temporary directory.');
  57. }
  58. protected static function ensureDirectoryExistsAndClear($directory)
  59. {
  60. $fs = new Filesystem();
  61. if (is_dir($directory)) {
  62. $fs->removeDirectory($directory);
  63. }
  64. mkdir($directory, 0777, true);
  65. }
  66. }