Skip to content
New issue

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

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

Already on GitHub? # to your account

Utilize PropertyAccess component for sorting arrays #159

Merged
merged 1 commit into from
Jun 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
"doctrine/phpcr-odm": "~1.2",
"jackalope/jackalope-doctrine-dbal": "~1.2",
"phpunit/phpunit": "~4.2",
"ruflin/elastica": "~1.0"
"ruflin/elastica": "~1.0",
"symfony/property-access": ">=2.3"
},

"suggest": {
"symfony/property-access": "To allow sorting arrays",
"doctrine/orm" : "to allow usage pagination with Doctrine ORM",
"doctrine/common" : "to allow usage pagination with Doctrine ArrayCollection",
"doctrine/mongodb-odm" : "to allow usage pagination with Doctrine ODM MongoDB",
Expand Down
117 changes: 66 additions & 51 deletions src/Knp/Component/Pager/Event/Subscriber/Sortable/ArraySubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,82 +2,97 @@

namespace Knp\Component\Pager\Event\Subscriber\Sortable;

use \ReflectionClass;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;
use Doctrine\ORM\Query;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

class ArraySubscriber implements EventSubscriberInterface
{

/**
* @var string the field used to sort current object array list
*/
private $currentSortingFieldGetter;
private $currentSortingField;

/**
* @var string the sorting direction
*/
private $sortDirection;

public function items(ItemsEvent $event)
/**
* @var PropertyAccessorInterface
*/
private $propertyAccessor;

public function __construct(PropertyAccessorInterface $accessor = null)
{
if (is_array($event->target) && count($event->target) > 1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactoring and enhancing in the same PR makes the diff roughly hard to read. Please next time create two separate PRs, it will make our life's easier.

Copy link
Contributor Author

@ostrolucky ostrolucky Jun 1, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean? Like first PR purely to refactor and second PR with actual feature pointed into first branch/PR? Sure can do so if you prefer that, even though I prefer having it in all in single PR to prevent conflicts (if there are some requested changes in first PR, it's likely second PR will have to be changed as well). In this case reading the full source is easier than diff though https://github.com/ostrolucky/knp-components/blob/db2daf3016612890b7a296dd5d44ae2bfe88856c/src/Knp/Component/Pager/Event/Subscriber/Sortable/ArraySubscriber.php

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep that's it. From my point of view it's better to not restructure the code and in the mean time change the contact(s). But don't worry, I'm not asking you to recreate two separate PRs :)

{
if (isset($_GET[$event->options['sortFieldParameterName']])) {
$this->sortDirection = isset($_GET[$event->options['sortDirectionParameterName']]) && strtolower($_GET[$event->options['sortDirectionParameterName']]) === 'asc' ? 'asc' : 'desc';

// TODO add whitelist
// if (isset($event->options['sortFieldWhitelist'])) {
// if (!in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) {
// throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist");
// }
// }

$sortFieldParameterName = explode('.', $_GET[$event->options['sortFieldParameterName']]);
if(isset($sortFieldParameterName[1])) {
// Capitalize first letter in order to prepare getter construction
$sortFieldName = ucfirst($sortFieldParameterName[1]);

$this->currentSortingFieldGetter = "get{$sortFieldName}";

// Getter detection
$class = new ReflectionClass(get_class(current($event->target)));
if($class->hasMethod($this->currentSortingFieldGetter)) {
// Sort
usort($event->target, array($this, "sort" . ucfirst($this->sortDirection)));
}
}
}
if (!$accessor && class_exists('Symfony\Component\PropertyAccess\PropertyAccess')) {
$accessor = PropertyAccess::createPropertyAccessorBuilder()->enableMagicCall()->getPropertyAccessor();
}

$this->propertyAccessor = $accessor;
}

/**
* @param $object1 first object to compare
* @param $object2 second object to compare
*/
private function sortAsc($object1, $object2)
public function items(ItemsEvent $event)
{
$fieldValue1 = strtolower($object1->{$this->currentSortingFieldGetter}());
$fieldValue2 = strtolower($object2->{$this->currentSortingFieldGetter}());
if ($fieldValue1 == $fieldValue2) {
return 0;
if (!is_array($event->target) || empty($_GET[$event->options['sortFieldParameterName']])) {
return;
}
return ($fieldValue1 > $fieldValue2) ? +1 : -1;

if (isset($event->options['sortFieldWhitelist']) && !in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) {
throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist");
}

$sortFunction = isset($event->options['sortFunction']) ? $event->options['sortFunction'] : array($this, 'proxySortFunction');
$sortField = $_GET[$event->options['sortFieldParameterName']];

// compatibility layer
if ($sortField[0] === '.') {
$sortField = substr($sortField, 1);
}

call_user_func_array($sortFunction, array(
&$event->target,
$sortField,
isset($_GET[$event->options['sortDirectionParameterName']]) && strtolower($_GET[$event->options['sortDirectionParameterName']]) === 'asc' ? 'asc' : 'desc'
));
}

private function proxySortFunction(&$target, $sortField, $sortDirection) {
$this->currentSortingField = $sortField;
$this->sortDirection = $sortDirection;

return usort($target, array($this, 'sortFunction'));
}

/**
* @param $object1 first object to compare
* @param $object2 second object to compare
* @param mixed $object1 first object to compare
* @param mixed $object2 second object to compare
*
* @return boolean
*/
private function sortDesc($object1, $object2)
private function sortFunction($object1, $object2)
{
$fieldValue1 = strtolower($object1->{$this->currentSortingFieldGetter}());
$fieldValue2 = strtolower($object2->{$this->currentSortingFieldGetter}());
if ($fieldValue1 == $fieldValue2) {
if (!$this->propertyAccessor) {
throw new \UnexpectedValueException('You need symfony/property-access component to use this sorting function');
}

$fieldValue1 = $this->propertyAccessor->getValue($object1, $this->currentSortingField);
$fieldValue2 = $this->propertyAccessor->getValue($object2, $this->currentSortingField);

if (is_string($fieldValue1)) {
$fieldValue1 = mb_strtolower($fieldValue1);
}

if (is_string($fieldValue2)) {
$fieldValue2 = mb_strtolower($fieldValue2);
}

if ($fieldValue1 === $fieldValue2) {
return 0;
}
return ($fieldValue1 > $fieldValue2) ? -1 : +1;

return ($fieldValue1 > $fieldValue2 ? 1 : -1) * ($this->sortDirection === 'asc' ? 1 : -1);
}

public static function getSubscribedEvents()
Expand All @@ -86,4 +101,4 @@ public static function getSubscribedEvents()
'knp_pager.items' => array('items', 1)
);
}
}
}
73 changes: 73 additions & 0 deletions tests/Test/Pager/Subscriber/Sortable/ArraySubscriberTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace Test\Pager\Subscriber\Sortable;

use Knp\Component\Pager\Event\ItemsEvent;
use Knp\Component\Pager\Event\Subscriber\Sortable\ArraySubscriber;
use Test\Tool\BaseTestCase;

class ArraySubscriberTest extends BaseTestCase
{
/**
* @test
*/
public function shouldSort()
{
$array = array(
array('entry' => array('sortProperty' => 2)),
array('entry' => array('sortProperty' => 3)),
array('entry' => array('sortProperty' => 1)),
);

$itemsEvent = new ItemsEvent(0, 10);
$itemsEvent->target = &$array;
$itemsEvent->options = array('sortFieldParameterName' => 'sort', 'sortDirectionParameterName' => 'ord');
$_GET = array('sort' => '[entry][sortProperty]', 'ord' => 'asc');

$this->assertEquals(2, $array[0]['entry']['sortProperty']);
$arraySubscriber = new ArraySubscriber();
$arraySubscriber->items($itemsEvent);
$this->assertEquals(1, $array[0]['entry']['sortProperty']);
$_GET ['ord'] = 'desc';
$arraySubscriber->items($itemsEvent);
$this->assertEquals(3, $array[0]['entry']['sortProperty']);
}

/**
* @test
*/
public function shouldSortWithCustomCallback()
{
$array = array(
array('name' => 'hot'),
array('name' => 'cold'),
array('name' => 'hot'),
);

$itemsEvent = new ItemsEvent(0, 10);
$itemsEvent->target = &$array;
$itemsEvent->options = array(
'sortFieldParameterName' => 'sort',
'sortDirectionParameterName' => 'ord',
'sortFunction' => function (&$target, $sortField, $sortDirection) {
usort($target, function($object1, $object2) use ($sortField, $sortDirection) {
if ($object1[$sortField] == $object2[$sortField]) {
return 0;
}

return ($object1[$sortField] == 'hot' ? 1 : -1) * ($sortDirection == 'asc' ? 1 : -1);
});
},
);
$_GET = array('sort' => '.name', 'ord' => 'asc');

$this->assertEquals('hot', $array[0]['name']);
$arraySubscriber = new ArraySubscriber();
$arraySubscriber->items($itemsEvent);
$this->assertEquals('cold', $array[0]['name']);
$_GET['ord'] = 'desc';
$arraySubscriber->items($itemsEvent);
$this->assertEquals('hot', $array[0]['name']);

}
}