Skip to content

Commit 4aefab8

Browse files
authored
Merge pull request #1727 from Nilead/v2.4.x
Allow Sortable objects to be compared by custom method
2 parents a86a943 + 19311c5 commit 4aefab8

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

doc/sortable.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Content:
3030
- [Yaml](#yaml-mapping) mapping example
3131
- [Xml](#xml-mapping) mapping example
3232
- Basic usage [examples](#basic-examples)
33+
- Custom comparison method (#custom-comparisons)
3334

3435

3536
<a name="including-extension"></a>
@@ -295,3 +296,33 @@ To move an item at the end of the list, you can set the position to `-1`:
295296
```
296297
$item2->setPosition(-1);
297298
```
299+
300+
<a name="custom-comparisons"></a>
301+
302+
## Custom comparison:
303+
304+
Sortable works by comparing objects in the same group to see how they should be positioned. From time to time you may want to customize the way these
305+
objects are compared by simply implementing the Doctrine\Common\Comparable interface
306+
307+
``` php
308+
<?php
309+
namespace Entity;
310+
311+
use Doctrine\Common\Comparable;
312+
313+
/**
314+
* @ORM\Table(name="items")
315+
* @ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
316+
*/
317+
class Item implements Comparable
318+
{
319+
public function compareTo($other)
320+
{
321+
// return 1 if this object is considered greater than the compare value
322+
323+
// return -1 if this object is considered less than the compare value
324+
325+
// return 0 if this object is considered equal to the compare value
326+
}
327+
}
328+
```

lib/Gedmo/Sortable/SortableListener.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Gedmo\Sortable;
44

5+
use Doctrine\Common\Comparable;
56
use Doctrine\Common\EventArgs;
67
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
78
use Doctrine\Common\Persistence\Proxy;
@@ -461,7 +462,13 @@ public function postFlush(EventArgs $args)
461462
$matches = $gr === null;
462463
} elseif (is_object($gr) && is_object($value) && $gr !== $value) {
463464
// Special case for equal objects but different instances.
464-
$matches = $gr == $value;
465+
// If the object implements Comparable interface we can use its compareTo method
466+
// Otherwise we fallback to normal object comparison
467+
if ($gr instanceof Comparable) {
468+
$matches = $gr->compareTo($value);
469+
} else {
470+
$matches = $gr == $value;
471+
}
465472
} else {
466473
$matches = $gr === $value;
467474
}

0 commit comments

Comments
 (0)