Completed
Push — master ( a08147...ea1ae0 )
by Ondrej
10s
created

LowercaseConverter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 41
c 0
b 0
f 0
ccs 8
cts 8
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A toEnum() 0 4 1
A fromEnum() 0 7 2
1
<?php
2
namespace SpareParts\Enum\Converter;
3
4
use SpareParts\Enum\Enum;
5
6
/**
7
 * Converts Enum to lowercase string.
8
 *
9
 * Usage:
10
 *
11
 * $converter = new LowercaseConverter(WindowState::class);
12
 *
13
 * $converter->toEnum('closed') // returns WindowState::CLOSED() instance
14
 *
15
 * $converter->fromEnum(WindowState::CLOSED()) // returns 'closed'
16
17
 */
18
class LowercaseConverter implements IConverter
19
{
20
    /**
21
     * @var string
22
     */
23
    protected $enumClass;
24
25
    /**
26
     * @param string $enumClass
27
     * @throws ConverterSetupException
28
     */
29 5
    public function __construct($enumClass)
30
    {
31 5
        if (!is_subclass_of($enumClass, Enum::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \SpareParts\Enum\Enum::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
32 1
            throw new ConverterSetupException("Class ${enumClass} is not a valid Enum. (doesnt extend Enum class)");
33
        }
34
        $this->enumClass = $enumClass;
35
    }
36
37
    /**
38
     * @param mixed $value
39
     * @return Enum
40
     */
41
    public function toEnum($value)
42
    {
43 2
        return call_user_func_array([$this->enumClass, 'instance'], [strtoupper($value)]);
44
    }
45
46
    /**
47
     * @param Enum $enum
48
     * @return string
49
     * @throws UnableToConvertException
50
     */
51
    public function fromEnum(Enum $enum)
52
    {
53 2
        if (!($enum instanceof $this->enumClass)) {
54 1
            throw new UnableToConvertException(sprintf('Enum %s is not of type %s.', get_class($enum), $this->enumClass));
55
        }
56 1
        return strtolower((string) $enum);
57
    }
58
}