Completed
Push — master ( c18e77...cd2879 )
by Maxime
13s queued 11s
created

convertToDatabaseValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
/*
4
 * This file is part of the "elao/enum" package.
5
 *
6
 * Copyright (C) Elao
7
 *
8
 * @author Elao <[email protected]>
9
 */
10
11
namespace Elao\Enum\Bridge\Doctrine\DBAL\Types;
12
13
use Doctrine\DBAL\Platforms\AbstractPlatform;
14
use Doctrine\DBAL\Types\SimpleArrayType;
15
use Elao\Enum\EnumInterface;
16
17
abstract class AbstractCsvCollectionEnumType extends SimpleArrayType
18
{
19 View Code Duplication
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
20
    {
21
        if (\is_array($value)) {
22
            return implode(',', array_unique(array_values(array_map(static function (EnumInterface $enum) {
23
                return $enum->getValue();
24
            }, $value))));
25
        }
26
27
        return parent::convertToDatabaseValue($value, $platform);
28
    }
29
30
    public function convertToPHPValue($value, AbstractPlatform $platform)
31
    {
32
        if ($value === null) {
33
            return null;
34
        }
35
36
        if ($value === '') {
37
            // An empty csv means an empty array:
38
            return [];
39
        }
40
41
        $values = parent::convertToPHPValue($value, $platform);
42
43
        if (\is_array($values)) {
44
            $enumClass = $this->getEnumClass();
45
            $values = array_map([$enumClass, 'get'], array_map(static function ($v) use ($enumClass) {
46
                // Attempt to cast to integer value if the enum class accepts it:
47
                return $enumClass::accepts((int) $v) ? (int) $v : $v;
48
            }, array_unique(array_values($values))));
49
        }
50
51
        return $values;
52
    }
53
54
    abstract protected function getEnumClass(): string;
55
}
56