From 452c4d0c6fd898245f7db68d00db64922d028be5 Mon Sep 17 00:00:00 2001 From: Tomas Prochazka Date: Thu, 12 Nov 2015 10:17:05 +0100 Subject: Sort by magic properies of object. --- src/SortByFieldExtension.php | 2 +- test/Foo.php | 13 +++++++++++++ test/SortByFieldExtensionTest.php | 28 ++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/SortByFieldExtension.php b/src/SortByFieldExtension.php index 6b2100f..8af21f5 100644 --- a/src/SortByFieldExtension.php +++ b/src/SortByFieldExtension.php @@ -79,7 +79,7 @@ class SortByFieldExtension extends \Twig_Extension { if (is_array($item)) return array_key_exists($field, $item); elseif (is_object($item)) - return property_exists($item, $field); + return isset($item->$field) || property_exists($item, $field); else return false; } diff --git a/test/Foo.php b/test/Foo.php index e6e688c..4b6148b 100644 --- a/test/Foo.php +++ b/test/Foo.php @@ -7,4 +7,17 @@ class Foo { public $name; + private $attrs = array(); + + public function __isset($name) { + return isset($this->attrs[$name]); + } + + public function __get($name) { + return $this->attrs[$name]; + } + + public function __set($name, $value) { + $this->attrs[$name] = $value; + } } diff --git a/test/SortByFieldExtensionTest.php b/test/SortByFieldExtensionTest.php index 64bd11e..ff15a35 100644 --- a/test/SortByFieldExtensionTest.php +++ b/test/SortByFieldExtensionTest.php @@ -89,6 +89,34 @@ class SortByFieldExtensionTest extends PHPUnit_Framework_TestCase { } } + public function testSortObjectsMagicProperty() { + $base = array(); + $ob1 = new Foo(); + $ob1->magicName = "Redmine"; + $base[]=$ob1; + + $ob2 = new Foo(); + $ob2->magicName = "GitLab"; + $base[]=$ob2; + + $ob3 = new Foo(); + $ob3->magicName = "Jenkins"; + $base[]=$ob3; + + $ob4 = new Foo(); + $ob4->magicName = "Jenkins"; + $base[]=$ob4; + + $fact = array('GitLab','Jenkins','Jenkins','Redmine'); + + $filter = new SortByFieldExtension(); + $sorted = $filter->sortByFieldFilter($base,'magicName'); + + for ($i = 0; $i < count($fact); $i++){ + $this->assertEquals($fact[$i], $sorted[$i]->magicName); + } + } + public function testNonArrayBase() { $filter = new SortByFieldExtension(); $this->setExpectedException('InvalidArgumentException'); -- cgit v1.2.3