StringSerializeConverter   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 15
c 1
b 0
f 0
dl 0
loc 41
ccs 13
cts 13
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A convertFromEnumSet() 0 7 2
A convertToEnumSet() 0 10 2
1
<?php
2
3
namespace SpareParts\Enum\Set\Converter;
4
5
6
use SpareParts\Enum\Enum;
7
use SpareParts\Enum\Exception\InvalidEnumClassException;
8
use SpareParts\Enum\Set\ISet;
9
use SpareParts\Enum\Set\ImmutableSet;
10
11
class StringSerializeConverter implements IEnumSetConverter
12
{
13
    /**
14
     * @var string
15
     */
16
    private $enumClass;
17
18
    /**
19
     * @param string $enumClass
20
     */
21 9
    public function __construct($enumClass)
22
    {
23 9
        if (!is_subclass_of($enumClass, Enum::class)) {
24 1
            throw new InvalidEnumClassException("Class ${enumClass} does not implement Enum (as it should).");
25
        }
26
        $this->enumClass = $enumClass;
27
    }
28
29
    /**
30
     * @param string $serialized
31
     * @return ImmutableSet
32
     */
33
    public function convertToEnumSet($serialized): ISet
34
    {
35 4
        $serialized = (string) $serialized;
36 4
        $stringList = unserialize($serialized);
37
38 4
        $set = [];
39 4
        foreach ($stringList as $value) {
40 3
            $set[] = call_user_func([$this->enumClass, 'instance'], $value);
41
        }
42 4
        return new ImmutableSet($this->enumClass, $set);
43
    }
44
45
    public function convertFromEnumSet(ISet $enumSet): string
46
    {
47 4
        $stringList = [];
48 4
        foreach ($enumSet as $enum) {
49 3
            $stringList[] = (string) $enum;
50
        }
51 4
        return serialize($stringList);
52
    }
53
}
54