diff --git a/src/Utilities/Helper.php b/src/Utilities/Helper.php index 5683ed91..4852df6b 100644 --- a/src/Utilities/Helper.php +++ b/src/Utilities/Helper.php @@ -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 { @@ -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); } diff --git a/tests/Integration/QueryDataTableTest.php b/tests/Integration/QueryDataTableTest.php index 40d8d1de..e3e20ccb 100644 --- a/tests/Integration/QueryDataTableTest.php +++ b/tests/Integration/QueryDataTableTest.php @@ -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(); @@ -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(); + }); } }