Skip to content

Commit

Permalink
[11.x] Allow using castAsJson() on non default db connection during…
Browse files Browse the repository at this point in the history
… test (#53256)

* [11.x] Allow using `castAsJson()` on non default db connection during
test

Signed-off-by: Mior Muhammad Zaki <crynobone@gmail.com>

* wip

Signed-off-by: Mior Muhammad Zaki <crynobone@gmail.com>

---------

Signed-off-by: Mior Muhammad Zaki <crynobone@gmail.com>
  • Loading branch information
crynobone authored Oct 21, 2024
1 parent 3807ec7 commit ebd5b6e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -231,20 +231,23 @@ protected function isSoftDeletableModel($model)
* Cast a JSON string to a database compatible type.
*
* @param array|object|string $value
* @param string|null $collection
* @return \Illuminate\Contracts\Database\Query\Expression
*/
public function castAsJson($value)
public function castAsJson($value, $connection = null)
{
if ($value instanceof Jsonable) {
$value = $value->toJson();
} elseif (is_array($value) || is_object($value)) {
$value = json_encode($value);
}

$value = DB::connection()->getPdo()->quote($value);
$db = DB::connection($connection);

return DB::raw(
DB::connection()->getQueryGrammar()->compileJsonValueCast($value)
$value = $db->getPdo()->quote($value);

return $db->raw(
$db->getQueryGrammar()->compileJsonValueCast($value)
);
}

Expand Down
10 changes: 5 additions & 5 deletions tests/Testing/Concerns/InteractsWithDatabaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,15 @@ protected function castAsJson($value, $grammar)

$connection->shouldReceive('getQueryGrammar')->andReturn($grammar);

$connection->shouldReceive('raw')->andReturnUsing(function ($value) {
return new Expression($value);
});

$connection->shouldReceive('getPdo->quote')->andReturnUsing(function ($value) {
return "'".$value."'";
});

DB::shouldReceive('connection')->andReturn($connection);

DB::shouldReceive('raw')->andReturnUsing(function ($value) {
return new Expression($value);
});
DB::shouldReceive('connection')->with(null)->andReturn($connection);

$instance = new class
{
Expand Down

0 comments on commit ebd5b6e

Please sign in to comment.