4 * This file is part of composer/semver.
6 * (c) Composer <https://github.com/composer>
8 * For the full copyright and license information, please view
9 * the LICENSE file that was distributed with this source code.
12 namespace Composer\Semver;
14 use Composer\Semver\Constraint\Constraint;
21 /** @var VersionParser */
22 private static $versionParser;
25 * Determine if given version satisfies given constraints.
27 * @param string $version
28 * @param string $constraints
32 public static function satisfies($version, $constraints)
34 if (null === self::$versionParser) {
35 self::$versionParser = new VersionParser();
38 $versionParser = self::$versionParser;
39 $provider = new Constraint('==', $versionParser->normalize($version));
40 $constraints = $versionParser->parseConstraints($constraints);
42 return $constraints->matches($provider);
46 * Return all versions that satisfy given constraints.
48 * @param array $versions
49 * @param string $constraints
53 public static function satisfiedBy(array $versions, $constraints)
55 $versions = array_filter($versions, function ($version) use ($constraints) {
56 return Semver::satisfies($version, $constraints);
59 return array_values($versions);
63 * Sort given array of versions.
65 * @param array $versions
69 public static function sort(array $versions)
71 return self::usort($versions, self::SORT_ASC);
75 * Sort given array of versions in reverse.
77 * @param array $versions
81 public static function rsort(array $versions)
83 return self::usort($versions, self::SORT_DESC);
87 * @param array $versions
88 * @param int $direction
92 private static function usort(array $versions, $direction)
94 if (null === self::$versionParser) {
95 self::$versionParser = new VersionParser();
98 $versionParser = self::$versionParser;
99 $normalized = array();
101 // Normalize outside of usort() scope for minor performance increase.
102 // Creates an array of arrays: [[normalized, key], ...]
103 foreach ($versions as $key => $version) {
104 $normalized[] = array($versionParser->normalize($version), $key);
107 usort($normalized, function (array $left, array $right) use ($direction) {
108 if ($left[0] === $right[0]) {
112 if (Comparator::lessThan($left[0], $right[0])) {
119 // Recreate input array, using the original indexes which are now in sorted order.
121 foreach ($normalized as $item) {
122 $sorted[] = $versions[$item[1]];