Skip to content

Commit

Permalink
Merge pull request #30 from systopia/json-schema-clone
Browse files Browse the repository at this point in the history
JsonSchema: Add method `__clone()`
  • Loading branch information
dontub authored Mar 21, 2024
2 parents b480fe4 + 789762f commit c248bf9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Civi/RemoteTools/JsonSchema/JsonSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,19 @@ public function __construct(array $keywords) {
$this->keywords = $keywords;
}

public function __clone() {
$this->keywords = array_map(function ($value) {
if (is_object($value)) {
return clone $value;
}
elseif (is_array($value)) {
return array_values(array_map(fn ($value) => is_object($value) ? clone $value : $value, $value));
}

return $value;
}, $this->keywords);
}

/**
* @param string $keyword
* @param TValue $value
Expand Down
14 changes: 14 additions & 0 deletions tests/phpunit/Civi/RemoteTools/JsonSchema/JsonSchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,20 @@ public function testFromArrayInvalid02(): void {
JsonSchema::fromArray(['foo' => new \stdClass()]);
}

public function testClone(): void {
$schema = new JsonSchema([
'foo' => new JsonSchema(['bar' => 'baz']),
'fuu' => [1, 2, new JsonSchemaString(['keyword' => 'value']), TRUE],
'f00' => NULL,
]);

$clone = clone $schema;

static::assertEquals($schema, $clone);
static::assertNotSame($schema, $clone);
static::assertNotSame($schema->getKeywords(), $clone->getKeywords());
}

public function testToArray(): void {
$schema = new JsonSchema([
'foo' => new JsonSchema(['bar' => 'baz']),
Expand Down

0 comments on commit c248bf9

Please sign in to comment.