Skip to content

Commit 6438520

Browse files
committed
Sort example
1 parent d470983 commit 6438520

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,39 @@ echo $version->isEqual(Version::parse("2.5.6-alpha.12+build.56")); // true
9797
echo $version->isNotEqual(Version::parse("2.2.4")); // true
9898
```
9999

100+
### Sort
101+
102+
`Version::compare()` and `Version::compareString()` methods can be used to sort an array of versions. (as callback for `usort()`)
103+
```php
104+
<?php
105+
106+
use z4kn4fein\SemVer\Version;
107+
108+
$versions = array_map(function(string $version) {
109+
return Version::parse($version);
110+
}, [
111+
"1.0.1",
112+
"1.0.1-alpha",
113+
"1.0.1-alpha.beta",
114+
"1.0.1-alpha.3",
115+
"1.0.1-alpha.2",
116+
"1.1.0",
117+
"1.1.0+build",
118+
]);
119+
120+
usort($versions, ["z4kn4fein\SemVer\Version", "compare"]);
121+
122+
// The result:
123+
// "1.0.1-alpha"
124+
// "1.0.1-alpha.2"
125+
// "1.0.1-alpha.3"
126+
// "1.0.1-alpha.beta"
127+
// "1.0.1"
128+
// "1.1.0"
129+
// "1.1.0+build"
130+
```
131+
132+
100133
## Constraints
101134
With constraints, it's possible to validate whether a version satisfies a set of rules or not.
102135
A constraint can be described as one or more conditions combined with logical `OR` and `AND` operators.

tests/CompareTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,4 +128,29 @@ public function testCompareStringsWithCompare()
128128
$this->assertEquals(1, Version::compareString('5.2.3-alpha.6+build.34','5.2.3-alpha.5'));
129129
$this->assertEquals(0, Version::compareString('5.2.3','5.2.3'));
130130
}
131+
132+
public function testSort()
133+
{
134+
$versions = array_map(function(string $version) {
135+
return Version::parse($version);
136+
}, [
137+
"1.0.1",
138+
"1.0.1-alpha",
139+
"1.0.1-alpha.beta",
140+
"1.0.1-alpha.3",
141+
"1.0.1-alpha.2",
142+
"1.1.0",
143+
"1.1.0+build",
144+
]);
145+
146+
usort($versions, ["z4kn4fein\SemVer\Version", "compare"]);
147+
148+
$this->assertEquals("1.0.1-alpha", (string)$versions[0]);
149+
$this->assertEquals("1.0.1-alpha.2", (string)$versions[1]);
150+
$this->assertEquals("1.0.1-alpha.3", (string)$versions[2]);
151+
$this->assertEquals("1.0.1-alpha.beta", (string)$versions[3]);
152+
$this->assertEquals("1.0.1", (string)$versions[4]);
153+
$this->assertEquals("1.1.0", (string)$versions[5]);
154+
$this->assertEquals("1.1.0+build", (string)$versions[6]);
155+
}
131156
}

0 commit comments

Comments
 (0)