GoodbyCsvProvider   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 76
c 0
b 0
f 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A countRows() 0 6 1
A collectColumnSizes() 0 6 1
B interpret() 0 44 6
1
<?php
2
3
namespace Toa\Component\Validator\Provider;
4
5
use Goodby\CSV\Import\Standard\Interpreter;
6
use Goodby\CSV\Import\Standard\Lexer;
7
use Goodby\CSV\Import\Standard\LexerConfig;
8
9
/**
10
 * GoodbyCsvProvider
11
 *
12
 * @author Enrico Thies <[email protected]>
13
 */
14
class GoodbyCsvProvider implements CsvProviderInterface
15
{
16
    /** @var array */
17
    private $interpretations = array ();
18
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function countRows($value, $options = array())
23
    {
24
        $interpretation = $this->interpret($value, $options);
25
26
        return $interpretation['rows'];
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function collectColumnSizes($value, $options = array())
33
    {
34
        $interpretation = $this->interpret($value, $options);
35
36
        return $interpretation['columnSizes'];
37
    }
38
39
    /**
40
     * @param string $value
41
     * @param array  $options
42
     *
43
     * @return array
44
     */
45
    private function interpret($value, $options = array())
46
    {
47
        $key = sprintf('%s|%s', (string) $value, implode('|', array_values($options)));
48
49
        if (isset ($this->interpretations[$key])) {
50
            return $this->interpretations[$key];
51
        }
52
53
54
        $config = new LexerConfig();
55
56
        $config = isset($options['delimiter']) ? $config->setDelimiter($options['delimiter']) : $config;
57
        $config = isset($options['enclosure']) ? $config->setEnclosure($options['enclosure']) : $config;
58
        $config = isset($options['escape']) ? $config->setEscape($options['escape']) : $config;
59
60
        $lexer = new Lexer($config);
61
62
        $rowCounter = 0;
63
        $columnSizes = array();
64
65
        $interpreter = new Interpreter();
66
        $interpreter->unstrict();
67
        $interpreter->addObserver(
68
            function (array $row) use (&$rowCounter, &$columnSizes) {
69
                $rowCounter ++;
70
                $rowLength = count($row);
71
72
                if (!isset($columnSizes[$rowLength])) {
73
                    $columnSizes[$rowLength] = array();
74
                }
75
76
                $columnSizes[$rowLength][] = $rowCounter;
77
            }
78
        );
79
80
        $lexer->parse($value, $interpreter);
81
82
        $this->interpretations[$key] = array(
83
            'rows' => $rowCounter,
84
            'columnSizes' => $columnSizes
85
        );
86
87
        return $this->interpretations[$key];
88
    }
89
}
90