Skip to content

Commit 54d1ba8

Browse files
authored
Merge pull request #4 from WyriHaximus/from-array-clone-false
fromArray can also update the current instance
2 parents 620f804 + e23aad3 commit 54d1ba8

File tree

2 files changed

+43
-7
lines changed

2 files changed

+43
-7
lines changed

src/Session.php

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -135,21 +135,25 @@ public function toArray(): array
135135

136136
/**
137137
* @param array $session
138+
* @param bool $clone
138139
* @throws \InvalidArgumentException
139140
* @return Session
140141
*/
141-
public function fromArray(array $session): self
142+
public function fromArray(array $session, bool $clone = true): self
142143
{
143144
if (!isset($session['id']) || !isset($session['contents']) || !isset($session['oldIds']) || !isset($session['oldIds'])) {
144145
throw new \InvalidArgumentException('Session array most contain "id", "contents", "oldIds", and "status".');
145146
}
146147

147-
$clone = clone $this;
148-
$clone->id = $session['id'];
149-
$clone->contents = $session['contents'];
150-
$clone->oldIds = $session['oldIds'];
151-
$clone->status = $session['status'];
148+
$self = $this;
149+
if ($clone === true) {
150+
$self = clone $this;
151+
}
152+
$self->id = $session['id'];
153+
$self->contents = $session['contents'];
154+
$self->oldIds = $session['oldIds'];
155+
$self->status = $session['status'];
152156

153-
return $clone;
157+
return $self;
154158
}
155159
}

tests/SessionTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,36 @@ public function testToFromArray()
106106
self::assertNotSame($session, $newSession);
107107
self::assertSame($array, $newSession->toArray());
108108
}
109+
110+
public function testToFromArrayNoClone()
111+
{
112+
$session = new Session('', [], new RandomBytes());
113+
114+
self::assertSame(
115+
[
116+
'id' => '',
117+
'contents' => [],
118+
'oldIds' => [],
119+
'status' => 1,
120+
],
121+
$session->toArray()
122+
);
123+
124+
$session->begin();
125+
126+
self::assertSame(
127+
[
128+
'id' => $session->getId(),
129+
'contents' => [],
130+
'oldIds' => [],
131+
'status' => 2,
132+
],
133+
$session->toArray()
134+
);
135+
136+
$array = $session->toArray();
137+
$newSession = $session->fromArray($array, false);
138+
self::assertSame($session, $newSession);
139+
self::assertSame($array, $newSession->toArray());
140+
}
109141
}

0 commit comments

Comments
 (0)