Skip to content

Commit

Permalink
Merge pull request #88 from paragonie/json-plus
Browse files Browse the repository at this point in the history
Support json field map templating
  • Loading branch information
paragonie-security authored Jul 28, 2023
2 parents 92aac4c + ec3b5fe commit 305c7ad
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/JsonFieldMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,30 @@ public function addField(array $indices, string $type): static
return $this;
}

/**
* Adds an object's configuration
*
* @param array|int|string $rootIndices
* @param JsonFieldMap $template
* @return static
*
* @throws CipherSweetException
*/
public function addMapFieldFromTemplate(
array|int|string $rootIndices,
JsonFieldMap $template
): static {
if (\is_string($rootIndices) || \is_int($rootIndices)) {
$rootIndices = [$rootIndices];
}

foreach ($template->getMapping() as $mapping) {
$indices = [...$rootIndices, ...$mapping['path']];
$this->addField($indices, $mapping['type']);
}
return $this;
}

/**
* @param array<array-key, string|int> $indices
* @return string
Expand Down
21 changes: 21 additions & 0 deletions tests/JsonFieldMapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,25 @@ public function testFlatten()
$this->assertCount(3, $new);
$this->assertSame($mapped, $new);
}

public function testTemplate()
{
$parent = new JsonFieldMap();
$template = (new JsonFieldMap())
->addTextField(['foo', 'bar'])
->addIntegerField(['bar', 'baz']);
$parent->addMapFieldFromTemplate(['data', 0], $template);
$parent->addMapFieldFromTemplate(['data', 1], $template);

$mapping = $parent->toString();
$this->assertSame(
'3be7ae2c{"fields":{' .
'"$64617461.#0000000000000000.$666f6f.$626172":"string",' .
'"$64617461.#0000000000000000.$626172.$62617a":"int",' .
'"$64617461.#0000000000000001.$666f6f.$626172":"string",' .
'"$64617461.#0000000000000001.$626172.$62617a":"int"' .
'}}',
$mapping
);
}
}

0 comments on commit 305c7ad

Please sign in to comment.