File: /home/xedaptot/be.naniguide.com/tests/Unit/FindAndReplaceTest.php
<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\Library\StringHelper;
class FindAndReplaceTest extends TestCase
{
public function test_it_updates_single_matching_node()
{
$data = [
'name' => 'Hello',
'src' => 'old.png'
];
$count = StringHelper::iterate($data, function (&$node) use (&$matches) {
$matches = 0;
if (($node['name'] ?? null) === 'Hello') {
$node['src'] = 'new.png';
$matches++;
}
return $matches;
});
$this->assertEquals('new.png', $data['src']);
}
public function test_it_updates_all_matching_nodes_across_nested_structure()
{
$data = [
'name' => 'Root',
'nodes' => [
['name' => 'Child1', 'src' => 'a.png'],
['name' => 'Child1', 'src' => 'b.png'],
],
'meta' => [
'info' => [
['name' => 'Child1', 'src' => 'c.png']
]
]
];
$count = 0;
StringHelper::iterate($data, function (&$node) use (&$count) {
if (($node['name'] ?? null) === 'Child1') {
$node['src'] = 'updated.png';
$count++;
}
});
$this->assertSame(3, $count);
$this->assertEquals('updated.png', $data['nodes'][0]['src']);
$this->assertEquals('updated.png', $data['meta']['info'][0]['src']);
}
public function test_it_handles_deeply_nested_structure()
{
$data = [
'a' => [
'b' => [
'c' => [
'name' => 'Target',
'src' => 'old.png'
]
]
]
];
$count = 0;
StringHelper::iterate($data, function (&$node) use (&$count) {
if (($node['name'] ?? null) === 'Target') {
$node['src'] = 'changed.png';
$count++;
}
});
$this->assertSame(1, $count);
$this->assertEquals('changed.png', $data['a']['b']['c']['src']);
}
public function test_it_returns_zero_when_no_match_is_found()
{
$data = [
'name' => 'Root',
'nodes' => [
['name' => 'ChildX', 'src' => 'a.png']
]
];
$count = 0;
StringHelper::iterate($data, function (&$node) use (&$count) {
if (($node['name'] ?? null) === 'Nonexistent') {
$node['src'] = 'updated.png';
$count++;
}
});
$this->assertSame(0, $count);
$this->assertEquals('a.png', $data['nodes'][0]['src']); // unchanged
}
public function test_it_works_with_mixed_assoc_and_numeric_arrays()
{
$data = [
'items' => [
['name' => 'Match', 'src' => 'a.png'],
['other' => [['name' => 'Match', 'src' => 'b.png']]]
]
];
$count = 0;
StringHelper::iterate($data, function (&$node) use (&$count) {
if (($node['name'] ?? null) === 'Match') {
$node['flag'] = true;
$count++;
}
});
$this->assertSame(2, $count);
$this->assertTrue($data['items'][0]['flag']);
$this->assertTrue($data['items'][1]['other'][0]['flag']);
}
public function test_it_allows_closure_to_add_new_keys()
{
$data = ['name' => 'Target', 'src' => 'a.png'];
$count = 0;
StringHelper::iterate($data, function (&$node) use (&$count) {
if (($node['name'] ?? null) === 'Target') {
$node['new'] = 'added';
$count++;
}
});
$this->assertSame(1, $count);
$this->assertEquals('added', $data['new']);
}
}