Skip to content

Commit d8fa9dc

Browse files
authored
Improve Context::__serialize (#1794)
1 parent 959faff commit d8fa9dc

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

src/Context.php

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class Context
4949
/**
5050
* Prototypical inheritance for properties.
5151
*/
52-
private ?Context $parent;
52+
protected ?Context $parent;
5353

5454
public function __construct(array $properties = [], ?Context $parent = null)
5555
{
@@ -183,16 +183,22 @@ public function getDebugLocation(): string
183183
return $location;
184184
}
185185

186-
/**
187-
* Excludes `reflector` property.
188-
*/
189186
public function __serialize(): array
190187
{
191-
$data = (array) $this;
192-
$data['reflector'] = null;
193-
unset($data['reflector']);
188+
return array_filter(get_object_vars($this), function ($value): bool {
189+
$rc = is_object($value) ? new \ReflectionClass($value) : null;
190+
191+
return (!$rc || !$rc->isAnonymous())
192+
&& !$value instanceof \Reflector
193+
&& !$value instanceof \Closure;
194+
});
195+
}
194196

195-
return $data;
197+
public function __unserialize(array $data): void
198+
{
199+
foreach ($data as $name => $value) {
200+
$this->{$name} = $value;
201+
}
196202
}
197203

198204
/**

tests/ContextTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,18 @@ public function testDebugLocation(): void
6868
$customerPropertyFirstName->_context->getDebugLocation()
6969
);
7070
}
71+
72+
// -------------------------------------------------------------------------
73+
74+
public function testSerialize(): void
75+
{
76+
$context = new Context(['filename' => __FILE__], $this->getContext());
77+
$serialized = serialize($context);
78+
$unserialized = unserialize($serialized);
79+
80+
$this->assertEquals($serialized, serialize($unserialized));
81+
$this->assertInstanceOf(Context::class, $unserialized->root());
82+
$this->assertNotSame($unserialized, $unserialized->root());
83+
$this->assertEquals(__FILE__, $unserialized->filename);
84+
}
7185
}

0 commit comments

Comments
 (0)