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

StringField::inferProperties()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 3
eloc 5
nc 3
nop 2
1
<?php
2
namespace frictionlessdata\tableschema\Fields;
3
4
use frictionlessdata\tableschema\Exceptions\FieldValidationException;
5
6
class StringField extends BaseField
7
{
8
    public function format()
9
    {
10
        return isset($this->descriptor()->format) ? $this->descriptor()->format : null;
11
    }
12
13
    public function inferProperties($val, $lenient=false)
14
    {
15
        parent::inferProperties($val, $lenient);
16
        if (!$lenient) {
17
            if (strpos($val, "@") !== false) {
18
                $this->descriptor->format = "email";
19
            }
20
        }
21
    }
22
23
    /**
24
     * @param mixed $val
25
     * @return string
26
     * @throws \frictionlessdata\tableschema\Exceptions\FieldValidationException;
27
     */
28
    public function validateValue($val)
29
    {
30
        if ($this->format() == "email" && strpos($val, "@") === false) {
31
            throw $this->getValidationException("value is not a valid email", $val);
32
        } else {
33
            return $val;
34
        }
35
    }
36
37
    public static function type()
38
    {
39
        return "string";
40
    }
41
42
    public function getInferIdentifier($lenient=false)
43
    {
44
        $inferId = parent::getInferIdentifier();
45
        $format = $this->format();
46
        if (!$lenient && !empty($format)) {
47
            $inferId .= ":".$this->format();
48
        };
49
        return $inferId;
50
    }
51
}