Skip to content

Commit 5d28e21

Browse files
authored
Merge pull request #2800 from yajra/di
[10.x] Add support for dependency injection when using closure.
2 parents e703d86 + d118a10 commit 5d28e21

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/Utilities/Helper.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
namespace Yajra\DataTables\Utilities;
44

5+
use Closure;
56
use DateTime;
67
use Illuminate\Contracts\Support\Arrayable;
78
use Illuminate\Support\Arr;
89
use Illuminate\Support\Str;
10+
use ReflectionFunction;
911

1012
class Helper
1113
{
@@ -58,12 +60,23 @@ protected static function isItemOrderInvalid($item, $array)
5860
* @param array $data data to use with blade template
5961
* @param array|object $param parameter to call with callable
6062
* @return mixed
63+
*
64+
* @throws \ReflectionException
6165
*/
6266
public static function compileContent($content, array $data, array|object $param)
6367
{
6468
if (is_string($content)) {
6569
return static::compileBlade($content, static::getMixedValue($data, $param));
66-
} elseif (is_callable($content)) {
70+
}
71+
72+
if ($content instanceof Closure) {
73+
$reflection = new ReflectionFunction($content);
74+
$arguments = $reflection->getParameters();
75+
76+
if (count($arguments) > 0) {
77+
return app()->call($content, [$arguments[0]->name => $param]);
78+
}
79+
6780
return $content($param);
6881
}
6982

tests/Integration/QueryDataTableTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,26 @@ public function it_can_return_formatted_columns()
339339
$this->assertEquals(Carbon::parse($user->created_at)->format('Y-m-d'), $data['created_at_formatted']);
340340
}
341341

342+
/** @test */
343+
public function it_can_return_added_column_with_dependency_injection()
344+
{
345+
$crawler = $this->call('GET', '/closure-di');
346+
347+
$crawler->assertJson([
348+
'draw' => 0,
349+
'recordsTotal' => 20,
350+
'recordsFiltered' => 20,
351+
]);
352+
353+
$user = DB::table('users')->find(1);
354+
$data = $crawler->json('data')[0];
355+
356+
$this->assertTrue(isset($data['name']));
357+
$this->assertTrue(isset($data['name_di']));
358+
359+
$this->assertEquals($user->name.'_di', $data['name_di']);
360+
}
361+
342362
protected function setUp(): void
343363
{
344364
parent::setUp();
@@ -451,5 +471,13 @@ protected function setUp(): void
451471
->setFilteredRecords(10)
452472
->toJson();
453473
});
474+
475+
$router->get('/closure-di', function (DataTables $dataTable) {
476+
return $dataTable->query(DB::table('users'))
477+
->addColumn('name_di', function ($user, User $u) {
478+
return $u->newQuery()->find($user->id)->name.'_di';
479+
})
480+
->toJson();
481+
});
454482
}
455483
}

0 commit comments

Comments
 (0)