Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to set custom comparator #23

Merged
merged 2 commits into from
Aug 4, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@

class Version implements JsonSerializable
{
/** @var ComparatorInterface */
private static $comparator;
nikolaposa marked this conversation as resolved.
Show resolved Hide resolved

/** @var int */
protected $major;

Expand All @@ -32,6 +35,11 @@ class Version implements JsonSerializable
/** @var Build */
protected $build;

public static function setComparator(?ComparatorInterface $comparator) : void
nikolaposa marked this conversation as resolved.
Show resolved Hide resolved
{
self::$comparator = $comparator;
}

protected function __construct(int $major, int $minor, int $patch, PreRelease $preRelease, Build $build)
{
$this->validateNumber('major', $major);
Expand Down Expand Up @@ -292,12 +300,10 @@ public function toArray() : array

protected function getComparator() : ComparatorInterface
{
static $comparator = null;

if (null === $comparator) {
$comparator = new SemverComparator();
if (null === self::$comparator) {
self::$comparator = new SemverComparator();
}

return $comparator;
return self::$comparator;
}
}
22 changes: 22 additions & 0 deletions tests/VersionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Version\Tests;

use PHPUnit\Framework\TestCase;
use Version\Comparator\ComparatorInterface;
use Version\Exception\InvalidVersionException;
use Version\Exception\InvalidVersionStringException;
use Version\Extension\Build;
Expand Down Expand Up @@ -221,4 +222,25 @@ public function getInvalidVersionStrings() : array
'leadingZeroIsInvalid' => ['1.05.2'],
];
}

/**
* @test
*/
public function it_can_set_custom_comparator() : void
nikolaposa marked this conversation as resolved.
Show resolved Hide resolved
{
Version::setComparator(new class implements ComparatorInterface {
public function compare(Version $version1, Version $version2) : int
{
return 1;
}
});

try {
$version = Version::fromParts(1);
$this->assertSame(1, $version->compareTo($version));
} finally {
// reset comparator
Version::setComparator(null);
}
}
}