Completed
Push — master ( 53f2a7...4c5c4c )
by Ori
02:27
created

BaseField::title()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace frictionlessdata\tableschema\Fields;
4
5
use frictionlessdata\tableschema\Exceptions\FieldValidationException;
6
use frictionlessdata\tableschema\SchemaValidationError;
7
8
abstract class BaseField
9
{
10
    public function __construct($descriptor = null)
11
    {
12
        $this->descriptor = empty($descriptor) ? (object) [] : $descriptor;
13
    }
14
15
    public function descriptor()
16
    {
17
        return $this->descriptor;
18
    }
19
20
    public function fullDescriptor()
21
    {
22
        $fullDescriptor = $this->descriptor();
23
        $fullDescriptor->format = $this->format();
24
        $fullDescriptor->type = $this->type();
25
26
        return $fullDescriptor;
27
    }
28
29
    public function name()
30
    {
31
        return $this->descriptor()->name;
32
    }
33
34
    public function title()
35
    {
36
        return isset($this->descriptor()->title) ? $this->descriptor()->title : null;
37
    }
38
39
    public function description()
40
    {
41
        return isset($this->descriptor()->description) ? $this->descriptor()->description : null;
42
    }
43
44
    public function rdfType()
45
    {
46
        return isset($this->descriptor()->rdfType) ? $this->descriptor()->rdfType : null;
47
    }
48
49
    public function format()
50
    {
51
        return isset($this->descriptor()->format) ? $this->descriptor()->format : 'default';
52
    }
53
54
    public function constraints()
55
    {
56
        if (!$this->constraintsDisabled && isset($this->descriptor()->constraints)) {
57
            return $this->descriptor()->constraints;
58
        } else {
59
            return (object) [];
60
        }
61
    }
62
63
    public function required()
64
    {
65
        return isset($this->constraints()->required) && $this->constraints()->required;
66
    }
67
68
    public function unique()
69
    {
70
        return isset($this->constraints()->unique) && $this->constraints()->unique;
71
    }
72
73
    public function disableConstraints()
74
    {
75
        $this->constraintsDisabled = true;
76
77
        return $this;
78
    }
79
80
    public function enum()
81
    {
82
        if (isset($this->constraints()->enum) && !empty($this->constraints()->enum)) {
83
            return $this->constraints()->enum;
84
        } else {
85
            return [];
86
        }
87
    }
88
89
    /**
90
     * try to create a field object based on the descriptor
91
     * by default uses the type attribute
92
     * return the created field object or false if the descriptor does not match this field.
93
     *
94
     * @param object $descriptor
95
     *
96
     * @return bool|BaseField
97
     */
98
    public static function inferDescriptor($descriptor)
99
    {
100
        if (isset($descriptor->type) && $descriptor->type == static::type()) {
101
            return new static($descriptor);
102
        } else {
103
            return false;
104
        }
105
    }
106
107
    /**
108
     * try to create a new field object based on the given value.
109
     *
110
     * @param mixed       $val
111
     * @param null|object $descriptor
112
     * @param bool @lenient
113
     *
114
     * @return bool|BaseField
115
     */
116
    public static function infer($val, $descriptor = null, $lenient = false)
117
    {
118
        $field = new static($descriptor);
119
        try {
120
            $field->castValue($val);
121
        } catch (FieldValidationException $e) {
122
            return false;
123
        }
124
        $field->inferProperties($val, $lenient);
125
126
        return $field;
127
    }
128
129
    public function inferProperties($val, $lenient)
130
    {
131
        // should be implemented by extending classes
132
        // allows adding / modfiying descriptor properties based on the given value
133
        $this->descriptor->type = $this->type();
134
    }
135
136
    /**
137
     * @param mixed $val
138
     *
139
     * @return mixed
140
     *
141
     * @throws \frictionlessdata\tableschema\Exceptions\FieldValidationException;
142
     */
143
    final public function castValue($val)
144
    {
145
        if ($this->isEmptyValue($val)) {
146
            if ($this->required()) {
147
                throw $this->getValidationException('field is required', $val);
148
            }
149
150
            return null;
151
        } else {
152
            $val = $this->validateCastValue($val);
153
            if (!$this->constraintsDisabled) {
154
                $validationErrors = $this->checkConstraints($val);
155
                if (count($validationErrors) > 0) {
156
                    throw new FieldValidationException($validationErrors);
157
                }
158
            }
159
160
            return $val;
161
        }
162
    }
163
164
    public function validateValue($val)
165
    {
166
        try {
167
            $this->castValue($val);
168
169
            return [];
170
        } catch (FieldValidationException $e) {
171
            return $e->validationErrors;
172
        }
173
    }
174
175
    /**
176
     * get a unique identifier for this field
177
     * used in the inferring process
178
     * this is usually the type, but can be modified to support more advanced inferring process.
179
     *
180
     * @param bool @lenient
181
     *
182
     * @return string
183
     */
184
    public function getInferIdentifier($lenient = false)
185
    {
186
        return $this->type();
187
    }
188
189
    /**
190
     * should be implemented by extending classes to return the table schema type of this field.
191
     *
192
     * @return string
193
     */
194
    public static function type()
195
    {
196
        throw new \Exception('must be implemented by extending classes');
197
    }
198
199
    protected $descriptor;
200
    protected $constraintsDisabled = false;
201
202
    protected function getValidationException($errorMsg = null, $val = null)
203
    {
204
        return new FieldValidationException([
205
            new SchemaValidationError(SchemaValidationError::FIELD_VALIDATION, [
206
                'field' => isset($this->descriptor()->name) ? $this->name() : 'unknown',
207
                'value' => $val,
208
                'error' => is_null($errorMsg) ? 'invalid value' : $errorMsg,
209
            ]),
210
        ]);
211
    }
212
213
    protected function isEmptyValue($val)
214
    {
215
        return is_null($val);
216
    }
217
218
    /**
219
     * @param mixed $val
220
     *
221
     * @return mixed
222
     *
223
     * @throws \frictionlessdata\tableschema\Exceptions\FieldValidationException;
224
     */
225
    // extending classes should extend this method
226
    // value is guaranteed not to be an empty value, that is handled elsewhere
227
    // should raise FieldValidationException on any validation errors
228
    // can use getValidationException function to get a simple exception with single validation error message
229
    // you can also throw an exception with multiple validation errors manually
230
    abstract protected function validateCastValue($val);
231
232
    protected function checkConstraints($val)
233
    {
234
        $validationErrors = [];
235
        $allowedValues = $this->getAllowedValues();
236
        if (!empty($allowedValues) && !$this->checkAllowedValues($allowedValues, $val)) {
237
            $validationErrors[] = new SchemaValidationError(SchemaValidationError::FIELD_VALIDATION, [
238
                'field' => $this->name(),
239
                'value' => $val,
240
                'error' => 'value not in enum',
241
            ]);
242
        }
243
        $constraints = $this->constraints();
244 View Code Duplication
        if (isset($constraints->pattern)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
            if (!$this->checkPatternConstraint($val, $constraints->pattern)) {
246
                $validationErrors[] = new SchemaValidationError(SchemaValidationError::FIELD_VALIDATION, [
247
                    'field' => $this->name(),
248
                    'value' => $val,
249
                    'error' => 'value does not match pattern',
250
                ]);
251
            }
252
        }
253 View Code Duplication
        if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
254
            isset($constraints->minimum)
255
            && !$this->checkMinimumConstraint($val, $this->castValueNoConstraints($constraints->minimum))
256
        ) {
257
            $validationErrors[] = new SchemaValidationError(SchemaValidationError::FIELD_VALIDATION, [
258
                'field' => $this->name(),
259
                'value' => $val,
260
                'error' => 'value is below minimum',
261
            ]);
262
        }
263 View Code Duplication
        if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
264
            isset($constraints->maximum)
265
            && !$this->checkMaximumConstraint($val, $this->castValueNoConstraints($constraints->maximum))
266
        ) {
267
            $validationErrors[] = new SchemaValidationError(SchemaValidationError::FIELD_VALIDATION, [
268
                'field' => $this->name(),
269
                'value' => $val,
270
                'error' => 'value is above maximum',
271
            ]);
272
        }
