Skip to content

Commit

Permalink
Merge pull request #2800 from yajra/di
Browse files Browse the repository at this point in the history
[10.x] Add support for dependency injection when using closure.
  • Loading branch information
yajra authored Jun 21, 2022
2 parents e703d86 + d118a10 commit 5d28e21
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Utilities/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

namespace Yajra\DataTables\Utilities;

use Closure;
use DateTime;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use ReflectionFunction;

class Helper
{
Expand Down Expand Up @@ -58,12 +60,23 @@ protected static function isItemOrderInvalid($item, $array)
* @param array $data data to use with blade template
* @param array|object $param parameter to call with callable
* @return mixed
*
* @throws \ReflectionException
*/
public static function compileContent($content, array $data, array|object $param)
{
if (is_string($content)) {
return static::compileBlade($content, static::getMixedValue($data, $param));
} elseif (is_callable($content)) {
}

if ($content instanceof Closure) {
$reflection = new ReflectionFunction($content);
$arguments = $reflection->getParameters();

if (count($arguments) > 0) {
return app()->call($content, [$arguments[0]->name => $param]);
}

return $content($param);
}

Expand Down
28 changes: 28 additions & 0 deletions tests/Integration/QueryDataTableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,26 @@ public function it_can_return_formatted_columns()
$this->assertEquals(Carbon::parse($user->created_at)->format('Y-m-d'), $data['created_at_formatted']);
}

/** @test */
public function it_can_return_added_column_with_dependency_injection()
{
$crawler = $this->call('GET', '/closure-di');

$crawler->assertJson([
'draw' => 0,
'recordsTotal' => 20,
'recordsFiltered' => 20,
]);

$user = DB::table('users')->find(1);
$data = $crawler->json('data')[0];

$this->assertTrue(isset($data['name']));
$this->assertTrue(isset($data['name_di']));

$this->assertEquals($user->name.'_di', $data['name_di']);
}

protected function setUp(): void
{
parent::setUp();
Expand Down Expand Up @@ -451,5 +471,13 @@ protected function setUp(): void
->setFilteredRecords(10)
->toJson();
});

$router->get('/closure-di', function (DataTables $dataTable) {
return $dataTable->query(DB::table('users'))
->addColumn('name_di', function ($user, User $u) {
return $u->newQuery()->find($user->id)->name.'_di';
})
->toJson();
});
}
}

0 comments on commit 5d28e21

Please sign in to comment.