Skip to content

Commit f066488

Browse files
committed
Added __serialize and __unserialize methods.
1 parent 4bd55ed commit f066488

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

system/Context/Context.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,8 @@ public function getAll(): array
141141
* Get a hidden value from the context by its key, or return a default value if the key does not exist.
142142
* Supports dot notation for nested arrays.
143143
*
144-
* @param string $key The key to identify the data.
145-
* @param mixed $default The default value to return if the key does not exist in the context.
144+
* @param string $key The key to identify the data.
145+
* @param mixed $default The default value to return if the key does not exist in the context.
146146
*
147147
* @return mixed The value associated with the key, or the default value if the key does not exist.
148148
*/
@@ -308,4 +308,20 @@ public function __clone()
308308
{
309309
$this->hiddenData = [];
310310
}
311+
312+
public function __serialize(): array
313+
{
314+
return [
315+
'data' => $this->data,
316+
];
317+
}
318+
319+
/**
320+
* @param array<string, mixed> $data
321+
*/
322+
public function __unserialize(array $data): void
323+
{
324+
$this->data = $data['data'] ?? [];
325+
$this->hiddenData = [];
326+
}
311327
}

tests/system/Context/ContextTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,4 +817,21 @@ public function testCloneDoesNotCopyHiddenValues(): void
817817
$this->assertSame(123, $clonedContext->get('user_id')); // Normal value should be copied
818818
$this->assertNull($clonedContext->getHidden('credentials.api_key')); // Hidden value should not be copied
819819
}
820+
821+
public function testSerializationDoesNotIncludeHiddenValues(): void
822+
{
823+
$context = new Context();
824+
$context->set('user_id', 123);
825+
$context->setHidden('credentials.api_key', 'secret');
826+
827+
$serialized = serialize($context);
828+
829+
$this->assertStringContainsString('user_id', $serialized);
830+
$this->assertStringNotContainsString('secret', $serialized);
831+
832+
$unserializedContext = unserialize($serialized);
833+
834+
$this->assertSame(123, $unserializedContext->get('user_id')); // Normal value should be preserved
835+
$this->assertNull($unserializedContext->getHidden('credentials.api_key')); // Hidden value should not be preserved
836+
}
820837
}

0 commit comments

Comments
 (0)