273 View Code Duplication
        if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
274
            isset($constraints->minLength) && !$this->checkMinLengthConstraint($val, $constraints->minLength)
275
        ) {
276
            $validationErrors[] = new SchemaValidationError(SchemaValidationError::FIELD_VALIDATION, [
277
                'field' => $this->name(),
278
                'value' => $val,
279
                'error' => 'value is below minimum length',
280
            ]);
281
        }
282 View Code Duplication
        if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
283
            isset($constraints->maxLength) && !$this->checkMaxLengthConstraint($val, $constraints->maxLength)
284
        ) {
285
            $validationErrors[] = new SchemaValidationError(SchemaValidationError::FIELD_VALIDATION, [
286
                'field' => $this->name(),
287
                'value' => $val,
288
                'error' => 'value is above maximum length',
289
            ]);
290
        }
291
292
        return $validationErrors;
293
    }
294
295
    protected function checkPatternConstraint($val, $pattern)
296
    {
297
        return preg_match('/^'.$pattern.'$/', $val) === 1;
298
    }
299
300
    protected function checkMinimumConstraint($val, $minConstraint)
301
    {
302
        return $val >= $minConstraint;
303
    }
304
305
    protected function checkMaximumConstraint($val, $maxConstraint)
306
    {
307
        return $val <= $maxConstraint;
308
    }
309
310
    protected function getLengthForConstraint($val)
311
    {
312
        if (is_string($val)) {
313
            return strlen($val);
314
        } elseif (is_array($val)) {
315
            return count($val);
316
        } elseif (is_object($val)) {
317
            return count((array) $val);
318
        } else {
319
            throw $this->getValidationException('invalid value for length constraint', $val);
320
        }
321
    }
322
323
    protected function checkMinLengthConstraint($val, $minLength)
324
    {
325
        return $this->getLengthForConstraint($val) >= $minLength;
326
    }
327
328
    protected function checkMaxLengthConstraint($val, $maxLength)
329
    {
330
        return $this->getLengthForConstraint($val) <= $maxLength;
331
    }
332
333
    protected function getAllowedValues()
334
    {
335
        $allowedValues = [];
336
        foreach ($this->enum() as $val) {
337
            $allowedValues[] = $this->castValueNoConstraints($val);
338
        }
339
340
        return $allowedValues;
341
    }
342
343
    protected function checkAllowedValues($allowedValues, $val)
344
    {
345
        return in_array($val, $allowedValues, !is_object($val));
346
    }
347
348
    protected function castValueNoConstraints($val)
349
    {
350
        $this->disableConstraints();
351
        $val = $this->castValue($val);
352
        $this->constraintsDisabled = false;
353
354
        return $val;
355
    }
356
}
357