Skip to content

Commit

Permalink
Merge pull request #560 from FriendsOfCake/custom-finder
Browse files Browse the repository at this point in the history
Allow using custom finder with options.
  • Loading branch information
ADmad authored Jan 2, 2018
2 parents ba256b5 + 81a8bdd commit 39b29c3
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/Traits/FindMethodTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ trait FindMethodTrait
* If `$method` is NULL the current value is returned
* else the `findMethod` is changed
*
* @param string|null $method Method name
* @return string
* @param string|array|null $method Method name as string or array where
* key is finder name and value is find options.
* @return string|array
*/
public function findMethod($method = null)
{
Expand All @@ -35,7 +36,13 @@ protected function _findRecord($id, Subject $subject)
{
$repository = $this->_table();

$query = $repository->find($this->findMethod());
$finder = $this->findMethod();
$options = [];
if (is_array($finder)) {
$options = (array)current($finder);
$finder = key($finder);
}
$query = $repository->find($finder, $options);
$query->where([current($query->aliasField($repository->primaryKey())) => $id]);

$subject->set([
Expand Down
16 changes: 16 additions & 0 deletions tests/App/Model/Table/BlogsTable.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
<?php
namespace Crud\Test\App\Model\Table;

use Cake\ORM\Query;

class BlogsTable extends \Cake\ORM\Table
{
public $customOptions;

/**
* findWithCustomOptions
*
* @param Query $query
* @param array $options
* @return void
*/
public function findWithCustomOptions(Query $query, array $options)
{
$this->customOptions = $options;

return $query;
}
}
20 changes: 20 additions & 0 deletions tests/TestCase/Action/EditActionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,26 @@ public function testActionGetWithQueryArgs()
$this->assertContains($expected, $result, '"body" do not match the expected value');
}

/**
* Test for custom finder with options.
*
* @return void
*/
public function testCustomFinder()
{
$this->_eventManager->on(
'Dispatcher.invokeController',
['priority' => 1000],
function ($event) {
$this->_controller->Crud->action('edit')
->findMethod(['withCustomOptions' => ['foo' => 'bar']]);
}
);

$this->get('/blogs/edit/1');
$this->assertSame(['foo' => 'bar'], $this->_controller->Blogs->customOptions);
}

/**
* Test POST will update an existing record
*
Expand Down

0 comments on commit 39b29c3

Please sign in to comment.