Skip to content

Commit 5dc983f

Browse files
committed
Allow Sortable objects to be compared by custom method
Sometimes it is necessary to customize the way objects should be compared. This will help to fix issues such as deep nesting reference when we compare objects that link to themselves. This commit fixes #1726
1 parent a86a943 commit 5dc983f

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

lib/Gedmo/Sortable/Comparable.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Gedmo\Sortable;
4+
5+
/**
6+
* This interface is not necessary but can be implemented for
7+
* Entities which has custom compare methods
8+
* Comparable
9+
*
10+
* @link https://wiki.php.net/rfc/comparable
11+
* @author Raine Ng <[email protected]>
12+
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
13+
*/
14+
interface Comparable
15+
{
16+
public function compareTo($other);
17+
}

lib/Gedmo/Sortable/SortableListener.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,13 @@ public function postFlush(EventArgs $args)
461461
$matches = $gr === null;
462462
} elseif (is_object($gr) && is_object($value) && $gr !== $value) {
463463
// Special case for equal objects but different instances.
464-
$matches = $gr == $value;
464+
// If the object implements Comparable interface we can use its compareTo method
465+
// Otherwise we fallback to normal object comparison
466+
if ($gr instanceof Comparable) {
467+
$matches = $gr->compareTo($value);
468+
} else {
469+
$matches = $gr == $value;
470+
}
465471
} else {
466472
$matches = $gr === $value;
467473
}

0 commit comments

Comments
 (0)