Skip to content

Commit c52bd8b

Browse files
committed
Add CallbackComparator
1 parent c6c2cbc commit c52bd8b

File tree

3 files changed

+88
-1
lines changed

3 files changed

+88
-1
lines changed

CHANGELOG.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
Changelog
22
=========
33

4+
* 1.0.0-beta (2016-07-17)
5+
6+
* Added `CallbackComparator`
7+
48
* 1.0.0-beta (2016-05-06)
59

6-
* first beta release
10+
* First beta release
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace PhpCommon\Comparison\Comparator;
4+
5+
use PhpCommon\Comparison\Comparator;
6+
7+
/**
8+
* A comparator the uses a callback to compare values.
9+
*
10+
* This comparator is useful when simple, one-off comparators need to be
11+
* created. It can be used to change or extend existing comparators in order to
12+
* achieve new ones that better fit to the underlying needs.
13+
*
14+
* @author Marcos Passos <marcos@marcospassos.com>
15+
*/
16+
class CallbackComparator implements Comparator
17+
{
18+
/**
19+
* @var callable
20+
*/
21+
protected $callback;
22+
23+
/**
24+
* CallbackComparator constructor.
25+
*
26+
* @param callable $callback
27+
*/
28+
public function __construct(callable $callback)
29+
{
30+
$this->callback = $callback;
31+
}
32+
33+
/**
34+
* {@inheritdoc}
35+
*/
36+
public function compare($left, $right)
37+
{
38+
return call_user_func_array($this->callback, [$left, $right]);
39+
}
40+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
/**
4+
* This file is part of the phpcommon/comparison package.
5+
*
6+
* (c) Marcos Passos <marcos@marcospassos.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE file
9+
* that was distributed with this source code.
10+
*/
11+
12+
namespace PhpCommon\Comparison\Tests\Comparator;
13+
14+
use PhpCommon\Comparison\Comparator\CallbackComparator;
15+
use PHPUnit_Framework_TestCase;
16+
17+
/**
18+
* @since 1.0
19+
*
20+
* @author Marcos Passos <marcos@croct.com>
21+
*/
22+
class CallbackComparatorTest extends PHPUnit_Framework_TestCase
23+
{
24+
/**
25+
* @testdox The compare() method delegates calls to the callback function
26+
*/
27+
public function testCompareMethodDelegatesCallsToTheCallbackFunction()
28+
{
29+
$callback = $this->getMockBuilder('stdClass')
30+
->setMethods(['callback'])
31+
->getMock()
32+
;
33+
34+
$callback->expects($this->once())
35+
->method('callback')
36+
->with($this->identicalTo('foo'), $this->identicalTo('bar'))
37+
->willReturn(-1)
38+
;
39+
40+
$comparator = new CallbackComparator([$callback, 'callback']);
41+
$this->assertSame(-1, $comparator->compare('foo', 'bar'));
42+
}
43+
}

0 commit comments

Comments
 (0)