Completed
Push — master ( b10a48...29cde4 )
by Ori
05:27
created

FieldsFactory::field()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
namespace frictionlessdata\tableschema\Fields;
3
4
use frictionlessdata\tableschema\Exceptions\FieldValidationException;
5
use frictionlessdata\tableschema\SchemaValidationError;
6
7
class FieldsFactory
8
{
9
    /**
10
     * list of all the available field classes
11
     * ordered in infer order - the most strict field first
12
     */
13
    public static $fieldClasses = [
14
        "\\frictionlessdata\\tableschema\\Fields\\IntegerField",
15
        "\\frictionlessdata\\tableschema\\Fields\\NumberField",
16
        "\\frictionlessdata\\tableschema\\Fields\\StringField",
17
    ];
18
19
    /**
20
     * get a new field object in the correct type according to the descriptor
21
     * @param object $descriptor
22
     * @return BaseField
23
     * @throws \Exception
24
     */
25
    public static function field($descriptor)
26
    {
27
        foreach (static::$fieldClasses as $fieldClass) {
28
            /** @var BaseField $fieldClass */
29
            if ($field = $fieldClass::inferDescriptor($descriptor)) {
30
                return $field;
31
            }
32
        }
33
        throw new FieldValidationException([
34
            new SchemaValidationError(
35
                SchemaValidationError::SCHEMA_VIOLATION,
36
                "Could not find a valid field for descriptor: ".json_encode($descriptor))
37
        ]);
38
    }
39
40
    /**
41
     * @param $val
42
     * @param null $descriptor
43
     * @return mixed
44
     * @throws FieldValidationException
45
     */
46
    public static function infer($val, $descriptor=null, $lenient=false)
47
    {
48
        foreach (static::$fieldClasses as $fieldClass) {
49
            /** @var BaseField $fieldClass */
50
            if ($field = $fieldClass::infer($val, $descriptor, $lenient)) {
51
                return $field;
52
            }
53
        }
54
        throw new FieldValidationException([
55
            new SchemaValidationError(
56
                SchemaValidationError::SCHEMA_VIOLATION,
57
                "Could not find a valid field for value: ".json_encode($val))
58
        ]);
59
    }
60
}