Skip to content

Commit

Permalink
Adding support for passing a closure to select(), it should return the
Browse files Browse the repository at this point in the history
list of fields to be selected
  • Loading branch information
lorenzo committed Mar 7, 2013
1 parent ec73b23 commit 53c9297
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/Cake/Model/Datasource/Database/Query.php
Expand Up @@ -331,6 +331,10 @@ public function select($fields = [], $overwrite = false) {
return $this->_parts['select']; return $this->_parts['select'];
} }


if (is_callable($fields)) {
$fields = $fields($this);
}

if (!is_array($fields)) { if (!is_array($fields)) {
$fields = [$fields]; $fields = [$fields];
} }
Expand Down
14 changes: 14 additions & 0 deletions lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php
Expand Up @@ -134,6 +134,20 @@ public function testSelectFieldsOnly() {
$this->assertEquals([3, 6], $result->fetch()); $this->assertEquals([3, 6], $result->fetch());
} }


/**
* Tests that it is possible to pass a closure as fields in select()
*
* @return void
*/
public function testSelectClosure() {
$query = new Query($this->connection);
$result = $query->select(function($q) use ($query) {

This comment has been minimized.

Copy link
@markstory

markstory Mar 7, 2013

Member

How is this working? The Closure never got bound to the test case.

This comment has been minimized.

Copy link
@lorenzo

lorenzo Mar 8, 2013

Author Member

Since PHP 5.4 you can use $this inside closures. The scope is always the class where the closure was declared in.

This comment has been minimized.

Copy link
@markstory

markstory Mar 8, 2013

Member

Good to know :D

$this->assertSame($query, $q);
return ['1 + 2', '1 + 5'];
})->execute();
$this->assertEquals([3, 6], $result->fetch());
}

/** /**
* Tests it is possible to select fields from tables with no conditions * Tests it is possible to select fields from tables with no conditions
* *
Expand Down

0 comments on commit 53c9297

Please sign in to comment.