Failed Conditions
Push — master ( ae100b...0b92ce )
by Adrien
10:55 queued 11s
created

LocalizedType::convertToPHPValue()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
ccs 5
cts 5
cp 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\DBAL\Types;
6
7
use Doctrine\DBAL\Platforms\AbstractPlatform;
8
use Doctrine\DBAL\Types\ConversionException;
9
use Doctrine\DBAL\Types\JsonType;
10
11
/**
12
 * Type specialized to store localized data as JSON.
13
 *
14
 * PHP values are expected to be an array of localized values indexed by language. The array
15
 * might be empty, but it can never be null or empty string.
16
 *
17
 * For convenience of DB operation the DB value might be null or an empty string, in which case
18
 * the PHP value will be an empty array. This allows for easy INSERT/UPDATE, and save two bytes
19
 * in case of empty array.
20
 */
21
final class LocalizedType extends JsonType
22
{
23
    public function getName(): string
24
    {
25
        return 'localized';
26
    }
27
28 1
    public function convertToPHPValue($value, AbstractPlatform $platform): array
29
    {
30 1
        if ($value === null || $value === '') {
31 1
            return [];
32
        }
33
34 1
        $val = parent::convertToPHPValue($value, $platform);
35
36 1
        return $val;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $val could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
37
    }
38
39 3
    public function convertToDatabaseValue($value, AbstractPlatform $platform): string
40
    {
41 3
        if (!is_array($value)) {
42 2
            throw ConversionException::conversionFailedSerialization($value, 'json', 'value must be a PHP array');
43
        }
44
45 1
        if (!$value) {
46 1
            return '';
47
        }
48
49 1
        return parent::convertToDatabaseValue($value, $platform);
50
    }
51
}
52