FieldFormatGuess::addValue()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 9
cp 0
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
1
<?php
2
3
namespace Mathielen\ImportEngineBundle\Generator\ValueObject;
4
5
class FieldFormatGuess
6
{
7
    private $hasBlankValues = false;
8
9
    /**
10
     * @var array
11
     */
12
    private $typeDistribution = array();
13
14
    private function guessValueType($value)
15
    {
16
        if (is_array($value)) {
17
            return 'array';
18
        } elseif (is_object($value)) {
19
            return get_class($value);
20
        } elseif (is_numeric($value)) {
21
            if (preg_match('/^[01]+$/', $value)) {
22
                return 'boolean';
23
            } elseif (preg_match('/^[0-9]+$/', $value)) {
24
                return 'integer';
25
            } else {
26
                return 'double';
27
            }
28
        } else {
29
            return 'string';
30
        }
31
    }
32
33
    public function addValue($value)
34
    {
35
        if ($value == '') {
36
            $this->hasBlankValues = true;
37
        } else {
38
            $type = $this->guessValueType($value);
39
            isset($this->typeDistribution[$type]) ? ++$this->typeDistribution[$type] : $this->typeDistribution[$type] = 1;
40
        }
41
    }
42
43
    public function guessFieldType($defaultFieldFormat)
44
    {
45
        $distributionCount = count($this->typeDistribution);
46
47
        if ($distributionCount == 1) {
48
            $types = array_keys($this->typeDistribution);
49
            $guessedType = $types[0];
50
        } elseif ($distributionCount == 0) {
51
            $guessedType = $defaultFieldFormat;
52
        } else {
53
            arsort($this->typeDistribution);
54
            $guessedType = array_keys($this->typeDistribution)[0];
55
        }
56
57
        return array(
58
            'empty' => $this->hasBlankValues,
59
            'type' => $guessedType,
60
        );
61
    }
62
}
63