SessionPhpSerializer::serialize()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 2
nop 1
crap 12
1
<?php
2
/**
3
 * SessionPhpSerializer.php
4
 *
5
 * @copyright      More in license.md
6
 * @license        http://www.ipublikuj.eu
7
 * @author         Adam Kadlec http://www.ipublikuj.eu
8
 * @package        iPublikuj:WebSocketSession!
9
 * @subpackage     Serializers
10
 * @since          1.0.0
11
 *
12
 * @date           02.03.17
13
 */
14
15
declare(strict_types = 1);
16
17
namespace IPub\WebSocketsSession\Serializers;
18
19
use Nette;
20
21
use IPub;
22
use IPub\WebSocketsSession\Exceptions;
23
24 1
class SessionPhpSerializer implements ISessionSerializer
25
{
26
	/**
27
	 * Implement nette smart magic
28
	 */
29 1
	use Nette\SmartObject;
30
31
	/**
32
	 * {@inheritdoc}
33
	 */
34
	public function serialize(array $data) : string
35
	{
36
		$preSerialized = [];
37
		$serialized = '';
38
39
		if (count($data)) {
40
			foreach ($data as $bucket => $bucketData) {
41
				$preSerialized[] = $bucket . '|' . \serialize($bucketData);
42
			}
43
44
			$serialized = implode('', $preSerialized);
45
		}
46
47
		return $serialized;
48
	}
49
50
	/**
51
	 * @link http://ca2.php.net/manual/en/function.session-decode.php#108037 Code from this comment on php.net
52
	 *
53
	 * {@inheritdoc}
54
	 *
55
	 * @throws \UnexpectedValueException If there is a problem parsing the data
56
	 */
57
	public function unserialize(string $raw) : array
58
	{
59
		$returnData = [];
60
		$offset = 0;
61
62
		while ($offset < strlen($raw)) {
63
			if (!strstr(substr($raw, $offset), '|')) {
64
				throw new Exceptions\UnexpectedValueException(sprintf('Invalid data, remaining: %s', substr($raw, $offset)));
65
			}
66
67
			$pos = strpos($raw, '|', $offset);
68
			$num = $pos - $offset;
69
			$varname = substr($raw, $offset, $num);
70
			$offset += $num + 1;
71
			$data = unserialize(substr($raw, $offset));
72
73
			$returnData[$varname] = $data;
74
			$offset += strlen(serialize($data));
75
		}
76
77
		return $returnData;
78
	}
79
}
80