InferSchema::lock()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
rs 9.4285
c 1
b 0
f 1
1
<?php
2
3
namespace frictionlessdata\tableschema;
4
5
/**
6
 *  Table Schema which updates the descriptor based on input data.
7
 */
8
class InferSchema extends Schema
9
{
10
    /**
11
     * InferSchema constructor.
12
     *
13
     * @param null $descriptor optional descriptor object - will be used as an initial descriptor
14
     * @param bool $lenient    if true - infer just basic types, without strict format requirements
15
     */
16
    public function __construct($descriptor = null, $lenient = false)
17
    {
18
        $this->descriptor = empty($descriptor) ? (object) ['fields' => []] : $descriptor;
19
        $this->fieldsInferer = new Fields\FieldsInferrer(null, $lenient);
20
    }
21
22
    /**
23
     * @return object
24
     */
25
    public function descriptor()
26
    {
27
        return $this->descriptor;
28
    }
29
30
    /**
31
     * @param mixed[] $row
32
     *
33
     * @return mixed[]
34
     *
35
     * @throws Exceptions\FieldValidationException
36
     */
37
    public function castRow($row)
38
    {
39
        if ($this->isLocked) {
40
            // schema is locked, no more inferring is needed
41
            return parent::castRow($row);
42
        } else {
43
            // add the row to the inferrer, update the descriptor according to the best inferred fields
44
            $this->fieldsInferer->addRows([$row]);
45
            $this->descriptor->fields = [];
46
            foreach ($this->fieldsInferer->infer() as $fieldName => $inferredField) {
47
                /* @var Fields\BaseField $inferredField */
48
                $this->descriptor->fields[] = $inferredField->descriptor();
49
            }
50
            $this->castRows = $this->fieldsInferer->castRows();
51
52
            return $this->castRows[count($this->castRows) - 1];
53
        }
54
    }
55
56
    public function lock()
57
    {
58
        $this->isLocked = true;
59
60
        return $this->castRows;
61
    }
62
63
    protected $isLocked = false;
64
    protected $fieldsInferer;
65
    protected $castRows;
66
}
67