Skip to content

Commit

Permalink
Merge pull request #367 from tighten/merge-array-and-with-parameters
Browse files Browse the repository at this point in the history
Merge array and `with` parameters
  • Loading branch information
driftingly authored Oct 9, 2024
2 parents 9999dc0 + ce54dd6 commit dc43abb
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/Formatters/ArrayParametersOverViewWith.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,32 @@ public function enterNode(Node $node): Node|int|null
return null;
}

$existingArrayItems = [];

// Check if `view` has a second argument and extract array items
if (isset($node->getArgs()[1])) {
$secondArg = $node->getArgs()[1]->value;
if ($secondArg instanceof Array_) {
$existingArrayItems = $secondArg->items;
}
}

// Merge existing array items with `with` parameters
$mergedItems = array_merge(
$existingArrayItems,
array_map(function ($viewWith) {
return new ArrayItem(
$viewWith[1]->value,
$viewWith[0]->value,
);
}, array_reverse($this->viewWith))
);

return new FuncCall(
new Name('view'),
[
$node->getArgs()[0],
new Arg(new Array_(array_map(function ($viewWith) {
return new ArrayItem(
$viewWith[1]->value,
$viewWith[0]->value,
);
}, array_reverse($this->viewWith)), [
new Arg(new Array_($mergedItems, [
'kind' => Array_::KIND_SHORT,
])),
]
Expand Down
72 changes: 72 additions & 0 deletions tests/Formatting/Formatters/ArrayParametersOverViewWithTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,76 @@ function edit()

$this->assertSame($expected, $formatted);
}

/** @test */
public function it_merges_parameters_passed_using_with_and_array_parameters(): void
{
$file = <<<'file'
<?php
namespace App;
class Controller
{
function index()
{
return view('test.index', ['id' => 1234])->with('first', 'yes');
}
}
file;

$expected = <<<'file'
<?php
namespace App;
class Controller
{
function index()
{
return view('test.index', ['id' => 1234, 'first' => 'yes']);
}
}
file;

$formatted = (new TFormat)->format(new ArrayParametersOverViewWith($file));

$this->assertSame($expected, $formatted);
}

/** @test */
public function it_merges_array_parameters_with_multiple_with_calls(): void
{
$file = <<<'file'
<?php
namespace App;
class Controller
{
function index()
{
return view('test.index', ['id' => 1234])->with('first', 'yes')->with('second', 'yes');
}
}
file;

$expected = <<<'file'
<?php
namespace App;
class Controller
{
function index()
{
return view('test.index', ['id' => 1234, 'first' => 'yes', 'second' => 'yes']);
}
}
file;

$formatted = (new TFormat)->format(new ArrayParametersOverViewWith($file));

$this->assertSame($expected, $formatted);
}
}

0 comments on commit dc43abb

Please sign in to comment.