diff --git a/README.md b/README.md index 36ffbb9..f7525ef 100644 --- a/README.md +++ b/README.md @@ -119,12 +119,12 @@ class User extends \Phalcon\Mvc\Model { url: '/test/index', method: 'POST' }, - columns: { + columns: [ {data: "id", searchable: false}, {data: "name"}, {data: "email"}, {data: "balance", searchable: false} - } + ] }); }); diff --git a/spec/suite/DataTableSpec.php b/spec/suite/DataTableSpec.php index 60efcf2..3fac694 100644 --- a/spec/suite/DataTableSpec.php +++ b/spec/suite/DataTableSpec.php @@ -12,6 +12,24 @@ }); + it("should work with empty ResultSet", function() { + + $resultset = $this->di->get('modelsManager') + ->createQuery("SELECT * FROM \Spec\Models\User WHERE balance < 0") + ->execute(); + + $dataTables = new DataTable(); + $response = $dataTables->fromResultSet($resultset)->getResponse(); + + expect($response)->toBe([ + 'draw' => null, + 'recordsTotal' => 0, + 'recordsFiltered' => 0, + 'data' => [] + ]); + + }); + it("should create a ResultSet", function() { $resultset = $this->di->get('modelsManager') @@ -38,6 +56,24 @@ }); + it("should create an empty ArrayAdapter", function() { + + $array = $this->di->get('modelsManager') + ->createQuery("SELECT * FROM \Spec\Models\User WHERE balance < 0") + ->execute()->toArray(); + + $dataTables = new DataTable(); + $response = $dataTables->fromArray($array)->getResponse(); + + expect($response)->toBe([ + 'draw' => null, + 'recordsTotal' => 0, + 'recordsFiltered' => 0, + 'data' => [] + ]); + + }); + it("should create a ArrayAdapter", function() { $array = $this->di->get('modelsManager') @@ -64,6 +100,26 @@ }); + it("should create a from a empty QueryBuilder", function() { + + $builder = $this->di->get('modelsManager') + ->createBuilder() + ->columns('id, name, email, balance') + ->from('Spec\Models\User') + ->where('balance < 0'); + + $dataTables = new DataTable(); + $response = $dataTables->fromBuilder($builder)->getResponse(); + + expect($response)->toBe([ + 'draw' => null, + 'recordsTotal' => 0, + 'recordsFiltered' => 0, + 'data' => [] + ]); + + }); + it("should create a QueryBuilder", function() { $builder = $this->di->get('modelsManager') diff --git a/src/DataTable.php b/src/DataTable.php index 2ba2ade..ad4bdd2 100644 --- a/src/DataTable.php +++ b/src/DataTable.php @@ -58,7 +58,7 @@ public function fromBuilder($builder, $columns = []) { } public function fromResultSet($resultSet, $columns = []) { - if(empty($columns)) { + if(empty($columns) && $resultSet->count() > 0) { $columns = array_keys($resultSet->getFirst()->toArray()); $resultSet->rewind(); } @@ -73,7 +73,7 @@ public function fromResultSet($resultSet, $columns = []) { } public function fromArray($array, $columns = []) { - if(empty($columns)) { + if(empty($columns) && count($array) > 0) { $columns = array_keys(current($array)); }